-
Notifications
You must be signed in to change notification settings - Fork 4
Improves/Fixes judge prompt; testing for templates #100
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jtoman
wants to merge
7
commits into
master
Choose a base branch
from
jtoman/judge-prompt-fixups
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
29c81c8
checkpoint
jtoman 63908db
Judge prompt improvements
jtoman af9bf1d
phew
jtoman 516747a
finally
jtoman 5570e2a
fuzz optimizations
jtoman 602711e
oops, don't want to add this here
jtoman 7816fe3
didn't mean to include this here either
jtoman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| """ | ||
| Module for introspection of the composer module. Stay away | ||
| """ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| from typing import Iterable, get_args | ||
| import sys | ||
| import importlib | ||
| from .types import TemplateDecl | ||
|
|
||
| def resolve_params(s: TemplateDecl) -> Iterable[type]: | ||
| importlib.import_module(s.module) | ||
| t = sys.modules[s.module].__dict__[s.qualname] | ||
|
|
||
| res = getattr(t, "__orig_class__") | ||
| for i in get_args(res): | ||
| assert isinstance(i, type), f"got {i} {type(i)}" | ||
| yield i |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import ast | ||
| import pathlib | ||
|
|
||
| from composer.meta.types import TemplateSort, TemplateDecl | ||
|
|
||
| PACKAGE = "composer" | ||
| FULL_TYPE_NAME = "TypedTemplate" | ||
| PARTIAL_NAME = "PartialTemplate" | ||
| TEMPLATE_ARG = 0 | ||
|
|
||
| TYPE_NAMES = (FULL_TYPE_NAME, PARTIAL_NAME) | ||
|
|
||
| def _names_type(node: ast.expr) -> TemplateSort | None: | ||
| """True if `node` textually refers to TYPE_NAME: bare, attribute, or subscripted.""" | ||
| if isinstance(node, ast.Name): | ||
| if node.id in TYPE_NAMES: | ||
| return node.id | ||
| if isinstance(node, ast.Attribute): | ||
| if node.attr in TYPE_NAMES: | ||
| return node.attr | ||
| if isinstance(node, ast.Subscript): # TYPE_NAME[...] generic annotation | ||
| return _names_type(node.value) | ||
| return None | ||
|
|
||
| def _extract_template(value: ast.expr | None) -> str | None: | ||
| """Pull the template-name argument (positional or kwarg per TEMPLATE_ARG).""" | ||
| if not isinstance(value, ast.Call): | ||
| return None | ||
| arg = value.args[TEMPLATE_ARG] if len(value.args) > TEMPLATE_ARG else None | ||
| if arg is None: | ||
| return None | ||
| if isinstance(arg, ast.Constant) and isinstance(arg.value, str): | ||
| return arg.value | ||
| raise ValueError( | ||
| f"template argument must be a string literal so the static " | ||
| f"scanner can see it (got {ast.dump(arg)[:60]})" | ||
| ) | ||
|
|
||
| def _match_statement(stmt: ast.stmt) -> tuple[str, TemplateSort, ast.expr | None] | None: | ||
| """Return (variable_name, value_expr_or_None) if `stmt` declares a TYPE_NAME.""" | ||
| if isinstance(stmt, ast.AnnAssign): | ||
| if (ty_name := _names_type(stmt.annotation)) is not None and isinstance(stmt.target, ast.Name): | ||
| return stmt.target.id, ty_name, stmt.value | ||
| return None | ||
| if isinstance(stmt, ast.Assign): | ||
| if (isinstance(stmt.value, ast.Call) and (ty_sort := _names_type(stmt.value.func)) is not None | ||
| and len(stmt.targets) == 1 and isinstance(stmt.targets[0], ast.Name)): | ||
| return stmt.targets[0].id, ty_sort, stmt.value | ||
| return None | ||
|
|
||
| def iter_declarations(package_dir: pathlib.Path, skips: tuple[pathlib.Path, ...]): | ||
| """Yield (module_name, var_name, template_or_None) for each top-level declaration. | ||
|
|
||
| Purely textual/AST -- aliased type names (``from registry import | ||
| TemplateDecl as TD``) or declarations built in loops will NOT be found. | ||
| Keep declaration style boring. | ||
| """ | ||
| base = package_dir.parent | ||
| for py in sorted(package_dir.rglob("*.py")): | ||
| if any(py.is_relative_to(skip) for skip in skips): | ||
| continue | ||
| source = py.read_text(encoding="utf-8") | ||
| if FULL_TYPE_NAME not in source and PARTIAL_NAME not in source: # cheap pre-filter before parsing | ||
| continue | ||
| tree = ast.parse(source, filename=str(py)) | ||
| module_name = ".".join(py.relative_to(base).with_suffix("").parts) | ||
|
|
||
| if module_name.endswith(".__init__"): | ||
| module_name = module_name.removesuffix(".__init__") | ||
| for stmt in tree.body: # top level ONLY -- no ast.walk on purpose | ||
| match = _match_statement(stmt) | ||
| if match is None: | ||
| continue | ||
| var_name, ty_sort, value = match | ||
| try: | ||
| template = _extract_template(value) | ||
| except ValueError as exc: | ||
| raise ValueError(f"{py}:{stmt.lineno}: {exc}") from None | ||
| yield module_name, var_name, template, ty_sort | ||
|
|
||
| def build_manifest(root_package: pathlib.Path, skips: tuple[pathlib.Path, ...]) -> dict[str, TemplateDecl]: | ||
| """Scan and return {"module:VAR": {"module", "qualname", "template"?}}.""" | ||
| manifest: dict[str, TemplateDecl] = {} | ||
| templates_seen: dict[str, str] = {} | ||
| for module_name, var_name, template, ty_sort in iter_declarations(root_package, skips): | ||
| key = f"{module_name}:{var_name}" | ||
| if key in manifest: | ||
| raise ValueError(f"{key} declared twice at module top level") | ||
| if template is None: | ||
| raise ValueError(f"No template name extracted for {key}") | ||
| if template in templates_seen: | ||
| raise ValueError( | ||
| f"template {template!r} declared by both " | ||
| f"{templates_seen[template]} and {key}" | ||
| ) | ||
| templates_seen[template] = key | ||
| manifest[key] = TemplateDecl( | ||
| qualname=var_name, module=module_name, ty_sort=ty_sort, template_name=template | ||
| ) | ||
| return manifest |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| from typing import Literal | ||
| from pydantic import BaseModel, TypeAdapter | ||
|
|
||
| type TemplateSort = Literal["TypedTemplate", "PartialTemplate"] | ||
|
|
||
| class TemplateDecl(BaseModel): | ||
| module: str | ||
| qualname: str | ||
| template_name: str | ||
| ty_sort: TemplateSort | ||
|
|
||
| Manifest = TypeAdapter(dict[str, TemplateDecl]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import importlib.util | ||
| import pathlib | ||
| import sys | ||
|
|
||
| from composer.meta.types import TemplateDecl, Manifest | ||
| from composer.meta.templates import build_manifest | ||
|
|
||
| # -------------------------------------------------------------------------- | ||
| # STUBS -- fill these in for your repo | ||
| # -------------------------------------------------------------------------- | ||
|
Comment on lines
+8
to
+10
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove this comment?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Haha this definitely isn't copy pasted from a stub I asked Claude to write bad_poker_face.gif |
||
| PACKAGE = "composer" | ||
|
|
||
| _THIS_DIR = pathlib.Path(__file__).parent | ||
|
|
||
| def _package_root() -> pathlib.Path: | ||
| """Locate PACKAGE on disk without importing it. | ||
|
|
||
| find_spec on a *top-level* name only consults path finders; the module is | ||
| never executed. (Dotted names would import parents -- don't pass those.) | ||
| """ | ||
| spec = importlib.util.find_spec(PACKAGE) | ||
| if spec is None or not spec.submodule_search_locations: | ||
| raise SystemExit(f"cannot locate package {PACKAGE!r} on sys.path") | ||
| to_ret = pathlib.Path(next(iter(spec.submodule_search_locations))) | ||
| assert pathlib.Path(__file__).is_relative_to(to_ret) | ||
| return to_ret | ||
|
|
||
| def _repo_root() -> pathlib.Path: | ||
| return _package_root().parent | ||
|
|
||
| def render_manifest(manifest: dict[str, TemplateDecl]) -> str: | ||
| """Canonical, diff-stable serialization (sorted keys, trailing newline).""" | ||
| return Manifest.dump_json(manifest, indent=2).decode("utf-8") | ||
|
|
||
| def _main(): | ||
| (_repo_root() / "template_manifest.json").write_text( | ||
| render_manifest(build_manifest(_package_root(), (_THIS_DIR,))) | ||
| ) | ||
|
|
||
| if __name__ == "__main__": | ||
| sys.exit(_main()) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So I guess the idea is to run this any time we make a change that would affect the manifest? Can we have a CI workflow that checks that the manifest is up-to-date?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It exists brother. test_manifest or something