Skip to content

fix(backend): cache the static instructions, not the unique transcript - #15649

Merged
Git-on-my-level merged 1 commit into
mainfrom
codex/llm-prompt-cache-misses
Sep 22, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
codex/llm-prompt-cache-misses

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

What changed and why

Production gpt-5.6-luna already sends explicit cache options, but conv_structure (notes v2) marked the unique conversation transcript as the cached prefix (omi-conv-{id}). That prefix is almost never reused, which is why sampled attempts show 3.7% cached on 240.5M input tokens/day. This PR follows chat_agent: hoist static instructions first, put dates / language / transcript after the breakpoint, and key the cache on the feature (or hashed instruction bytes), not the conversation id.

No prompt wording was rewritten. Dates and timezone stay in the per-call suffix so the model still sees them.

Product invariants affected

  • INV-MEM-4 — backend/utils/llm/working_observations.py and backend/utils/llm/memories.py are on this invariant's path globs. Message order changed (instruction prefix first, conversation context after the breakpoint). Extraction schema, persistence, and promotion authority are untouched.

Per-feature cache diagnosis

feature current cached % cause this PR expected if improved
conv_structure 3.7% Notes v2 marked the unique transcript; dates/language/density sat after that breakpoint so they did not break that cache, but the cached blob itself was per-conversation. Explicit options were reaching the provider. Static rules + schema first with breakpoint; language, density, task filter, open tasks, DATE CONTEXT, transcript, wake-word rules in the suffix. Cache key omi-conversation-notes-v1. ≈60% → ≈$730/mo
memories 21.9% Mostly riding the conversation prefix notes wrote. After notes stops writing omi-conv-{id}, that ride disappears unless L1 has its own instruction prefix. L1 system instructions first with breakpoint; conversation prefix unmarked after that. Cache key hashes the static system bytes (omi-memory-l1-v1). user_name stays in the prefix (per-user cache, not deleted). ≈60% → ≈$325/mo
conv_apps 25.0% Same ride-along on the conversation prefix for the notes-prefix path. Legacy app-framing split is already static-first. Prefix path: app name/description/task first with breakpoint; Respond in {language} and conversation after. ≈60% → ≈$95/mo when the app instructions clear the 1024-token floor; short-task apps stay opted out (same floor as the legacy path).
conv_action_items 35.7% Already static-instruction-first. Left alone. —
conversation_processing 0.0% Unique prompts; already sends explicit mode with no breakpoint (opt-out of unreadable writes). Left alone. —
knowledge_graph 0.0% EXISTING NODES sits in the middle of a single string; the static guidelines + schema are at or under the 1024-token floor. Splitting would be a content-layout rewrite without a clear cacheable head. Left alone. —
goals 0.0% 326 tok/call, below the 1024-token cacheable minimum. Left alone. —
chat_agent 47.9% Reference: static system prefix, live datetime in the user turn. Left alone. —
desktop_proactivity 29.0% Not the same mechanical miss. Left alone. —
proactive_notification 0.0% Separate worktree. Not touched. This PR does not share prompt-layout code with that path. —

Total in-scope if the three changed features land near the targets: roughly $1,150/mo, dominated by conv_structure. Cached-input share is still a production measurement (llm_gateway_attempts); these percentages are the sampled baseline plus the chat_agent-shaped layout, not a live A/B.

How it was verified

Regression tests assert the marked prefix is byte-identical across two invocations that differ in transcript, timezone, clock, and language:

  • backend/tests/unit/test_llm_feature_prompt_cache_prefix.py — conv_structure, memories, conv_apps prefix path
  • Existing notes/wake-word/L1 tests updated for the new message order

Commands (from this worktree; backend/test.sh with an explicit file list, never one multi-file pytest):

scripts/backend-python-format --write \
  backend/utils/llm/conversation_processing.py \
  backend/utils/llm/working_observations.py \
  backend/utils/llm/memories.py \
  backend/tests/unit/test_llm_feature_prompt_cache_prefix.py \
  backend/tests/unit/test_conversation_notes_v2.py \
  backend/tests/unit/test_working_observations_extractor.py \
  backend/tests/unit/test_wake_word.py \
  backend/tests/unit/test_conversation_structure_timezone.py \
  backend/tests/unit/test_action_item_date_validation.py

