Skip to content

perf(llm): trim L1 generation schema and reuse exact Vertex embeddings - #23680

Closed
Git-on-my-level wants to merge 7 commits into
mainfrom
lane/s4-llm-schema-compact
Closed

Git-on-my-level wants to merge 7 commits into
mainfrom
lane/s4-llm-schema-compact

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

What changed and why

Reduce redundant L1 schema tokens and repeated Vertex embeddings while preserving the full output contracts.

L1 uses a private generation schema without five fields that the server always recomputes. The original parser, public model, policy validators and deterministic IDs remain authoritative. The source-derived schema falls from 719 to 580 tokens (139/request in both pinned tokenizers).

Company-managed Vertex embeddings reuse successful vectors for the same tenant/user and exact effective input. Keys hash the full text, task, title and endpoint. Reuse has a hard 600s TTL, 512-entry and 262144-value bounds; batches keep every input position. No plaintext input or owner is retained in the cache. Missing owners and other models bypass reuse; BYOK is rejected before lookup. Existing fan-out, deadlines, cancellation and wire validation remain authoritative.

Both cuts have independent on-by-default kill switches. Content-free counters expose submitted and reused embedding characters without inventing provider token usage. See backend/docs/runbooks/llm-output-neutral-cuts.md.

Product invariants affected

  • INV-MEM-4: generation instructions and exact successful embedding reuse change; intake, promotion authority, ownership, evidence, privacy policy and lifecycle writes remain authoritative.

Verification

Selected fixture suites use bin/omi-heavy run -- env BACKEND_UNIT_TEST_FILE_LIST=... BACKEND_PYTEST_WORKERS=1 nice -n 19 bash backend/test.sh:

  • Full legacy L1 responses and responses omitting derived fields produce identical complete parsed objects, including IDs, sensitive/general policy, evidence and speaker attribution. Kill restores the exact original schema.
  • Real Vertex adapter wire replay produces identical vectors, order and response shape while nine fixture inputs use three provider calls. Scope/input changes, failure, cancellation, kill, TTL, memory bounds and mutation isolation are covered; existing wire/fan-out/deadline tests remain selected.

The single Luna round marked L1 SHIP and requested a P2 cancellation correction for Vertex. New vectors now stay request-local until the batch outcome is known; cancellation/deadlines discard staging while ordinary provider errors retain valid partial reuse. The new real-HTTP tests reject the old implementation in exactly three cancellation/timeout cases; the corrected embedding/gateway selection passes all 43 tests. The rollout lead accepted this disposition and required no second round. Full details are in the review-disposition comment.

Main's independent app-schema inventory repair (#23780) is integrated; the repaired inventory suite passes all 14 tests locally. No app/scanner changes are part of this PR's diff.

No production content, account data or secret payloads were read. Aggregate gateway baseline uses ro-prod. Deterministic fixture replay establishes parser/vector equality; no live-model generation quality or realized production dollar saving is claimed. Baseline and tokenizer projections are separate from vendor usage. Vertex reports no token usage through this path.

Rollout and rollback

Lead-owned bundled train: backend processing hosts for L1 and llm-gateway for vector reuse. Observe one full post-change window of extraction/parse failures and gateway request p95 against the preceding matched window before expansion. Stop expansion on accuracy, attribution or latency regression. Compare tokens per eligible attempt as well as totals and reconcile vendor usage before booking dollars; C5 reuse and caching overlap these cuts. Cold prefix/result fingerprints can briefly increase spend.

  • MEMORY_L1_PROMPT_SCHEMA_TRIM_ENABLED=false: original full generation schema.
  • VERTEX_EMBEDDING_DEDUPE_ENABLED=false: every provider input, including duplicates in a batch; clears the process cache.

Image rollback restores both prior paths. No stored-data migration or client release is required. Notes duplicate-capture removal remains a separate default-off draft pending synthetic dev-gateway model parity, per the rollout lead.

UI evidence

UI-Evidence: none -- backend generation schema and gateway vector reuse

Failure class (fixes)

Failure-Class: none

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T05:51:13.608372Z 41b45ff New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Git-on-my-level Git-on-my-level changed the title perf(llm): omit server-derived L1 fields from generation schema perf(llm): trim L1 generation schema and reuse exact Vertex embeddings Oct 27, 2026
@mintlify

mintlify Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

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

Project Status Preview Updated
omi 🟢 Ready View Preview Oct 27, 2026, 5:19 AM

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

@Git-on-my-level

Copy link
Copy Markdown
Member Author

The single Luna review marked L1 SHIP and requested one P2 correction for Vertex: a completed item could enter the cache while a sibling remained pending, then survive cancellation or timeout of that batch.

