Skip to content

[codex] Add LLM gateway chat extraction pilot - #8427

Merged
Git-on-my-level merged 38 commits into
mainfrom
codex/llm-gateway
Jun 28, 2026
Merged

Git-on-my-level merged 38 commits into
mainfrom
codex/llm-gateway

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Jun 27, 2026 •

Copy link
Copy Markdown
Member

Summary

  • add a separate FastAPI LLM gateway with repo-local auto-route config, service auth, readiness, and OpenAI-compatible chat completions
  • route non-BYOK chat extraction requires_context through omi:auto:chat-structured first, with existing provider fallback on gateway miss or failure
  • add bounded Prometheus telemetry for chat extraction gateway success, fallback, and BYOK skip outcomes
  • document the LLM gateway architecture, rollout behavior, BYOK policy, and remaining migration boundaries

Validation

  • rtk pytest backend/tests/unit/test_llm_gateway_service.py backend/tests/unit/test_llm_gateway_config.py backend/tests/unit/test_llm_gateway_auth.py backend/tests/unit/test_llm_gateway_credentials.py backend/tests/unit/test_llm_gateway_validator.py backend/tests/unit/test_llm_gateway_resolver.py backend/tests/unit/test_llm_gateway_executor.py backend/tests/unit/test_llm_gateway_openai_provider.py backend/tests/unit/test_llm_gateway_openai_compatible.py backend/tests/unit/test_llm_gateway_readiness.py backend/tests/unit/test_llm_gateway_client_config.py backend/tests/unit/test_llm_gateway_route_refs.py backend/tests/unit/test_llm_gateway_dependencies.py backend/tests/unit/test_llm_gateway_chat_extraction_pilot.py -v (113 passed)
  • rtk bash backend/test-preflight.sh (passed with optional dependency warnings)
  • rtk python backend/scripts/scan_async_blockers.py (completed; reports existing unrelated blockers)

Notes

  • origin/main was already an ancestor of this branch after fetch, so no merge commit was needed.
  • backend/test.sh was not used for final validation because it invokes bare pytest in this shell; the equivalent gateway-focused tests were run through rtk pytest.

Review in cubic

@mintlify

mintlify Bot commented Jun 27, 2026

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
deepeninc 🟡 Building – Jun 27, 2026, 7:26 AM

💡 Tip: Enable Workflows to automatically generate PRs for you.

@mintlify

mintlify Bot commented Jun 27, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
omi 🟢 Ready View Preview Jun 27, 2026, 7:27 AM

💡 Tip: Enable Workflows to automatically generate PRs for you.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 47dad57cb5

ℹ️ 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".

Comment thread backend/utils/llm/gateway_client.py Resolved

@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.

10 issues found across 41 files

Confidence score: 2/5

  • backend/utils/llm/gateway_client.py uses synchronous httpx.post() inside an async path, which can block the event loop for up to the request timeout and stall health checks/autoscaling under load. This is the highest merge risk—move this call to the shared httpx.AsyncClient flow in utils/http_client.py before merging.
  • Validation gaps across backend/llm_gateway/gateway/validator.py, backend/llm_gateway/gateway/credentials.py, and backend/llm_gateway/gateway/resolver.py allow malformed inputs through and then return misleading downstream/provider errors (including wrong 404 vs invalid-request semantics). Tighten request validation (json_schema.name required, trimmed key_ref, blank model as invalid request) so clients get correct, actionable errors before merge.
  • backend/utils/llm/gateway_client.py does not fully normalize strict JSON Schema output (missing additionalProperties: false on object schemas), so otherwise valid structured-output calls can be rejected by strict gateway/provider validation. Normalize generated schemas recursively before dispatch to reduce production request failures.
  • backend/llm_gateway/gateway/executor.py ignores configured retry.max_attempts, and backend/llm_gateway/routers/openai_compatible.py maps error type to the same value as code, reducing retry resilience and OpenAI-format compatibility for clients. Respect per-route retry counts and correct type to category-level values before merging.

Note: This PR contains a large number of files. cubic only reviews up to 40 files per PR, so some files may not have been reviewed. cubic prioritizes the most important files to review.
On a pro plan you can use ultrareview for larger PRs.

Re-trigger cubic

