Skip to content

Let the direct-provider inventory see a call reached through an accessor - #12662

Merged
Git-on-my-level merged 1 commit into
mainfrom
fix/direct-provider-scanner-accessor-indirection
Sep 3, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
fix/direct-provider-scanner-accessor-indirection

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

The direct-provider inventory stopped seeing a direct provider call

backend/tests/unit/test_llm_gateway_coverage_guardrails.py::test_direct_provider_usage_stays_inside_approved_boundaries fails on main today. Not on violations — on stale_allowlist. The allowlist says utils/other/chat_file.py makes direct openai.chat.completions calls; the scanner no longer detects them.

The calls are still there. They moved behind accessors:

_async_openai: AsyncOpenAI | None = None

def _get_async_openai() -> AsyncOpenAI: ...
def _get_sync_openai() -> Any: return openai

await _get_async_openai().chat.completions.create(...)   # ~338, ~346
_get_sync_openai().chat.completions.create(...)          # ~390, ~397

_dotted_name walks an attribute chain and returns node.attr when the receiver does not resolve, so _get_async_openai().chat.completions.create reads as the unowned chat.completions.create and matches no provider prefix. The entry became stale to the scanner while staying true in the code — which is the worst state for an inventory to be in, and why deleting the entry to get a green check would have been the wrong fix.

What changed

  • _provider_accessors resolves a module-level function to a provider root by any of three signals, all of which appear in chat_file.py: the return annotation (-> AsyncOpenAI), returning an imported provider module (return openai), or returning a name bound to a direct constructor call (the global _async_openai lazy singleton). DIRECT_PROVIDER_ROOTS is derived from DIRECT_CONSTRUCTOR_NAMES so the two cannot drift.
  • _dotted_name_through_accessors re-reads a call chain with the accessor substituted for its root, and returns None rather than a bare attribute when the receiver is unresolvable — so it never invents a name.
  • _direct_provider_uses tries the plain walk first and only falls back to the accessor re-read when nothing matched. Existing detections are untouched.
  • The inventory now records the second direct path. docs/llm/model_endpoint_inventory.yaml said direct OpenAI happens "only when OMI_LLM_GATEWAY_FEATURE_MODE is off". It also happens on the is_gateway_model_not_found degrade with feature mode on, and that request is not recorded in llm_gateway_attempts and carries no lane accounting. Both file-chat surfaces now say so.

Scope of the widening, measured

Scanned every file the guardrail scans, with and without the accessor re-read:

NEWLY VISIBLE:  utils/other/chat_file.py  openai.chat.completions
lost:           (none)
newly visible NOT in allowlist: (none)

One site, already allowlisted. No detection lost, no new violation introduced anywhere in backend/.

Automatic-or-dead check

test_direct_provider_scan_sees_through_a_provider_accessor runs the scanner over a synthetic module exercising all three resolution signals, so it stays meaningful if chat_file.py changes. test_direct_provider_scan_reports_the_file_chat_direct_fallback pins the live site, because an inventory that silently stops detecting a real direct provider call is worse than one that never had the entry.

Red-proofs applied and seen red, then reverted:

Mutation Result
drop the accessor re-read in _direct_provider_uses all three tests red
_provider_accessors returns an empty map all three tests red

11 passed in that file; 27 passed across it plus test_chat_file_gateway_surface.py and test_chat_file_completions.py.

Cut list

  • Ledgering the model-not-found degrade, or gating it. It is recorded here, not changed: file chat is an allowlisted basic-plan feature, so this is an attribution gap rather than an authorization one, and the fix belongs to whoever owns the degrade's cost story.
  • Teaching the scanner to follow accessors across module boundaries. Every case found in backend/ today is module-local.

Line-count ratchet

No product source grew. The only non-test change is a documentation line in docs/llm/model_endpoint_inventory.yaml.

Product invariants

  • INV-DATA-1 — no deployment authority, credential or routing change. The scanner is a test; the inventory is documentation.
  • INV-MEM-4 — no memory promotion, admission or Long-term authority path is touched.
  • INV-TASK-2 — no task-capture authority path is touched.