The correction stages new successful vectors in request-local state. Full success publishes them; caller cancellation, the batch deadline and provider timeouts discard the staging. Ordinary provider errors still allow already completed valid items to be reused, as documented. Previously cached results from separate successful requests remain intact.

New tests exercise the real Vertex HTTP adapter with one item fully validated before a sibling blocks/fails. The reviewed old implementation fails exactly the three cancellation/timeout cases (3 failed, 17 passed). The corrected implementation passes all 43 selected embedding/gateway tests, including ordinary-error partial reuse and the original vector/order parity corpus. No production content or live model call is involved.

This is the disposition of the one review round, not a claim that Luna reviewed the later correction. The rollout lead owns the final merge decision and the active merge freeze is respected.

@Git-on-my-level
Git-on-my-level marked this pull request as draft November 4, 2026 07:01
@Git-on-my-level
Git-on-my-level marked this pull request as ready for review November 4, 2026 07:27

@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 11 files

Confidence score: 3/5

  • Cache hits in vertex_embedding_cache.py still depend on refreshing ADC credentials, adding latency and failing when refresh is temporarily unavailable. Check the cache before obtaining the token.
  • In vertex_embedding_cache.py, a worker timeout can be hidden by another TaskGroup failure, allowing staged vectors to be committed. Prioritize TIMEOUT_BEFORE... when classifying grouped failures.
  • feature-flag-registry.md is dated 2026-10-22 even though this entry was created on 2026-10-27, so the freshness metadata is inaccurate. Regenerate it with the current snapshot date.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/llm_gateway/gateway/vertex_embedding_cache.py">

<violation number="1" location="backend/llm_gateway/gateway/vertex_embedding_cache.py:160">
P2: The runner acquires a Vertex access token before checking the reuse cache, so cache hits still pay token-refresh latency and fail when ADC refresh is temporarily unavailable. Check the cache before obtaining the token, and create headers only when a miss needs `_create_instance`.</violation>

<violation number="2" location="backend/llm_gateway/gateway/vertex_embedding_cache.py:232">
P2: `TaskGroup` can group concurrent worker failures, but this re-raises only the first classification. A sibling timeout can therefore be hidden and the outer handler can commit staged vectors; prioritize `TIMEOUT_BEFORE_OUTPUT` whenever any grouped failure has that class.</violation>
</file>

<file name="backend/docs/feature-flag-registry.md">

<violation number="1" location="backend/docs/feature-flag-registry.md:451">
P3: This generated registry is labeled `as-of: 2026-10-22`, but this entry was created on `2026-10-27`. Regenerate it with the current snapshot date so its freshness is accurate.</violation>
</file>

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

View guided diff | Turn on auto-fix | Re-trigger cubic

if len(instances) == 1:
# A single predict keeps the existing per-request wire timeout.
# Only batches need to share a shrinking budget across requests.
headers = _vertex_headers(await self._access_token(), ptr.REQUEST_TYPE_SHARED)

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: The runner acquires a Vertex access token before checking the reuse cache, so cache hits still pay token-refresh latency and fail when ADC refresh is temporarily unavailable. Check the cache before obtaining the token, and create headers only when a miss needs _create_instance.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/llm_gateway/gateway/vertex_embedding_cache.py, line 160:

<comment>The runner acquires a Vertex access token before checking the reuse cache, so cache hits still pay token-refresh latency and fail when ADC refresh is temporarily unavailable. Check the cache before obtaining the token, and create headers only when a miss needs `_create_instance`.</comment>

<file context>
@@ -0,0 +1,283 @@
+        if len(instances) == 1:
+            # A single predict keeps the existing per-request wire timeout.
+            # Only batches need to share a shrinking budget across requests.
+            headers = _vertex_headers(await self._access_token(), ptr.REQUEST_TYPE_SHARED)
+            vector = await self._reusable_embedding_instance(
+                endpoint,
</file context>

except* ProviderFailure as failures:
# TaskGroup cancels and drains siblings before exposing the
# first typed error; never return a partially embedded batch.
raise failures.exceptions[0] from None

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: TaskGroup can group concurrent worker failures, but this re-raises only the first classification. A sibling timeout can therefore be hidden and the outer handler can commit staged vectors; prioritize TIMEOUT_BEFORE_OUTPUT whenever any grouped failure has that class.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/llm_gateway/gateway/vertex_embedding_cache.py, line 232:

<comment>`TaskGroup` can group concurrent worker failures, but this re-raises only the first classification. A sibling timeout can therefore be hidden and the outer handler can commit staged vectors; prioritize `TIMEOUT_BEFORE_OUTPUT` whenever any grouped failure has that class.</comment>

<file context>
@@ -0,0 +1,283 @@
+                except* ProviderFailure as failures:
+                    # TaskGroup cancels and drains siblings before exposing the
+                    # first typed error; never return a partially embedded batch.
+                    raise failures.exceptions[0] from None
+        except TimeoutError as exc:
+            raise ProviderFailure(FailureClass.TIMEOUT_BEFORE_OUTPUT) from exc
</file context>
Suggested change
raise failures.exceptions[0] from None
failure = next(
(
failure
for failure in failures.exceptions
if failure.failure_class == FailureClass.TIMEOUT_BEFORE_OUTPUT
),
failures.exceptions[0],
)
raise failure from None

| `LOCAL_PREVIEW_BATCH_ENABLED` | Default on; a mobile listen session that declares local_preview=enabled, whose uid is on the batch record lane (batch allowlist or batch percent) with private cloud sync and no custom STT, journals all pendant audio through the mobile Standard batch route and defers the cloud live STT stream until audio reaches the socket | backend | env | open | — | — | — | — | keep | keep | — | dazheng |
| `MEMORY_ENABLED` | Global incident stop for canonical memory intake and reads | backend | env | closed | on | on (backend-listen (chart), cloud_run/backend, cloud_run/backend-integration, cloud_run/backend-sync, cloud_run/backend-sync-backfill, gke/backend-listen, gke/pusher, pusher (chart)) | on (backend-listen (chart), cloud_run/backend, cloud_run/backend-integration, cloud_run/backend-sync, cloud_run/backend-sync-backfill, gke/backend-listen, gke/pusher, job/x-connector-sync-job, pusher (chart)) | — | keep | keep | — | unowned |
| `MEMORY_IMPORT_WRITE_BLOCK_MODE` | Block memory import writes during incident | backend | env | inverted | — | — | — | — | keep | keep | — | unowned |
| `MEMORY_L1_PROMPT_SCHEMA_TRIM_ENABLED` | Default on; omit five server-derived fields from the generation-only L1 schema. Original parsing and deterministic policy/id derivation remain unchanged; false restores the complete legacy schema. | backend | env | open | — | — | — | — | keep | keep | — | dazheng |

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: This generated registry is labeled as-of: 2026-10-22, but this entry was created on 2026-10-27. Regenerate it with the current snapshot date so its freshness is accurate.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/feature-flag-registry.md, line 451:

<comment>This generated registry is labeled `as-of: 2026-10-22`, but this entry was created on `2026-10-27`. Regenerate it with the current snapshot date so its freshness is accurate.</comment>

<file context>
@@ -448,6 +448,7 @@ and an explicit empty literal renders as `''`.
 | `LOCAL_PREVIEW_BATCH_ENABLED` | Default on; a mobile listen session that declares local_preview=enabled, whose uid is on the batch record lane (batch allowlist or batch percent) with private cloud sync and no custom STT, journals all pendant audio through the mobile Standard batch route and defers the cloud live STT stream until audio reaches the socket | backend | env | open | — | — | — | — | keep | keep | — | dazheng |
 | `MEMORY_ENABLED` | Global incident stop for canonical memory intake and reads | backend | env | closed | on | on (backend-listen (chart), cloud_run/backend, cloud_run/backend-integration, cloud_run/backend-sync, cloud_run/backend-sync-backfill, gke/backend-listen, gke/pusher, pusher (chart)) | on (backend-listen (chart), cloud_run/backend, cloud_run/backend-integration, cloud_run/backend-sync, cloud_run/backend-sync-backfill, gke/backend-listen, gke/pusher, job/x-connector-sync-job, pusher (chart)) | — | keep | keep | — | unowned |
 | `MEMORY_IMPORT_WRITE_BLOCK_MODE` | Block memory import writes during incident | backend | env | inverted | — | — | — | — | keep | keep | — | unowned |
+| `MEMORY_L1_PROMPT_SCHEMA_TRIM_ENABLED` | Default on; omit five server-derived fields from the generation-only L1 schema. Original parsing and deterministic policy/id derivation remain unchanged; false restores the complete legacy schema. | backend | env | open | — | — | — | — | keep | keep | — | dazheng |
 | `MEMORY_OBSERVATION_INTAKE_ENABLED` | Default on; route ordinary captured observations inline and in maintenance independently of Dream | backend | env | open | — | — | — | — | keep | keep | — | dazheng |
 | `MEMORY_RELEASED_PROJECTION` | Default on; reuse exact raw released-memory queries only under current atomic writer heads and proven fleet coverage | backend | env | open | — | — | — | — | keep | keep | — | dazheng |
</file context>

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Folding batch (2026-11-04): this branch's tip was merged into the survivor PR #24477 (feat/cv1-release-safety), which now carries origin/main plus all sixteen folded branches; pushed as 88c7ec5. Both sides' conflict intents were preserved (main's evolved implementations win where a successor of the same intent had already landed). Closing here so the batch lives on one PR. Reopen if something you need is missing from the survivor.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Hey @Git-on-my-level 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

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