Comment thread backend/utils/llm/gateway_client.py Resolved
Comment thread backend/llm_gateway/gateway/schemas.py Resolved
Comment thread backend/llm_gateway/gateway/executor.py Resolved
Comment thread backend/llm_gateway/gateway/resolver.py Resolved
Comment thread backend/utils/llm/gateway_client.py Resolved
Comment thread backend/utils/llm/gateway_client.py Resolved
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Review Feedback Addressed

All 11 review threads from Codex and Cubic have been addressed in commit e0cc0bd. Summary:

# Priority File Fix
1 P2 gateway_client.py Inject additionalProperties: false recursively into all object schemas for OpenAI Structured Outputs strict mode
2 P1 gateway_client.py Replaced httpx.post() with httpx.Client context manager + added explicit sync-only docstring clarifying event-loop safety
3 P2 schemas.py Extracted duplicated lane_id regex into shared LaneId type alias (Annotated[str, Field(...)])
4 P2 validator.py Added json_schema.name validation per OpenAI API requirement
5 P2 executor.py Implemented retry.max_attempts per-provider retry loop before fallback
6 P2 openai_compatible.py Mapped error type to OpenAI category (invalid_request_error, authentication_error, api_error) instead of duplicating code
7 P2 credentials.py Normalized whitespace-only key_ref to None so malformed refs fail BYOK availability checks
8 P2 resolver.py Changed missing/blank model from MODEL_NOT_FOUND (404) to INVALID_REQUEST (400)
9 P2 gateway_client.py Same as #1 — strict JSON schema normalization applied before sending
10 P3 test file Removed duplicate gateway-success test (test_requires_context_non_byok_tries_gateway_by_default)
11 P3 gateway_client.py Removed dead Pydantic v1 fallback branches (schema(), parse_obj())

Verification

  • Lint & Format Check: PASS
  • Hermetic Backend E2E: PASS
  • Local tests: 63 passed (all test_llm_gateway_* tests, including 7 new tests covering: retry behavior, name validation, whitespace key_ref, error type mapping, missing-model error code)
tests/unit/test_llm_gateway_chat_extraction_pilot.py: 7 passed
tests/unit/test_llm_gateway_validator.py: 9 passed (1 new)
tests/unit/test_llm_gateway_resolver.py: 19 passed (1 new)
tests/unit/test_llm_gateway_executor.py: 13 passed (1 new)
tests/unit/test_llm_gateway_credentials.py: 6 passed (1 new)
tests/unit/test_llm_gateway_openai_compatible.py: 9 passed (1 new)

Note: 8 pre-existing failures in test_llm_gateway_openai_provider.py (FrozenInstanceError with ProviderFailure dataclass) are unrelated to this PR — they fail on the base commit too.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e0cc0bdbc6

ℹ️ 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".

Comment thread backend/llm_gateway/gateway/executor.py Resolved
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Fix: gate active-route execution on rollout stage/percentage (P2)

Addresses Codex review comment on executor.py:59.

Problem

The checked-in active route (route.chat_structured.2026_06_27.001) is marked rollout.stage: shadow, percent: 0 in route_artifacts.yaml, but execute_chat_completion always served resolved_route.active_route without checking rollout — so a shadow candidate served 100% of live traffic instead of falling back to LKG/legacy output.

Fix

Added rollout gating at the executor entry point:

  • _select_serving_route() checks whether the active route is eligible to serve live traffic via _is_route_eligible_to_serve().
  • _is_route_eligible_to_serve() returns False when rollout.stage is shadow or disabled, or when rollout.percent is 0.
  • When the active route is ineligible, traffic falls back to the last-known-good route (LKG) — the route that is actually marked stage: active, percent: 100.
  • When LKG is already the serving route (because active is shadow), the redundant LKG-on-failure fallback is skipped — LKG failures propagate directly.

Verification

  • backend/tests/unit/test_llm_gateway_executor.py — 19/19 passed (0.37s), including 3 new tests:
    • test_shadow_active_route_serves_lkg_not_active — shadow active route serves LKG model (gpt-4o-mini), not active (gpt-4.1-mini)
    • test_disabled_active_route_serves_lkg_not_active — disabled active route serves LKG
    • test_canary_active_route_with_percent_zero_serves_lkg — canary at 0% serves LKG
  • backend/tests/unit/test_llm_gateway_openai_compatible.py — 8/8 passed; updated the success test to assert LKG model (gpt-4o-mini) since the checked-in active route is shadow.
  • ruff check + black --check --line-length 120 — clean.
  • The 8 pre-existing failures in test_llm_gateway_openai_provider.py are unrelated (Python 3.11/httpx FrozenInstanceError), present on the original HEAD before this change.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8b36ddac9a

