Repository navigation
Fix main: assert the tool loop controller catalog structurally, not by source proximity - #9809
Conversation
…source proximity test_tool_loop_controllers_are_built_from_the_sanitized_catalog scraped a fixed 200-character window after each ToolLoopController( construction site and required the text of the sweep to fall inside it. #9773 hoisted the very same sweep one statement up into a controller_tools local so it could short-circuit on tool_choice == "none", which emptied the window and turned main red without changing a single thing about what reaches the controller. Resolve the tools argument through the AST instead: local assignments, conditional expressions and boolean operands are followed until the value terminates in the sweep, in a catalog builder that wraps it, or in an empty/None catalog. Reformatting, renaming the local or rewrapping the call all still resolve; handing the controller the raw catalog does not. Two supporting tests hold up the parts the resolver takes on trust: every production caller that supplies renderable_tools must pass a swept catalog, and the catalog builders must sweep and must never return their own tools argument.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dd78aeddc1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| profile = call.args[2] if len(call.args) >= 3 else None | ||
| for keyword in call.keywords: | ||
| if keyword.arg == "markup": | ||
| profile = keyword.value | ||
| if profile is None: | ||
| return False | ||
| return not (isinstance(profile, ast.Constant) and profile.value is None) |
There was a problem hiding this comment.
Require the renderer's actual markup profile
When a sweep is changed to use a stale or unrelated profile, such as neutralize_tool_descriptions(tools, None, other_profile), this helper still returns true because it checks only that the third argument is not a literal None. The controller can then retain tools containing delimiters recognized by the actual renderer, recreating the authorization mismatch this test is intended to catch without failing CI; verify the module-specific profile (markup or self.markup_profile) or trace its provenance instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one.
Pinning the assertion to markup or self.markup_profile is the exact defect this PR exists to remove. The test that was red on main asserted on identifiers appearing near the construction site, and #9773 broke it by hoisting the identical sweep with the identical arguments one statement up. Requiring a specific variable name puts that back: renaming self.markup_profile, or threading the profile through a local, goes red with no behaviour change, and a test a rename can break is not testing what it claims.
What is load-bearing is that a profile was supplied at all rather than defaulted, because that is the failure with a mechanism behind it: sweeping under the default profile drops what the renderer keeps and keeps what it drops. _ctrl_sweep_carries_profile asserts that, and _neutralize_tool_descriptions(tools, None, None) is RED in the mutation set.
The residue you describe needs somebody to substitute a DIFFERENT live profile object. There is no second profile in scope at either site to substitute, and distinguishing "this turn's profile" from "some profile" is not something an AST can decide without going back to naming.
| assert called & _CATALOG_PRODUCERS, f"{producer} no longer sweeps the catalog" | ||
| raw = node.args.args[0].arg | ||
| for statement in ast.walk(node): | ||
| if isinstance(statement, ast.Return) and isinstance(statement.value, ast.Name): | ||
| assert statement.value.id != raw, ( |
There was a problem hiding this comment.
Trace every producer return to the sanitizing call
When a catalog producer calls a sanitizer but later returns the raw catalog indirectly, this check still passes: for example, catalog = tools; neutralize_tool_descriptions(...); return catalog satisfies the call-set assertion and avoids the direct return tools check. Since _ctrl_resolve unconditionally trusts calls to these producers, such a regression would let an unsanitized controller catalog pass the new guard; resolve all return expressions back to a sanitizer rather than rejecting only a bare parameter name.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, and the prescribed check is the reason.
I ran your remedy: _ctrl_resolve over every return inside the two producers, which is what "resolve all return expressions back to a sanitizer" asks for. It fails 6 of the 10 returns in code that is correct and does sweep:
renderable_tool_catalog:1785 return _unadvertised() -> not a sanitized catalog
renderable_tool_catalog:1798 return safe if ... else _unadvertised()
renderable_tool_catalog:1800 return _unadvertised()
renderable_tool_catalog:1814 return safe if ... else narrowed -> ListComp is not resolvable
renderable_tool_catalog_for_targets:1734 return catalog
renderable_tool_catalog_for_targets:1735 return catalog
The last two are literally the shape you describe -- catalog = tools and later return catalog -- and they are correct there: the loop rebinds catalog through renderable_tool_catalog on every live target. Passing the check would need the resolver to model comprehensions that filter an already-swept list, and nested helpers that return []. That is a lot of machinery whose failure mode is a red build on correct code.
The guard as written is deliberately the weaker, supporting one: the load-bearing assertion is the resolver at the construction sites, which does not trust these producers about anything except that they are the ones that sweep. This check exists to notice if one stops sweeping or starts handing its own argument straight back, and it still does that.
| for keyword in node.keywords: | ||
| if keyword.arg not in wanted: | ||
| continue |
There was a problem hiding this comment.
Inspect expanded keyword arguments at contract call sites
When a production caller supplies the contract through expansion, for example run_safetensors_tool_loop(**{"renderable_tools": tools, ...}), its AST keyword has arg is None, so this loop never examines the raw catalog. The existing direct callers still keep callers nonzero, allowing the unsafe additional caller to pass a test that claims to validate every supplied renderable_tools value; resolve literal mappings and trace named **kwargs where possible.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one.
run_safetensors_tool_loop(**{"renderable_tools": tools, ...}) is not a shape this codebase contains or is heading towards -- every production caller passes the contract as a plain keyword, which is why callers is nonzero. Resolving literal mappings and tracing named **kwargs is real machinery added for a call style nobody writes, and it would still stop at the first **kwargs forwarded through a wrapper, so it buys a bounded amount of coverage for an unbounded amount of resolver.
The narrower reading of the item -- that assert callers cannot distinguish "every caller checked" from "some callers checked" -- is fair, but it is the same statement the surrounding test makes in its name and docstring, and the enforcement that matters is at the construction site: renderable_tools only earns its contract because _SANITIZED_BY_CONTRACT names it, and every value flowing into the controller from it is resolved there too.
| def _ctrl_called_name(call, aliases): | ||
| func = call.func | ||
| name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None) | ||
| return aliases.get(name, name) |
There was a problem hiding this comment.
Resolve the sanitizer's callable identity
When a call merely ends in the trusted name, such as passthrough.neutralize_tool_descriptions(tools, None, markup), _ctrl_called_name treats it as the real sanitizer without resolving the attribute's owner; a locally shadowed imported alias has the same problem. Either form can return the raw catalog while _ctrl_resolve reports that it was swept, so verify that the callable resolves to the imported helper rather than comparing only its final identifier.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, and the attribute form is deliberate.
neutralize_tool_descriptions lives in chat_template_helpers, and chat_template_helpers.neutralize_tool_descriptions(tools, None, markup) is how a module-qualified import of the REAL sanitizer is written. Matching on the final identifier is what lets that keep working; resolving the owner would need import-graph resolution across the package to accept it, and rejecting attribute calls outright would fail correct code.
The residue is a same-named function on some other object, taking the same three positional arguments in the same order. There is nothing like it in the tree -- grep -rn '\\.neutralize_tool_descriptions\\|\\.renderable_tool_catalog' studio/backend --include=*.py returns nothing at all -- so both real call sites are bare names, one of them through the as alias _ctrl_aliases exists to follow.
Worth noting the direction of travel: the guard this replaced was "neutralize_tool_descriptions" in window, a plain substring match over 200 characters of source. Every shape you describe passed that too.
… in place Two shapes reached the controller past the new dataflow resolver. A bare tools = None resolves (there is no catalog to sanitize) but sets _restrict_to_allowed = False, so prepare_call stops checking names at all and every tool the sweep dropped is executable again. The resolver now reports whether a value can hold a catalog as well as whether it is sanitized, and the construction sites require both; None still resolves as the branch of an if-expression that has nothing to authorize, which is the shape both loops use. A catalog bound to an empty literal and then filled in place -- controller_tools = []; controller_tools.extend(tools) -- resolved on the literal, because the binding table only sees rebinds. A resolved name that is appended to, extended, updated or assigned through a subscript is refused instead of modelled. Mutation proof over the two loops: raw catalog, raw catalog via the other loop, sweep without a markup profile, unrestricted controller, empty catalog filled in place, and catalog assigned by subscript all go red; a pure reformat of the construction site and unmodified head stay green.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e1ae570e56
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| isinstance(child, ast.Call) | ||
| and isinstance(child.func, ast.Attribute) | ||
| and child.func.attr in _CTRL_MUTATORS | ||
| and isinstance(child.func.value, ast.Name) | ||
| ): | ||
| names.add(child.func.value.id) |
There was a problem hiding this comment.
Follow aliases when detecting in-place catalog mutation
Fresh evidence in the revised mutation handling is that it records only the receiver's immediate name. For example, catalog = []; alias = catalog; alias.extend(tools); ToolLoopController(tools=catalog) marks only alias as mutated, so resolving catalog approves the original empty literal even though the controller receives the raw tools added through the shared list. Track alias relationships or conservatively reject catalogs whose aliases are mutated.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one.
catalog = []; alias = catalog; alias.extend(tools) needs a deliberate two-step aliasing of a list nobody has a reason to alias, and none of the accidents this guard is built for produce it: the accident shapes are a dropped sweep, a hoisted sweep, an inverted predicate, a conditional sweep, an in-place fill. All five are RED. Tracking aliases means a points-to analysis over the enclosing function, which for llama_cpp.py is thousands of lines, and conservatively rejecting "any catalog whose alias is mutated" needs the alias set first, so it is the same analysis.
There is also a real cost to guessing here. Rejecting on any name that shares a binding with a mutated one would fire on unrelated locals in a function that long, and a guard that goes red on correct code is the failure mode this PR exists to remove.
The two shapes from the previous round that DID have an accident behind them are covered, and the four in cada0b2 are as well.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 361a4bc27c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return True, "swept at the construction site", True | ||
| if name in _CATALOG_PRODUCERS: | ||
| return True, f"built by {name}", True |
There was a problem hiding this comment.
Trace sanitizer inputs to the selected tool catalog
When the sweep or a trusted producer is called with an unrelated catalog, these unconditional returns accept it without resolving the first argument. For example, a caller can pass tools=request_tools alongside renderable_tools=renderable_tool_catalog(privileged_tools, ...); both the caller check and controller check remain green even though the resulting controller authorizes names outside the request's selected catalog. Require trusted calls to derive from the corresponding tools root, allowing only proven narrowing transformations.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one: it is a different property, and a much larger one.
The guard's claim is that the controller catalog was SWEPT. What you describe is that it was swept AND derives from this request's own selection -- provenance, not sanitization. To check it the resolver would have to know which variable is "the request's tools" at an arbitrary call site, and "allowing only proven narrowing transformations" means modelling every filter, comprehension and intersection a catalog passes through. The producer-return experiment from the last round already showed where that ends: _ctrl_resolve fails 6 of the 10 returns in renderable_tool_catalog and renderable_tool_catalog_for_targets, which are correct and do sweep, because of one list comprehension and one nested helper.
The concrete shape -- tools = request_tools with renderable_tools = renderable_tool_catalog(privileged_tools, ...) -- also has no caller: renderable_tools is supplied from the same catalog the loop is running, and there is no privileged_tools in the tree. If a divergence between the two ever becomes possible it wants its own invariant and its own test, not a widened definition of "sanitized" inside this one.
Which branch gates was decided by an or over the branches, so ToolLoopController(tools = None if tools else swept) passed: the swept branch gates while None is selected exactly when there IS a catalog. A non-gating branch now has to be guarded by the emptiness of the catalog the other branch narrows, followed through the binding rather than matched on the name, so unrestricted_tools = not tools still resolves and the inversion does not. A parameter that is also rebound kept only its rebindings, and the resolver is flow-insensitive, so if sanitize: tools = neutralize_tool_descriptions(...) vouched for the raw parameter on the other path. A rebound parameter now has to clear its contract as well, which also closes catalog = catalog vouching for itself through the cycle. Lambda was in _NESTED_SCOPES but not in the scope chain, so a lambda parameter resolved against the outer name it shadows at runtime. studio_tool_loop.py is a third construction site the guard never named. It drives an external provider and builds its controller from policy.tools, and external_provider.py sweeps only what it sends and only for the providers whose prompt this repo templates, keeping that result local. Closing it needs the transport to report whether it templated the prompt, which is a product change for its own PR, so it is recorded in _CONTROLLER_MODULES_OUT_OF_SCOPE with the reason and a new test fails on any FOURTH site that is in neither list. Mutation proof now at 8 breakages red, with the pure reformat and unmodified head green.
…assify per site The guard on the non-gating branch read only the sweep's first POSITIONAL argument, so respelling the same call as neutralize_tool_descriptions(tools = tools, markup = markup) left it with no root to match the predicate against and the safetensors site would have gone red on a pure refactor. That is the fragility this whole test exists to remove, reintroduced by the fix for it. The keyword spelling is now read as well, and it is a control in the mutation set rather than only an assertion. A boolean had no predicate to prove emptiness with and still took the OR of its operands, so tools = _authorized or None was accepted: short-circuit reaches None exactly when the sweep emptied the catalog, which is when the allowlist matters most. Every operand of a boolean now has to gate. The classification test keyed on the file name, so a SECOND controller inside studio_tool_loop.py, or a same-named module elsewhere in the tree, would have inherited the external-provider exemption. Sites are now keyed by path under studio/backend plus enclosing function. Mutation proof: 9 breakages red, 3 controls green.
The classification key was (path, enclosing function), so two constructors inside stream_with_studio_tools collapsed to one entry and a second one would have inherited the external-provider exemption instead of forcing a decision. The key now carries the number of sites that function holds. The count rather than a line number: a line moves when anything above it does, so the test would fail on an unrelated edit, which is the fragility this file exists to remove. The count moves only when a controller is added or removed, which is exactly the event that has to force the decision. Verified by adding a second constructor to the exempt function, which turns the test red naming (studio_tool_loop.py, stream_with_studio_tools, 2) as unclassified.
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…onstructor aliases A name with several bindings took the OR of them, so controller_tools = None followed by if enabled: controller_tools = neutralize_tool_descriptions(...) resolved as gating with the unrestricted path still reachable. A conditional expression carries a predicate that can prove there is nothing to authorize; separate assignments carry none, so every binding of a name now has to gate. The catalog roots the branch predicate is matched against were bare identifiers, so an inner helper whose parameter shadows the name the outer scope swept satisfied the proof with a different catalog. Each root now carries the scope that binds it, and a binding is followed in its OWN scope chain from that scope outward rather than in the call site's. controller_cls = ToolLoopController then controller_cls(tools = raw) was not recognised as a construction site at all, so it escaped the resolver and the classification test together. Assignment aliases of the tracked callables are followed like an as import, restricted to those names so unrelated locals cannot answer to a trusted one. Mutation proof: 11 breakages red, 3 controls green.
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Third and last of the main-red defects I know of.
Backend CI / (Python 3.13)andRepo tests (CPU)both collect this file, so every open Studio PR inherits the failure. Companions: #9802 (workflow guard not collected in the unfiltered job) and #9808 (locale parity).What is red
Not PR-specific. It fails on main and on every branch cut from it, including four unrelated contributors' PRs (#9798, #9797, #9796, #9788).
What turned it red
50f6ba2af(#9773, "Studio: honour forced tool_choice on local GGUF tool loops"). I bisected the marker across 60 commits ofllama_cpp.py: every commit through05cee801bpasses,50f6ba2afand everything after fails.The whole of its change at that site:
The test is at fault, not the product
The sanitization is still there, four lines above the construction site, and it is the exact same call with the exact same arguments. #9773 hoisted it into a local only so it could short-circuit to
[]ontool_choice == "none", which if anything narrows the catalog further. Nothing unsanitized reaches the controller, then or now.What broke is the test. It took a fixed 200-character slice of source text starting at
ToolLoopController(and required the sweep to be spelled inside it. Moving the identical call one statement up emptied the window. A formatter would have done the same: pre-commit.ci has been rewrappingllama_cpp.pylately, and any rewrap that pushes text past the 200-character mark breaks this assertion without changing behaviour at all. This is the same fragile-window class we already cleaned out of the host-defaults guard.Widening the window only moves the cliff, so I did not.
What replaces it
The assertion is now on the dataflow rather than on source proximity. For every
ToolLoopController(inllama_cpp.pyandsafetensors_agentic.py, thetoolsargument is resolved through the AST: local assignments, conditional expressions, boolean operands andlist()/tuple()wrappers are followed until the value terminates inneutralize_tool_descriptions(...), which additionally has to be given this turn's markup profile rather than the default,None/ an empty literal, which carry no catalog at all.asimports are resolved, soneutralize_tool_descriptions as _neutralize_tool_descriptionsstill counts, and scopes are walked innermost-first without descending into nested functions. Every binding of a name has to resolve, not just one, so a catalog that is swept on one branch and raw on another does not pass.Two supporting tests hold up what the resolver takes on trust:
test_the_sanitized_by_contract_catalog_is_sanitized_at_every_caller-renderable_toolsis the one catalog the safetensors loop accepts from its caller, so every production call site that supplies it is resolved by the same resolver.test_every_catalog_producer_returns_a_swept_catalog- the catalog builders must sweep, and must never hand their owntoolsargument straight back.Mutation proof
Deliberately broken, then reverted:
llama_cpp.pyhands the controller the rawtoolsllama_cpp.pysweeps without the markup profilesafetensors_agentic.pyhands the controller the rawtoolsrenderable_toolsrenderable_tool_catalogreturns its unswepttoolsThe last row is the point. The old assertion could not tell those two apart.
Tests
Same four files, same runner, run side by side.
origin/mainfailstest_tool_loop_controllers_are_built_from_the_sanitized_catalogplustest_text_only_vision_system_prompt_is_neutralizedandtest_vision_processor_render_is_neutralized; this branch fails only the latter two, which are pre-existing on this runner and unrelated to this change.