What this was

A static inventory lost sight of the call its own allowlist describes, because the matcher was a literal attribute chain and ordinary refactoring moved the call behind an accessor. The allowlist entry that stayed behind is what turned a silent coverage loss into a visible failure — the check was right to be red.

🤖 Generated with Claude Code

Review in cubic

test_direct_provider_usage_stays_inside_approved_boundaries fails on main,
and not on violations: on stale_allowlist. The allowlist says chat_file.py
makes direct openai.chat.completions calls and the scanner no longer finds
them. The calls are still there; they moved behind _get_async_openai() and
_get_sync_openai(). _dotted_name returns a bare attribute when the receiver
does not resolve, so the chain read as the unowned chat.completions.create
and matched no provider prefix.

The entry was stale to the scanner and true in the code, which is the worst
state for an inventory: deleting it for a green check would have made the
record less honest than the failure.

Resolve a module-level accessor to its provider root by return annotation,
by a returned provider module, or by a returned name bound to a constructor
call, and re-read a call chain that way only after the plain walk matched
nothing. Measured across every scanned file: one newly visible site, already
allowlisted, none lost.

Also record the second direct path in the inventory. It said direct OpenAI
happens only when OMI_LLM_GATEWAY_FEATURE_MODE is off; it also happens on the
is_gateway_model_not_found degrade with feature mode on, and that request
reaches no llm_gateway_attempts row.

Co-Authored-By: Claude Opus 5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 2 files

Confidence score: 3/5

  • backend/tests/unit/test_llm_gateway_coverage_guardrails.py keys accessor roots only by function name, so same-named class or nested methods can overwrite one another and misclassify call chains; preserve lexical scope during collection and resolution.
  • backend/tests/unit/test_llm_gateway_coverage_guardrails.py records local constructor assignments as module-level bindings, which can falsely classify an accessor returning that name as a provider accessor; track assignment scope before updating bound.
  • The probe coverage in backend/tests/unit/test_llm_gateway_coverage_guardrails.py claims to exercise three signals but covers only two, leaving _get_async_openai... behavior insufficiently validated; add a probe for the missing direct-constructor binding case.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/tests/unit/test_llm_gateway_coverage_guardrails.py">

<violation number="1" location="backend/tests/unit/test_llm_gateway_coverage_guardrails.py:206">
P3: The probe test claims "all three appear in the probe below" (return annotation, returning an imported module, returning a name bound to a direct constructor call), but only two signals are exercised. `_get_async_openai` resolves through its `-> AsyncOpenAI` return annotation (signal 1), and `_get_sync_openai` resolves by returning the `openai` module (signal 2). No accessor in the probe or in `chat_file.py` resolves via the third signal (returning a name in `_module_level_constructor_bindings`), because in both files the accessor either has a return annotation or returns the module directly. As a result the bound-singleton-return path in `_provider_accessors` has no effective test coverage, and a regression that breaks it would pass both new tests and the live-site test unchanged. Add an unannotated accessor that returns the lazily constructed singleton (e.g. `def _get_async_openai_untyped():
    global _async_openai
    ...
    return _async_openai`) and assert against `_get_async_openai_untyped().chat.completions.create`, or drop the stale claim.</violation>

<violation number="2" location="backend/tests/unit/test_llm_gateway_coverage_guardrails.py:381">
P2: Local constructor assignments are recorded as module-level bindings, so an accessor returning the same name can be falsely classified as a provider accessor. Track assignment scope before adding names to `bound`.</violation>

<violation number="3" location="backend/tests/unit/test_llm_gateway_coverage_guardrails.py:419">
P2: Accessor roots are keyed only by function name, so class or nested methods with the same name overwrite each other and misclassify call chains. Preserve lexical scope when collecting and resolving accessors.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