list=$(mktemp)
printf '%s\n' \
  tests/unit/test_llm_feature_prompt_cache_prefix.py \
  tests/unit/test_conversation_notes_v2.py \
  tests/unit/test_working_observations_extractor.py \
  tests/unit/test_wake_word.py \
  tests/unit/test_conversation_structure_timezone.py \
  tests/unit/test_action_item_date_validation.py \
  tests/unit/test_memory_l1_deadline_invariance.py \
  tests/unit/test_compact_speaker_transcript.py \
  tests/unit/test_conversation_features_prompt_cache.py \
  tests/unit/test_conversation_structure_provider_timeout.py \
  tests/unit/test_prompt_caching.py > "$list"
BACKEND_UNIT_TEST_FILE_LIST="$list" backend/test.sh

scripts/failure-class validate
make preflight
scripts/pr-preflight --pr-body-file .pr-body.md

Tests

  • New: backend/tests/unit/test_llm_feature_prompt_cache_prefix.py — the regression that would have caught a date/transcript leaking into the marked prefix
  • Updated: test_conversation_notes_v2.py, test_working_observations_extractor.py, test_wake_word.py (static prefix identical; wake rules only on the marked volatile suffix)

Failure class (fixes)

Failure-Class: new

Failure-class transition narrative (only when needed)

New class FC-per-call-bytes-in-cached-prompt-prefix.

Violated contract: A prompt-cache breakpoint must sit after a prefix that is byte-identical across calls that differ only in per-call inputs. Putting a timestamp, timezone, language, transcript, or other per-call value at or before that boundary means every call writes a unique prefix and no later call can read it.

Canonical prevention: Hoist only static instruction text into the marked prefix; move dates, transcripts, and other per-call values after the breakpoint; pin the split with a regression test that two invocations with different per-call inputs produce byte-identical prefix bytes.

Guard: backend/tests/unit/test_llm_feature_prompt_cache_prefix.py (listed as canonical_prevention_artifact). evidence_prs is [] because this PR is the first instance and has no merged number yet.

Scoped cleanups (optional)

SHARED_CONVERSATION_PREAMBLE remains in the notes static block. After the reorder it still says task-specific instructions “follow” the shared context, which is slightly out of order; the bytes are unchanged (allowed: reorder/hoist only, no wording rewrite).

Line-Count-Exception: backend/utils/llm/conversation_processing.py | 1903 -> 1968 | the static/volatile prompt split adds two named builder functions and their docstrings to an existing oversized module; splitting the module is a separate refactor that would obscure this fix's diff

🤖 Generated with Claude Code

Review in cubic

conv_structure sat at 3.7% cached on 240.5M input tokens/day because notes v2
marked the per-conversation transcript as the cached prefix (omi-conv-{id}), so
every call wrote an entry no later call could read. Explicit cache options were
reaching the provider; the prefix was the defect. memories L1 and the apps
prefix path were riding the same unreadable blob.

Follow chat_agent: static rules and parser schema first behind the breakpoint,
with language, density, open tasks, DATE CONTEXT and the transcript in the
per-call suffix. No prompt wording was rewritten.

Failure-Class: FC-per-call-bytes-in-cached-prompt-prefix
Invariants: INV-MEM-4

Co-Authored-By: Claude Opus 5 <[email protected]>
@Git-on-my-level
Git-on-my-level force-pushed the codex/llm-prompt-cache-misses branch from 7662bd7 to b9c0e63 Compare September 22, 2026 04:11
@Git-on-my-level
Git-on-my-level merged commit a979f62 into main Sep 22, 2026
60 checks passed
@Git-on-my-level
Git-on-my-level deleted the codex/llm-prompt-cache-misses branch September 22, 2026 04:21
Wizard815 pushed a commit to Wizard815/omi-local that referenced this pull request Nov 25, 2026
BasedHardware#15649)

conv_structure sat at 3.7% cached on 240.5M input tokens/day because notes v2
marked the per-conversation transcript as the cached prefix (omi-conv-{id}), so
every call wrote an entry no later call could read. Explicit cache options were
reaching the provider; the prefix was the defect. memories L1 and the apps
prefix path were riding the same unreadable blob.

Follow chat_agent: static rules and parser schema first behind the breakpoint,
with language, density, open tasks, DATE CONTEXT and the transcript in the
per-call suffix. No prompt wording was rewritten.

Failure-Class: FC-per-call-bytes-in-cached-prompt-prefix
Invariants: INV-MEM-4

Co-authored-by: Claude Opus 5 <[email protected]>
Wizard815 pushed a commit to Wizard815/omi-local that referenced this pull request Nov 25, 2026
Brings the fork from the 2026-09-14 merge base (6075928) to upstream
8a1de0d (2026-10-21). 122 conflicts. Upstream's code is the baseline; the
fork's self-hosting changes are re-applied on top, ported into upstream's new
structure where it moved code. Fork commits that were cherry-picks of
upstream PRs (BasedHardware#15202, BasedHardware#15289, BasedHardware#15304, BasedHardware#15317, BasedHardware#15462, BasedHardware#15649) take upstream's
newer version.

Resolution decisions
- Chat: upstream moved the send-message turn into utils/chat_turn.py. That
  call now forwards model_shortcut, so the sticky /adult toggle still works.
  graph.execute_chat_stream keeps the shortcut-routing wrapper around
  upstream's body. upstream already has the async quota release.
- Local LLM: upstream routes every managed get_llm() through the Omi LLM
  gateway (OMI_LLM_GATEWAY_FEATURE_MODE no longer opts out). In local mode
  (is_local_mode()) clients.py now keeps generation on the direct client at
  OPENAI_BASE_URL. model_config keeps the fork's Redis/env model resolution,
  the per-turn shortcut override and local_base_chat_model.
- Conversation notes: upstream serves them only through the shaped notes
  agent and fails closed unless OMI_SHAPED_AGENT_MODE is on, so
  omi-host/entrypoint.sh now exports OMI_SHAPED_AGENT_MODE=on (default).
- Auth: upstream added POST /v1/auth/local-dev/custom-token, gated only on
  FIREBASE_AUTH_EMULATOR_HOST. omi-host always sets that (the emulator is its
  real auth store), so the route would mint a token for any uid.
  OMI_DISABLE_LOCAL_DEV_TOKEN_ROUTE (set by the entrypoint) switches it off.
  The fork's /v1/auth/local-login and remote-login sessions are kept.
- Time zone: upstream added the same PUT /v1/users/time-zone. Keep upstream's
  handler and database.notifications.set_user_time_zone, and drop the fork's
  duplicate setter (it shadowed upstream's) and SaveTimeZoneRequest. The
  app calls upstream's syncUserTimeZoneServer.
- Folders: upstream has no hierarchy, so the fork's folder tree is kept.
  folder_tabs.dart was deleted upstream (folder browsing moved into global
  search), so the subfolder bar, breadcrumb and tree entry were ported into
  global_search.dart and folder_options_sheet.dart.
- Static map: rebuilt on upstream's themed renderer. The no-key
  OpenStreetMap fallback dispatches to _render_osm_png.
- TTS: upstream's provider switch, plus the fork's local Piper path
  (TTS_LOCAL_BASE_URL).
- Subscription/billing: the PROVIDER_MODE=offline early return sits ahead of
  upstream's new funded-compute and budget gates.
- belief_model.py: deleted upstream (BasedHardware#22209) with nothing left importing it,
  so it stays deleted, as do its fork-only tests.
- Vector DB: the fork's LOCAL_VECTOR_DB=chroma path is kept on top of
  upstream's upsert_vector2 metrics and legal-hold gates.
- App:
  - The "/" popup, the sticky shortcut chip and modelShortcut are ported
    onto upstream's composer.
  - The day-review banner stays on Home.
  - The day-review list moves into the Daily Recaps app bar (its Home header
    button went away upstream).
  - LED dim on mute is re-applied after upstream's dispatch-based
    pause/resume.
- Session snapshots: AuthService snapshots recognize a valid remote-login
  session. Upstream's snapshots read it as signed out, which silently
  disabled data export, on-demand recaps and onboarding sync.
- SaaS removals stay removed: referral page and its Settings destination,
  Creator Payouts destination, Crashlytics, the FCM token, and the Google
  sign-in button.
- route_policy_manifest.yaml: upstream's entries plus the fork's 25 routes.
- Generated files:
  - regenerated from the merged sources: app-client OpenAPI spec and its
    Dart/Swift/TS types, flutter gen-l10n;
  - regenerated from requirements.txt by update-python-lock.sh: all
    pylocks, which also restores the e2e packages main's pylock had lost.

Verification (details in the PR):
- flutter analyze: 0 errors; app/scripts/analyze_ratchet.sh passes.
- Backend suites for every touched area pass, among them
  test_local_model_routing (including the new gateway-bypass tests),
  test_chat_model_shortcuts through upstream's run_chat_turn,
  test_nested_folders, test_local_scheduler, test_local_dev_auth plus the
  new self-host opt-out test, test_static_map, and the
  LLM/retrieval/vector suites.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148HLrpWR8Mimn43rkNvGKg
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