ℹ️ 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".

Comment thread backend/llm_gateway/gateway/executor.py Resolved

@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.

1 issue found across 3 files (changes from recent commits).

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

Re-trigger cubic

Comment thread backend/llm_gateway/gateway/executor.py Resolved
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Canary rollout percentage enforcement

Both review threads flagged the same root cause: _is_route_eligible_to_serve treated any nonzero rollout.percent as full eligibility, so a 10% canary served 100% of gateway traffic.

Fix

_is_route_eligible_to_serve now takes the validated request and enforces canary sampling:

  • SHADOW / DISABLED → traffic falls back to LKG (unchanged)
  • CANARY with percent < 100 → deterministic per-request sampling via sha256(route_artifact_id + request messages), mapped to [0, 100) and compared against rollout.percent
  • CANARY at 100% / ACTIVE → all traffic to active route (no sampling)

The deterministic hash ensures the same request consistently lands on the same route across retries, while distributing traffic proportionally over many distinct requests.

Verification

  • black --check --line-length 120 --skip-string-normalization — pass
  • 22 executor tests pass (including 4 new canary tests):
    • test_canary_active_route_with_percent_zero_serves_lkg — percent 0 → LKG
    • test_canary_route_enforces_partial_rollout_percentage — 30% canary over 500 distinct requests → ~150 active (within ±50 tolerance)
    • test_canary_sampling_is_deterministic_for_same_request — same request → same decision
    • test_canary_route_at_100_percent_serves_active — percent 100 → active route
  • All 71 llm_gateway unit tests pass

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4972d4f089

ℹ️ 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".

Comment thread backend/llm_gateway/gateway/auth.py Resolved
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Fixed in ec9543d6. The gateway now accepts the same primary env var as the client with identical precedence.

What changed

  • backend/llm_gateway/gateway/auth.py: _configured_service_token() now reads OMI_LLM_GATEWAY_SERVICE_TOKEN first and falls back to LLM_GATEWAY_SERVICE_TOKEN, matching utils.llm.gateway_client.get_llm_gateway_service_token() exactly. The old SERVICE_TOKEN_ENV_VAR constant is kept aliased to the legacy name for backward compatibility with existing references.
  • When both vars are present with different values, the gateway now resolves to the same token the client sends, so local dev and token rotation no longer reject every request.

Verification (local, .venv, ENCRYPTION_SECRET set)

  • tests/unit/test_llm_gateway_auth.py: 12 passed (8 existing + 4 new)
  • tests/unit/test_llm_gateway_openai_compatible.py: 4 passed
  • tests/unit/test_llm_gateway_readiness.py: 8 passed
  • black --check on both changed files: clean
  • New tests cover: primary-only accepted, primary takes precedence over legacy, legacy fallback when primary absent, both-blank fails closed (503).

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ec9543d6f3

ℹ️ 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".

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Fixed in 5719856 — aligned the LKG route with the legacy model.

The LKG route route.chat_structured.2026_06_20.001 previously served gpt-4o-mini as its primary model, while the legacy get_llm('chat_extraction') path resolves to gpt-4.1-mini (confirmed in model_config.py). Since the active route is in shadow rollout (percent: 0), the executor serves the LKG for 100% of successful non-BYOK pilot calls — silently swapping gpt-4.1-mini for gpt-4o-mini and changing classifier behavior instead of being a no-user-visible shadow.

Change: set the LKG primary to gpt-4.1-mini (matching the legacy route) and recomputed the artifact_digest for the changed route content. Added a comment in the YAML documenting the invariant.

Verification:

  • load_gateway_config(prod_mode=True) loads cleanly — the digest check and prod evidence gates pass.
  • Ran the full gateway test suite: test_llm_gateway_executor.py, test_llm_gateway_config.py, test_llm_gateway_resolver.py, test_llm_gateway_openai_compatible.py, test_llm_gateway_chat_extraction_pilot.py — 62 passed, 0 failed.
  • Updated the executor and openai-compatible tests that asserted the served LKG model to expect gpt-4.1-mini.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Separate FastAPI LLM gateway pilot (OpenAI-compatible) with auto-route config + telemetry. Large feature; approving only.

@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.

8 issues found across 24 files (changes from recent commits).

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/scripts/smoke-llm-gateway.py">

<violation number="1" location="backend/scripts/smoke-llm-gateway.py:18">
P1: Passing a service bearer token via `--token` command-line argument exposes the secret in process listings, shell history, and audit logs.</violation>

<violation number="2" location="backend/scripts/smoke-llm-gateway.py:55">
P2: `choices` indexing is unsafe: an empty `choices` array causes an unhandled `IndexError` before the script can emit a controlled failure message.</violation>
</file>

<file name="backend/charts/llm-gateway/templates/deployment.yaml">

<violation number="1" location="backend/charts/llm-gateway/templates/deployment.yaml:30">
P2: No configurable pod/container securityContext is included in the llm-gateway deployment template, reducing security hardening and preventing cluster operators from enforcing security policies through Helm values.</violation>

<violation number="2" location="backend/charts/llm-gateway/templates/deployment.yaml:36">
P1: Hardcoded uvicorn listen port (8080) conflicts with configurable containerPort (`.Values.service.port`), creating a port-drift risk. If operators change `service.port`, traffic and probes will target a different port than the container is actually listening on.</violation>
</file>

<file name="backend/scripts/validate-llm-gateway-env.py">

<violation number="1" location="backend/scripts/validate-llm-gateway-env.py:26">
P2: Validation script only checks presence of env variable names, not whether they have actual values or valid secret references. Empty or malformed secret configs can pass silently.</violation>

<violation number="2" location="backend/scripts/validate-llm-gateway-env.py:34">
P2: The `_load_yaml` function lacks error handling for file I/O and YAML parsing failures, causing unhandled exceptions and tracebacks instead of deterministic validation output. As a preflight/CI validation script, it should catch `OSError` and `yaml.YAMLError` and surface them as controlled validation `ERROR:` messages with a clean exit code.</violation>
</file>

<file name="backend/llm_gateway/routers/openai_compatible.py">

<violation number="1" location="backend/llm_gateway/routers/openai_compatible.py:38">
P2: Metrics emission is not fail-safe; unprotected `observe_success` and `observe_error` calls can raise and disrupt normal request handling</violation>
</file>

<file name="backend/charts/llm-gateway/prod_omi_llm_gateway_values.yaml">

<violation number="1" location="backend/charts/llm-gateway/prod_omi_llm_gateway_values.yaml:76">
P1: Readiness probe depends on `sh` and `curl` binaries being present in the container image, which is fragile and can break on minimal or distroless images. All other services in this repo use native `httpGet` or `tcpSocket` probes without shell dependencies.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread backend/scripts/smoke-llm-gateway.py Resolved
Comment thread backend/scripts/smoke-llm-gateway.py Resolved

@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.

1 issue found across 1 file (changes from recent commits).

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=".github/workflows/gcp_backend_pusher.yml">

<violation number="1" location=".github/workflows/gcp_backend_pusher.yml:126">
P2: Unredacted kubectl logs/describe output on deployment failure may leak sensitive runtime data into CI logs</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

@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.

1 issue found across 1 file (changes from recent commits).

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/scripts/smoke-llm-gateway.py">

<violation number="1" location="backend/scripts/smoke-llm-gateway.py:18">
P1: Passing a service bearer token via `--token` command-line argument exposes the secret in process listings, shell history, and audit logs.</violation>

<violation number="2" location="backend/scripts/smoke-llm-gateway.py:55">
P2: `choices` indexing is unsafe: an empty `choices` array causes an unhandled `IndexError` before the script can emit a controlled failure message.</violation>
</file>

<file name="backend/charts/llm-gateway/templates/deployment.yaml">

<violation number="1" location="backend/charts/llm-gateway/templates/deployment.yaml:30">
P2: No configurable pod/container securityContext is included in the llm-gateway deployment template, reducing security hardening and preventing cluster operators from enforcing security policies through Helm values.</violation>

<violation number="2" location="backend/charts/llm-gateway/templates/deployment.yaml:36">
P1: Hardcoded uvicorn listen port (8080) conflicts with configurable containerPort (`.Values.service.port`), creating a port-drift risk. If operators change `service.port`, traffic and probes will target a different port than the container is actually listening on.</violation>
</file>

<file name="backend/scripts/validate-llm-gateway-env.py">

<violation number="1" location="backend/scripts/validate-llm-gateway-env.py:26">
P2: Validation script only checks presence of env variable names, not whether they have actual values or valid secret references. Empty or malformed secret configs can pass silently.</violation>

<violation number="2" location="backend/scripts/validate-llm-gateway-env.py:34">
P2: The `_load_yaml` function lacks error handling for file I/O and YAML parsing failures, causing unhandled exceptions and tracebacks instead of deterministic validation output. As a preflight/CI validation script, it should catch `OSError` and `yaml.YAMLError` and surface them as controlled validation `ERROR:` messages with a clean exit code.</violation>
</file>

<file name="backend/llm_gateway/routers/openai_compatible.py">

<violation number="1" location="backend/llm_gateway/routers/openai_compatible.py:38">
P2: Metrics emission is not fail-safe; unprotected `observe_success` and `observe_error` calls can raise and disrupt normal request handling</violation>
</file>

<file name=".github/workflows/gcp_backend_pusher.yml">

<violation number="1" location=".github/workflows/gcp_backend_pusher.yml:69">
P1: Race condition in secret bootstrap: concurrent workflow runs can fail the deployment when both observe the secret missing and one create call loses the race with ALREADY_EXISTS.</violation>

<violation number="2" location=".github/workflows/gcp_backend_pusher.yml:126">
P2: Unredacted kubectl logs/describe output on deployment failure may leak sensitive runtime data into CI logs</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Git-on-my-level and others added 18 commits June 28, 2026 12:00
The client (utils.llm.gateway_client) reads OMI_LLM_GATEWAY_SERVICE_TOKEN
first and falls back to LLM_GATEWAY_SERVICE_TOKEN, but the gateway only
read the bare name. When both vars were present with different values
(e.g. local dev or token rotation), every gateway request was rejected
and the pilot silently fell back.

Make the gateway accept the same primary env var with identical
precedence (OMI_ prefixed wins, bare name is legacy). Adds 4 tests
covering primary-only, precedence, legacy fallback, and blank fails
closed.
The LKG route (route.chat_structured.2026_06_20.001) served gpt-4o-mini
while the legacy get_llm('chat_extraction') path resolves to gpt-4.1-mini.
With the active route in shadow rollout (percent 0), enabling the gateway
silently changed classifier behavior for 100% of successful non-BYOK
pilot calls instead of being a no-user-visible shadow.

Align the LKG primary model to gpt-4.1-mini to match the legacy route, and
update the artifact_digest for the changed content. Update the executor and
openai-compatible tests that assert the served LKG model.

Addresses chatgpt-codex-connector review feedback (P2).
- smoke-llm-gateway.py: support token via OMI_LLM_GATEWAY_SERVICE_TOKEN env
  var instead of only --token CLI arg (avoids secret in process listings)
- smoke-llm-gateway.py: guard against empty/missing choices array (IndexError)
- validate-llm-gateway-env.py: add I/O and YAML parsing error handling in
  _load_yaml (controlled ERROR output + clean exit)
- validate-llm-gateway-env.py: validate env vars have actual values or valid
  secret references, not just key presence
- deployment.yaml: parameterize uvicorn listen port via .Values.service.port
  (fixes port-drift risk between containerPort and uvicorn)
- deployment.yaml: add configurable podSecurityContext and container
  securityContext blocks (matches backend-listen chart pattern)
- openai_compatible.py: wrap metrics observe calls in _safe_observe to
  prevent telemetry failures from disrupting request handling
Address cubic P2 (discussion_r3487225338): the llm-gateway is an
OpenAI-compatible service that processes chat content and service
tokens, so dumping raw `kubectl logs` on rollout failure could leak
sensitive runtime data into CI output. Keep the safe status diagnostics
(describe deploy/pods, get pods, ExternalSecret status, secret key
presence) and drop only the raw log dump. The smoke-pod log line is
intentionally retained since it only logs a controlled smoke test
script.
Address two cubic review threads on gcp_backend_pusher.yml:

- P1 (r3487241404): Tolerate ALREADY_EXISTS in the dev service-token
  bootstrap. Two concurrent workflow_dispatch dev deploys could both
  observe the secret missing and race on gcloud secrets create; the
  loser failed the whole deployment. Now a failed create re-checks
  existence and exits 0 if the secret is present (created by the other
  run), only failing if the secret is genuinely absent.

- P2 (r3487301182): Append GITHUB_RUN_ATTEMPT to the smoke pod name so
  workflow reruns don't collide on the prior attempt's pod if its
  cleanup trap didn't fire.
…ing, sentinel

- Gate provider error body preview behind LLM_GATEWAY_EXPOSE_PROVIDER_ERROR_DETAILS
  flag so pure-alpha error text is never surfaced to API clients by default
  (Cubic P1: information disclosure via sanitize() bypass)
- Check HTTP status before reading full response body on error responses so a
  large/invalid-content-length body cannot reclassify a 401/403/429/4xx as
  PROVIDER_5XX_OMI_PAID, preserving correct retry/LKG-fallback behavior
  (Cubic P1: status-specific failure masking)
- Replace magic-string sentinel 'provider request failed' with shared
  GENERIC_PROVIDER_FAILURE_MESSAGE constant to avoid drift
  (Cubic P2: fragile exact-string sentinel check)
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Review feedback addressed (Cubic P1/P1/P2)

Fixed all three unresolved Cubic threads in providers.py and executor.py:

Thread 1 — P1: Provider error body information disclosure

  • _provider_error_message() now gates the body preview behind the existing LLM_GATEWAY_EXPOSE_PROVIDER_ERROR_DETAILS flag. By default it returns the generic GENERIC_PROVIDER_FAILURE_MESSAGE so pure-alpha provider error text (prompt fragments, account metadata) is never surfaced to API clients. The body preview is only included when the flag is explicitly enabled for debugging.
  • This also fixes the pre-existing failure in test_openai_compatible_provider_maps_status_without_leaking_body (6 parametrized cases were failing because the raw body leaked through str(ProviderFailure)).

Thread 2 — P1: Body-size errors masking status-specific failures

  • Error responses (status >= 400) now read a small bounded preview (PROVIDER_ERROR_DETAIL_BYTES = 1000) via a new _read_bounded_preview() helper before calling _raise_for_status(). Unlike _read_limited_response(), this helper truncates silently instead of raising PROVIDER_5XX_OMI_PAID on oversize bodies.
  • This ensures a 401/403/429/4xx with a large or invalid-content-length body is correctly classified by its status code, preserving retry and LKG-fallback behavior (INVALID_CONFIG and CAPABILITY_MISMATCH stay in NEVER_LKG_FAILURE_CLASSES).

Thread 3 — P2: Fragile exact-string sentinel check

  • Replaced the magic string 'provider request failed' sentinel in _safe_failure_message() with the shared GENERIC_PROVIDER_FAILURE_MESSAGE constant. Consolidated the duplicated EXPOSE_PROVIDER_ERROR_DETAILS_ENV_VAR constant and _expose_provider_error_details() into providers.py as the single source of truth.

Verification

  • pytest tests/unit/test_llm_gateway_*.py — 136 passed (was 130 with 6 failing before this fix)
  • Behavioral checks: error body does not leak when expose flag is OFF; 401 + oversized body classified as INVALID_CONFIG not 5XX; sentinel comparison uses constant correctly
  • git diff --check clean; pre-commit formatting hook passed
  • CI: Hermetic Backend E2E ✅, Lint & Format Check ✅

@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.

1 issue found across 2 files (changes from recent commits).

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/scripts/smoke-llm-gateway.py">

<violation number="1" location="backend/scripts/smoke-llm-gateway.py:68">
P2: `--check-metrics` does not actually validate metric increment; it only validates metric is non-zero, allowing false positives from prior traffic.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

value = float(line.rsplit(' ', 1)[-1])
except ValueError:
continue
if value > 0:

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: --check-metrics does not actually validate metric increment; it only validates metric is non-zero, allowing false positives from prior traffic.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/scripts/smoke-llm-gateway.py, line 68:

<comment>`--check-metrics` does not actually validate metric increment; it only validates metric is non-zero, allowing false positives from prior traffic.</comment>

<file context>
@@ -40,6 +40,36 @@ def _get_ready(client: httpx.Client, url: str, headers: dict[str, str]) -> httpx
+            value = float(line.rsplit(' ', 1)[-1])
+        except ValueError:
+            continue
+        if value > 0:
+            return line
+    return None
</file context>

This branch was successfully deployed

1 active (outdated) and 1 inactive deployments
development — f5d013ef Deployed Jun 28, 2026 by Git-on-my-level via deploy #229
staging - docs — b95a74e6 Deployed Jun 28, 2026 by mintlify[bot]
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.

2 participants