if root is not None:
break
if root is not None:
accessors[node.name] = root

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Accessor roots are keyed only by function name, so class or nested methods with the same name overwrite each other and misclassify call chains. Preserve lexical scope when collecting and resolving accessors.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_llm_gateway_coverage_guardrails.py, line 419:

<comment>Accessor roots are keyed only by function name, so class or nested methods with the same name overwrite each other and misclassify call chains. Preserve lexical scope when collecting and resolving accessors.</comment>

<file context>
@@ -268,6 +341,100 @@ def _direct_provider_uses(rel: str, tree: ast.AST) -> set[DirectUse]:
+                if root is not None:
+                    break
+        if root is not None:
+            accessors[node.name] = root
+    return accessors
+
</file context>

targets = node.targets if isinstance(node, ast.Assign) else [node.target]
for target in targets:
if isinstance(target, ast.Name):
bound[target.id] = root

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Local constructor assignments are recorded as module-level bindings, so an accessor returning the same name can be falsely classified as a provider accessor. Track assignment scope before adding names to bound.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_llm_gateway_coverage_guardrails.py, line 381:

<comment>Local constructor assignments are recorded as module-level bindings, so an accessor returning the same name can be falsely classified as a provider accessor. Track assignment scope before adding names to `bound`.</comment>

<file context>
@@ -268,6 +341,100 @@ def _direct_provider_uses(rel: str, tree: ast.AST) -> set[DirectUse]:
+        targets = node.targets if isinstance(node, ast.Assign) else [node.target]
+        for target in targets:
+            if isinstance(target, ast.Name):
+                bound[target.id] = root
+    return bound
+
</file context>


The accessor resolves by return annotation, by returning an imported
provider module, or by returning a name bound to a constructor call —
all three appear in the probe below.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The probe test claims "all three appear in the probe below" (return annotation, returning an imported module, returning a name bound to a direct constructor call), but only two signals are exercised. _get_async_openai resolves through its -> AsyncOpenAI return annotation (signal 1), and _get_sync_openai resolves by returning the openai module (signal 2). No accessor in the probe or in chat_file.py resolves via the third signal (returning a name in _module_level_constructor_bindings), because in both files the accessor either has a return annotation or returns the module directly. As a result the bound-singleton-return path in _provider_accessors has no effective test coverage, and a regression that breaks it would pass both new tests and the live-site test unchanged. Add an unannotated accessor that returns the lazily constructed singleton (e.g. def _get_async_openai_untyped(): global _async_openai ... return _async_openai) and assert against _get_async_openai_untyped().chat.completions.create, or drop the stale claim.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_llm_gateway_coverage_guardrails.py, line 206:

<comment>The probe test claims "all three appear in the probe below" (return annotation, returning an imported module, returning a name bound to a direct constructor call), but only two signals are exercised. `_get_async_openai` resolves through its `-> AsyncOpenAI` return annotation (signal 1), and `_get_sync_openai` resolves by returning the `openai` module (signal 2). No accessor in the probe or in `chat_file.py` resolves via the third signal (returning a name in `_module_level_constructor_bindings`), because in both files the accessor either has a return annotation or returns the module directly. As a result the bound-singleton-return path in `_provider_accessors` has no effective test coverage, and a regression that breaks it would pass both new tests and the live-site test unchanged. Add an unannotated accessor that returns the lazily constructed singleton (e.g. `def _get_async_openai_untyped():
    global _async_openai
    ...
    return _async_openai`) and assert against `_get_async_openai_untyped().chat.completions.create`, or drop the stale claim.</comment>

<file context>
@@ -166,6 +167,70 @@ def test_inventory_surfaces_have_status_guardrails_and_resolvable_code_paths():
+
+    The accessor resolves by return annotation, by returning an imported
+    provider module, or by returning a name bound to a constructor call —
+    all three appear in the probe below.
+
+    red-proof: drop the accessor re-read in ``_direct_provider_uses`` and both
</file context>

@Git-on-my-level
Git-on-my-level merged commit d88e50a into main Sep 3, 2026
43 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/direct-provider-scanner-accessor-indirection branch September 3, 2026 07:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant