Skip to content

feat(pipeline): lifecycle ledger writers for every summary outcome, and a tunable notes hold - #25304

Merged
Git-on-my-level merged 20 commits into
mainfrom
lane/lifecycle
Nov 15, 2026
Merged

Git-on-my-level merged 20 commits into
mainfrom
lane/lifecycle

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

Capture lifecycle spine: ledger writers for every summary outcome, and a tunable notes hold

Supersedes #25125 and #25129 (both folded in by merge, history kept). Tracking: SCA-1760, SCA-1762,
SCA-1766. Design note: the DESIGN: comment on SCA-1760.

The in-flight ledger (users/{uid}/pipeline_ledger/{capture_id}) had two production writers on main
(capturing, transcribed), so no capture ever reached a terminal and the end-to-Home gate had nothing to
read. This gives every normal outcome a writer, and makes the 600 s notes hold tunable without a release.

Line-Count-Exception: backend/database/conversations.py | 4971 -> 5020 | thread the ledger's summary-outcome hook through the two existing lifecycle writers and delete the sibling ledger row with its conversation; splitting this oversized file is separate debt

Failure-Class: FC-dashboard-reads-key-no-writer-maintains

Why this class: the census reads a collection no writer maintained past transcribed, and returned a
well-formed empty aggregate instead of an error. The defect is the missing writers.

What changed

From #25125, unchanged in behaviour:

  • Seal (database/record_audio.py): capturing -> sealed on the seal that closes the recording;
    admission counted once per capture.
  • failed:upload_failed terminal, with end_type=unknown and end_at the observed failure time.
  • Deletion fence in pipeline_ledger.advance(): the ledger transaction reads the source conversation
    and the account-deletion marker (account_deletions/{uid}) and writes nothing for a deleted source or an
    account being wiped. The marker, not the user document, is the authority: the user document outlives its
    subcollections during a wipe (review finding 1). Every writer here passes both references, the operator
    closes included (finding 2).
  • Conversation deletion removes the sibling ledger row and fails if that delete fails (finding 3); the
    delete is idempotent, so the caller's retry completes it.
  • Retention, deletion and erasure inventory for the now-live collection. The ledger is not added to the
    portability export (removed under the goal owner's ruling of 23:37Z: the only approved readers are the
    census routes).

New in this PR:

  • noted and done in one ledger transaction (pipeline_ledger.advance(..., then=(DONE,))). fix(pipeline): wire the first live writers into the in-flight ledger (C1b-1) #25125
    used two transactions at every summary commit; this is one read set and one write.

  • noise terminal for a receipted relevance discard. Before, a discarded capture sat at transcribed
    until its 30-minute deadline and counted as stuck. A later real summary re-opens it with a higher revision.

  • no_speech and noise terminals on the two operator closes (utils/conversations/lifecycle.py),
    written after the real close commits. A restore needs no ledger undo: the restored capture's next real
    transition re-opens the row.

  • SYNC_PROCESSING_QUIET_SECONDS (utils/sync/processing_hold.py): the arrival-quiet window before
    full notes processing is read per call. Default 600, clamped to 120..600, malformed keeps the default. The
    outbox due time and the budget-denial reschedule follow the same value. No behaviour change at the
    default.

  • omi_sync_content_arrival_gap_seconds histogram: seconds between content arrivals on one held
    conversation. The share above a candidate quiet window is the late re-run rate that window would buy.

  • Ledger metrics kept in the sync scrape (deploy/cloud_run_gmp_sync.yaml): the keep rule dropped every
    omi_pipeline_ledger_* family on the services where seal and summary ledger writes run.

Not carried over from #25125: its downgrade of the ledger stuck alert. That rule set is owned by #25284 and
the downgrade no longer met the alert tier contract on main.

Reads and writes

Each fenced ledger write is one transaction: three document reads (account-deletion marker, source, ledger
row) and at most one write. A normal capture costs about 12 reads and 4 writes across its life (seal, summary, and the two
existing writers), against 15 reads and 5 writes if #25125 had merged as it was. No query, scan, per-frame or per-request
read. Rows carry an expiry time; the TTL policy that acts on it is not enabled by this PR.

What this does not do yet, and how to read it

  • Every terminal row still has end_type=unknown and no end_at: the end writers are the next PR, stacked on
    this one. Until that serves, omi_pipeline_ledger_unknown_end_type_total is not a health signal.
  • Done check, after serving: of captures admitted after the serving timestamp, the share reaching done,
    with noise, no_speech and failed:* reported beside it, and no row past its stage deadline. "Any
    terminal" is not the pass. Rows already at transcribed before serving get no writer, expire on the 7-day
    nonterminal lifetime, and are excluded and named as excluded.
  • The hold's 120 s floor is a safety bound (the recorded-time gap at which a conversation splits), not a
    proposed value. The first candidate value is 300, chosen from the arrival-gap histogram.

Kill switches and rollback

  • PIPELINE_LEDGER=off (existing, default on) stops every ledger write. Nothing reads the ledger on a
    serving path, so a revert restores today's behaviour exactly.
  • SYNC_PROCESSING_QUIET_SECONDS unset or 600 is today's behaviour.

Needs the owner's eye

  • Not in this PR: enabling the Firestore TTL policy on the pipeline_ledger collection group. fix(pipeline): wire the first live writers into the in-flight ledger (C1b-1) #25125 did
    it by editing .github/actions/sync-backfill-lifecycle/action.yml; that edit is removed here and waits for
    the owner's explicit yes as its own change. Until then ledger rows carry expires_at but nothing deletes
    them on a timer; conversation deletion and account erasure still remove them.
  • The hold value itself is not changed here. Lowering it is a separate config decision.

Tests

  • tests/unit/test_pipeline_ledger.py: one-write chain keeps both transitions; a duplicate first stage still
    lands the follow stage; a follow stage never re-opens a terminal; receipt-to-stage mapping; noise terminal
    and re-open by a later summary; deleted source writes nothing.
  • tests/unit/test_lifecycle_ledger_terminals.py (new): both operator closes write their terminal; a refused
    close writes none.
  • tests/unit/test_sync_processing_hold.py: per-call read, clamp, malformed values, outbox due time.
  • tests/unit/test_summary_persistence.py, test_conversation_persistence_transaction_expiry.py: one ledger
    transaction per summary commit.
  • tests/unit/test_lifecycle_metrics_are_scraped.py (new): ledger and hold families survive the sync keep
    rule; arrival-gap observation is covered in test_sync_processing_hold.py.
  • Inherited from fix(pipeline): wire the first live writers into the in-flight ledger (C1b-1) #25125: test_record_audio_seal.py, test_record_token_lease.py, erasure tests,
    and the emulator proof tests/integration/test_pipeline_ledger_firestore.py.

🤖 Generated with Claude Code

Git-on-my-level and others added 7 commits November 12, 2026 06:11
The C1 in-flight ledger shipped its stage/deadline contract with zero
production callers, so the C2 census read an empty collection and reported a
well-formed 0/UNKNOWN instead of a missing sample.

Add the seal (capturing -> sealed, admission counted once per capture, not per
partial-seal repair), failed:upload_failed (record_upload_failed_at as end_at,
falling back to the observation time), and first-durable-summary noted hooks.
Seal and notes callers pass an ordered source revision with reopen=True, so a
proof repair can close an upload failure and a stale failure hook loses. A
delayed post-commit write reads the source and owner inside the ledger
transaction and refuses to create a row after deletion or erasure, fail-open
for the already-committed transition.

The ledger is write-only, fail-open, and never read on the hot path: one
document per capture, at most five transitions, 26h terminal TTL. Off stops
ledger writes and leaves capture behavior unchanged. Portability export and the
recursive account wipe now cover the collection.

The dead-code allowlist entry for the module is left in place; the prepared
removal hunk needs separate approval.
Add the done writer at the Home-ready point so noted rows reach a terminal, and downgrade the stuck alert to warning with a named re-arm condition. Count admission once per capture with a durable record_admitted_at marker, stamp a bounded expires_at on nonterminal rows, declare and provision the pipeline_ledger TTL, and delete the sibling ledger row with its conversation. Fix the lifecycle inventory and token-lease test, reset per-attempt observations, and use integer-microsecond source revisions.
…upload-failed

Folds the stalled C1b-1 branch into the lifecycle branch. One conflict in the
combined Grafana rules file, resolved by taking main and re-applying the single
pipeline-ledger rule change from the split source file.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…NDS per call

Default stays 600 s, so behaviour is unchanged until the value is set. Clamped
to 120..600; a malformed value keeps the default. The outbox due time and the
budget-denial reschedule follow the same value.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…minals

- noted and done ride one fenced ledger transaction instead of two, halving
  the ledger's reads and writes at the summary commit.
- A receipted relevance discard is the noise terminal, so a discarded capture
  no longer sits at transcribed until its deadline.
- The operator no-speech and stuck-backfill noise closes record their ledger
  terminal after the real close commits.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…rape; leave the ledger alert unchanged

- omi_sync_content_arrival_gap_seconds: seconds between content arrivals on one
  held conversation. The share above a candidate quiet window is the late re-run
  rate that window would buy, so the hold value is chosen from a distribution.
- The sync services' GMP keep rule dropped every omi_pipeline_ledger_* family,
  though seal and summary ledger writes run there. Keep them, with a test that
  derives the names from the producers.
- Drop the inherited downgrade of the ledger stuck alert: it no longer meets the
  alert tier contract on main and #25284 owns those rules.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@Git-on-my-level Git-on-my-level self-assigned this Nov 14, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T18:42:22.499302Z f2a03e9 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.

@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: 7cb8d23947

ℹ️ 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 on lines +382 to +383
if first.doc is None and (not then or first.outcome not in {'duplicate', 'stale'}):
return first.outcome

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 Badge Reject stale revisions before applying follow-up stages

When a delayed summary hook has an older revision than a newer nonterminal ledger row, this condition still executes its then=(DONE,) stage. The follow-up calls plan_advance without the supplied revision, bypassing the stale-event fence: a sealed row at revision 20 becomes terminal done at revision 21 when an old noted event at revision 10 arrives, even leaving home_ready_at unset. This can hide a repaired capture that is still awaiting transcription or notes from stuck monitoring. Reject stale first stages; only continue a duplicate when it actually proves the requested first stage.

Useful? React with 👍 / 👎.

Comment on lines +1327 to +1329
reason=stage,
owner_ref=user_ref,
firestore_client=client,

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 Badge Fence operator terminal writes against conversation deletion

If a conversation is deleted after an operator close commits but before _ledger_terminal runs, this hook recreates its sibling ledger row because it supplies only owner_ref. The account still exists, so _commit never checks the missing or deleted conversation and writes a new terminal after delete_conversation has removed the old row. Pass the conversation reference as source_ref, as the seal and summary hooks do, so deleting a capture cannot leave newly recreated durable ledger data.

Useful? React with 👍 / 👎.

Comment thread backend/database/conversations.py Outdated
nonterminal row would otherwise survive until its max-lifetime TTL.
"""
try:
db.collection('users').document(uid).collection('pipeline_ledger').document(conversation_id).delete()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Use an injectable Firestore client in the new deletion helper

This newly introduced database helper uses the legacy db proxy and provides no client-injection parameter, contrary to the explicit Database rule in backend/AGENTS.md. Resolve get_firestore_client() at call time and accept an optional keyword-only firestore_client so cleanup can operate against the same injected client as its caller instead of requiring module-global replacement.

AGENTS.md reference: backend/AGENTS.md:L180-L180

Useful? React with 👍 / 👎.

Comment on lines +437 to +439
if receipt.get('reason') == 'discarded' and not receipt.get('present'):
return (NOISE,)
return ()

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 Badge Recognize discard receipts with an unknown acceptance time

For a discarded conversation without summary_first_pending_at, an acceptance context, or processing_admitted_at, summary_delivery.merge_result emits reason='accept_unknown', present=False rather than reason='discarded'. This is still a committed discard receipt—the non-present accept_unknown result can only come from the discarded branch—but this mapping returns no stages. Such captures remain at transcribed and eventually count as stuck despite having completed their relevance discard. Map this receipt shape to NOISE as well.

Useful? React with 👍 / 👎.

Comment on lines +83 to +89
if result is None and admitted:
pipeline_ledger.advance(
uid,
conversation_id,
pipeline_ledger.SEALED,
revision=revision,
reopen=True,

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 Badge Reopen failed ledger rows after a proven upload repair

After a previously admitted capture encounters an upload failure, this code writes failed:upload_failed, but the real repair paths (record_seal_repair.apply_seals and record_seal_nojob.apply_backfill) clear the failure and seal the conversation directly without advancing the ledger. A subsequent call here also skips the success hook because the repair already set record_audio_closed, or because record_admitted_at is already present. The transcript projection hook cannot recover it either: it supplies neither reopen=True nor a higher revision. Consequently, a successfully repaired capture remains marked failed until a first-summary receipt happens to reopen it, concealing any intervening transcription or notes stall. Keep admission counting once-only, but wire the committed repair transition to reopen the ledger independently of admission.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 2 commits November 14, 2026 23:25
- keep the TTL provisioning step's name, which a workflow contract test reads
- flag budget count follows the merged main
- the deletion cascade now also removes the sibling ledger row

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…operator closes; surface ledger delete failures

Review findings on #25304:
1. The user document outlives its subcollections during an account wipe, so
   checking that it exists fenced nothing. Read account_deletions/{uid} inside
   the ledger transaction instead (same read count).
2. Operator no-speech and noise closes now pass the source conversation, so a
   delete between the close and the ledger write leaves no row.
3. delete_conversation no longer reports success when the sibling ledger row
   delete failed.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

@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: dfad598508

ℹ️ 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 on lines +1320 to +1321
needs no ledger undo: the restored capture's next real transition re-opens
the row with its own higher source revision.

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 Badge Reopen the ledger when an operator hide is undone

After restore_no_speech_capture or restore_stuck_backfill_noise restores a capture, the new ledger terminal remains unchanged: neither restore path updates it. Contrary to this comment, the subsequent seal cannot reopen it because plan_advance excludes SEALED from REOPEN_STAGES, and batch_pipeline_projection._observe_transcription supplies neither reopen=True nor a revision. Consequently, a restored capture that stalls before producing notes remains classified as terminal noise/no-speech and is excluded from stuck monitoring. Wire the committed restore to reopen the ledger rather than relying on a later summary receipt.

Useful? React with 👍 / 👎.

Comment on lines +94 to +98
elif result == 'upload_failed':
# A deleted capture gets no ledger row: erasure must not be followed by
# a new durable record. The firing clock is the observed failure, never
# last speech or the ledger-write time.
pipeline_ledger.advance(

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 Badge Record upload-failure terminals at the failure commit

When the pusher loses audio and calls RecordUploadBarrier.fail_recording, it persists mark_record_upload_failed and adds the capture to failed_recordings. Its subsequent finish_recording returns early for that capture before calling seal_record_audio, so this new failure-ledger branch never runs on the actual failure path. Unless another session later attempts a seal, the capture remains nonterminal in the ledger instead of recording failed:upload_failed, misclassifying known audio loss as an ordinary pipeline stall. Emit the fenced terminal after mark_record_upload_failed commits, rather than relying solely on a later seal refusal.

Useful? React with 👍 / 👎.

@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: 91ce65a101

ℹ️ 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 False
try:
from database import pipeline_ledger
from database._client import get_firestore_client

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move the new Firestore client import to module scope

The newly added function-local import violates the explicit Import Rules in backend/AGENTS.md, which require all imports at module scope. Move get_firestore_client into the module-level imports while retaining the client getter call inside the guarded execution path; lazy client construction does not require a lazy import.

AGENTS.md reference: backend/AGENTS.md:L168-L174

Useful? React with 👍 / 👎.

Git-on-my-level and others added 2 commits November 15, 2026 00:59
The Firestore TTL policy for pipeline_ledger was enabled by an edit to a
composite action under .github/. That needs the owner's explicit approval, so
it is removed here and proposed separately. Ledger rows keep their expires_at;
conversation deletion and account erasure still remove them.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
# Conflicts:
#	backend/deploy/cloud_run_gmp_sync.yaml

@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: c9aa999974

ℹ️ 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 on lines +143 to +146
from types import SimpleNamespace

from database import user_data_deletion
from database._client import delete_collection_recursive

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move the newly added test imports to module scope

These new function-local imports violate the explicit backend/AGENTS.md requirement: “All imports at module top level — never inside functions.” Move them to the module-level import block, along with the newly added REGISTRY import inside test_arrival_gap_is_observed_only_between_arrivals_of_one_hold_epoch in backend/tests/unit/test_sync_processing_hold.py. The rule applies to both test files and provides no test-only exception.

AGENTS.md reference: backend/AGENTS.md:L168-L168

Useful? React with 👍 / 👎.

Git-on-my-level and others added 3 commits November 15, 2026 01:23
The live admission writer now passes the account and source references and
takes the shared client. The test's in-memory ledger accepted neither, so the
write was refused and the test saw no row.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
# Conflicts:
#	backend/deploy/cloud_run_gmp_sync.yaml
Git-on-my-level added a commit that referenced this pull request Nov 14, 2026
…nchanged) (#25321)

# Notes quiet hold: readable from the environment, default unchanged

Split out of #25304 so it can ship on its own. Tracking: SCA-1766.

Notes on uploaded audio wait `QUIET_SECONDS = 600` after the last
content arrival before full processing.
That value was a constant. This makes it
`SYNC_PROCESSING_QUIET_SECONDS`, read per call, so it can be lowered
for every existing app build by config, with no release.

**No behaviour change in this PR.** The default is 600. Lowering it is a
separate, user-visible config
decision.

Failure-Class: none

## What changed

- `utils/sync/processing_hold.quiet_seconds()`: reads
`SYNC_PROCESSING_QUIET_SECONDS`, default 600, clamped
to 120..600. A missing or malformed value keeps 600. The floor is the
recorded-time gap at which a
conversation splits, so a typo cannot remove the debounce; the ceiling
means it can only shorten the wait.
- `admission`, the enrichment outbox due time, and the budget-denial
reschedule all use it.
- Flag budget entry with an owner and review date; contract doc updated.

## Risk when the value is lowered (not in this PR)

Notes may be written before a late upload lands. The existing
`MAX_LATE_RUNS = 1` bounds that to one extra
notes run per conversation; audio is never lost. Watch `late_runs > 0`
against its baseline.

## Kill switch and rollback

Unset the variable, or set it to 600. `SYNC_PROCESSING_HOLD_ENABLED` is
unchanged.

## Tests

`tests/unit/test_sync_processing_hold.py`: per-call read, clamp and
malformed values, outbox due time follows
the configured window.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25321?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/25321?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25321&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
# Conflicts:
#	backend/tests/unit/test_sync_processing_hold.py
Git-on-my-level added a commit that referenced this pull request Nov 14, 2026
# App: tell the server when a pendant recording ended

Client half of the end-of-recording event. Server half: #25309 (stacked
on #25304). Tracking: SCA-1767.
Independent of both: against a server without the route the call fails
quietly and nothing else changes.

Notes on uploaded pendant audio wait 600 s after the last upload because
the server cannot tell an ended
recording from one with uploads still coming. The phone knows. This
makes it say so.

Line-Count-Exception: app/lib/services/capture/capture_controller.dart |
4916 -> 4941 | four call sites that must sit where the events happen
(lane install, packet routing, status event, device stop); the detector
and reporter are in a new file
Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2725
-> 2740 | a pending-file count and one callback at the two existing
upload acceptance sites

Failure-Class: none

UI-Evidence: none -- no screen, layout or copy changes

## What changed

- **`CaptureEndDetector`**
(`app/lib/services/capture/capture_end.dart`): keeps the last time the
on-phone
VAD heard speech for the current recording. That clock is separate from
the 2 s chunk seal, which keeps
clearing its own. It reports an end on an explicit stop
(`user_initiated`), a lost or removed pendant
(`disconnect`, never claimed as user intent), or when the
server-provided silence timer runs out
(`silence_backstop`). No wall timer: the silence end is one comparison
per incoming packet. Speech after a
silence end re-opens the recording, and the next end supersedes the
earlier one.
- **`CaptureEndReporter`**: posts the end to `POST /v2/sync-capture-end`
with the number of sealed files not
yet accepted, and once more when the recording's last file is accepted,
so the final copy says nothing is
pending. At most two accepted calls per end. It is an observer only: it
never seals, flushes, publishes or
uploads, and it changes no chunk boundary. Audio up to the end that is
still being written or published is
counted as pending (`MobileBatchBuffer.unregisteredStarts`) until the
capture lifecycle seals it and the
server accepts it, so the marker cannot say zero early. Sends are
serialized; an unaccepted first report
  retries on the next accepted file; at most 16 open ends are tracked.
- A stop or lost pendant with no detected speech is reported with a null
speech time, never an invented one.
- **`MobileStandardBatch.onSpeech`**: the lane's VAD reports speech
frames with their capture time.
- **`MessageServiceStatusEvent.endSilenceSeconds`**: read from the
`mobile_batch_admission` status event.
  Absent means the phone sends no silence end.
- **`LocalWalSyncImpl`**: `pendingWalsForRecording` and an
`onRecordingUploadAccepted` callback at the two
  upload acceptance sites.

## What it does not touch

Custody. The marker never seals, uploads, deletes or releases a WAL, and
no custody rule reads it
(`app/lib/services/wals/CUSTODY.md`, new section). It is held in memory:
an app killed before the resend
takes the server's ordinary wait.

## Kill switches

- PostHog `upload_end_marker_off`: true stops the marker; absent, false
or unreadable sends it. It deletes
  nothing, so unknown keeps it on.
- Server: omit `end_silence_seconds` to stop silence ends;
`SYNC_UPLOAD_WATERMARK_ENABLED=false` ignores the
  marker entirely.

## Battery

No new radio wake on its own: the first report rides the stop, and the
resend rides an upload that just
completed. One comparison per packet while the pendant streams.

## Not in this PR

The per-file upload trace header (seal time, first attempt, gate). It
needs skip reasons plumbed through the
upload coordinator and gets its own PR.

## Product invariants affected

- INV-CAP-1 — unaffected, and the change is built so it cannot be
otherwise. The end marker is a statement
about a recording, not a control: it closes no uplink, unsubscribes
nothing, fences no sync and discards no
frame. A silence end does not stop capture or transmission; frames keep
going to the batch journal or the
socket exactly as before, and speech after a silence end simply produces
a later end. No retention or
  transmission path reads the detector or the reporter.

## Tests

- `app/test/services/capture/capture_end_test.dart` (new, 14 cases):
silence end fires once at last speech
plus the timer; speech re-opens; no timer means no silence end; stop and
disconnect are typed apart; a
recording without speech has no end; the reporter's resend, dedupe,
retry, kill switch, replacement,
  transport failure and bound.
- `app/test/backend/http/capture_end_api_test.dart` (new): request
shape; "not bound yet" is a successful false;
an old server or an outage is a typed failure (`ApiResult`), never a
silent null.
- `app/test/services/wals/mobile_standard_batch_test.dart`: an end
reported while the final chunk is open
sends pending 1, seals nothing, leaves the next frame in the same chunk,
and reports zero only after the
capture lifecycle seals and the file is accepted; a chunk whose publish
fails stays counted.
- Also in that file: speech is reported with its capture time and the
  2 s seal does not un-report it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Git-on-my-level added a commit that referenced this pull request Nov 14, 2026
## What changed and why

The original four backend unit files spent call-phase CPU re-parsing or
re-serializing large deploy documents once per test. Three more guard
failures were then reported on PR #25304 and #25268:
`test_batch_upload_coalescing.py::test_supervisor_drains_existing_holds_while_producer_off[true]`,
`test_home_transcribing_hold.py::test_stamped_capture_remains_completed_for_batch_replacement`,
and
`test_monthly_switch.py::test_switch_charges_monthly_first_then_voids_the_unpaid_yearly_invoice`.
Those three were not covered by the original #25312 diff or summary
table. Their measured calls paid for cold imports of helpers/modules
used by only one test. The imports now happen at module collection time,
outside per-test call-phase accounting.

Each YAML-heavy file parses once per process with the C loader and
deep-copies only where a test mutates. Assertions remain intact. The
three follow-up changes only move imports; no production code changed.

| File | Cost removed |
| --- | --- |
| `tests/unit/test_conversation_erasure_queue_deploy.py` | 280 KB
`deploy/runtime_env.yaml` + 82 KB `deploy-backend-stack/action.yml`
parsed in every test |
| `tests/unit/test_backend_runtime_env_validator.py` | 280 KB manifest
re-serialized through `yaml.safe_dump` before each validation |
| `tests/unit/test_pipeline_ledger_routes.py` | 160 KB
`route_policy_manifest.yaml` parsed with the pure-Python loader |
| `tests/unit/test_listen_helm_env_overrides.py` | 40 KB listen helm
workflow re-parsed for every `_step()` lookup |
| `tests/unit/test_batch_upload_coalescing.py` | Load the supervisor
modules at collection instead of importing them inside the measured test
call |
| `tests/unit/test_home_transcribing_hold.py` | Load the
recording/projection helpers at collection instead of importing them
inside the measured test call |
| `tests/unit/test_monthly_switch.py` | Preload `billing_recovery`,
which `switch()` lazily imports, before the measured test call |

## Product invariants affected

None. No production code, guard limits, allow-list entries, markers,
skips, retries, or assertions changed.

## How it was verified

The guard reports call-phase CPU (`time.process_time`), warns above 0.10
s, and fails above 1.00 s. It prints numeric per-test values only above
the warning floor; `<0.10 s` is the reportable upper bound for nodes
with no warning row. Before values below are from five recent main guard
runs:
[43613611072](https://github.com/BasedHardware/omi/actions/runs/43613611072),
[43609042294](https://github.com/BasedHardware/omi/actions/runs/43609042294),
[43608838125](https://github.com/BasedHardware/omi/actions/runs/43608838125),
[43600956507](https://github.com/BasedHardware/omi/actions/runs/43600956507),
and
[43607443879](https://github.com/BasedHardware/omi/actions/runs/43607443879),
except where a stronger PR failure is cited. The original four-file fix
was measured on PR run
[43623704701](https://github.com/BasedHardware/omi/actions/runs/43623704701).
The follow-up import changes are at head `6ccb6d91` and were measured on
PR run
[43627834886](https://github.com/BasedHardware/omi/actions/runs/43627834886):
all eight backend unit shards and backend guardrails passed. The guard
emitted no warning row for the three added test nodes, so each was below
0.10 s in that report.

Runtime-validator rows explicitly report both original run `43623704701`
and final run `43627834886`, in that order. Values without a warning row
use the guard’s `<0.10 s` reporting bound.

| Changed test node | Before (CI call CPU) | After (CI call CPU) |
| --- | ---: | ---: |
|
`tests/unit/test_conversation_erasure_queue_deploy.py::test_every_prod_dispatcher_names_the_queue_and_wipes_keep_theirs`
| 1.10 s on [#25304](#25304);
1.13 s and 1.04 s on
[#25323](#25323) | <0.10 s on
#25312 |
|
`tests/unit/test_conversation_erasure_queue_deploy.py::test_prod_contract_rejects_erasure_units_on_the_wipe_queue`
| 0.93 s on main; 0.95 s on
[#25304](#25304) | <0.10 s on
#25312 |
|
`tests/unit/test_backend_runtime_env_validator.py::test_runtime_manifest_lake_writes_allow_dev_but_require_c4_for_prod[false-1-dev]`
| 0.57 s | 0.26 s (original); 0.22 s (final) |
|
`tests/unit/test_backend_runtime_env_validator.py::test_runtime_manifest_lake_writes_allow_dev_but_require_c4_for_prod[false-1-prod]`
| 0.55 s | 0.23 s (original); 0.22 s (final) |
|
`tests/unit/test_backend_runtime_env_validator.py::test_runtime_manifest_lake_writes_allow_dev_but_require_c4_for_prod[true-0-dev]`
| 0.56 s | 0.24 s (original); 0.22 s (final) |
|
`tests/unit/test_backend_runtime_env_validator.py::test_runtime_manifest_lake_writes_allow_dev_but_require_c4_for_prod[true-0-prod]`
| 0.57 s | 0.25 s (original); 0.23 s (final) |
|
`tests/unit/test_backend_runtime_env_validator.py::test_runtime_manifest_lake_writes_allow_dev_but_require_c4_for_prod[true-100-dev]`
| 0.52 s | 0.21 s (original); 0.21 s (final) |
|
`tests/unit/test_backend_runtime_env_validator.py::test_runtime_manifest_lake_writes_allow_dev_but_require_c4_for_prod[true-100-prod]`
| 0.57 s | 0.22 s (original); 0.22 s (final) |
|
`tests/unit/test_backend_runtime_env_validator.py::test_dev_lake_writes_require_real_bindings[BUCKET_OBJECT_LAKE]`
| 0.53 s | 0.21 s (original); 0.21 s (final) |
|
`tests/unit/test_backend_runtime_env_validator.py::test_dev_lake_writes_require_real_bindings[OBJECT_LAKE_KMS_KEY]`
| 0.56 s | 0.22 s (original); 0.21 s (final) |
|
`tests/unit/test_backend_runtime_env_validator.py::test_memory_job_retirement_rejects_captured_after_window`
| 0.54 s | 0.22 s (original); 0.22 s (final) |
|
`tests/unit/test_backend_runtime_env_validator.py::test_memory_job_retirement_rejects_reintroduced_job`
| 0.52 s | 0.22 s (original); 0.22 s (final) |
|
`tests/unit/test_backend_runtime_env_validator.py::test_memory_job_retirement_rejects_retired_cron_env_on_request_path`
| 0.56 s | 0.27 s (original); 0.22 s (final) |
|
`tests/unit/test_backend_runtime_env_validator.py::test_memory_job_retirement_rejects_retired_maintenance_controls_on_request_path[MEMORY_CANONICAL_CONSOLIDATION_ENABLED]`
| 0.50 s | 0.21 s (original); 0.20 s (final) |
|
`tests/unit/test_backend_runtime_env_validator.py::test_memory_job_retirement_rejects_retired_maintenance_controls_on_request_path[MEMORY_CANONICAL_MAINTENANCE_FLEX]`
| 0.52 s | 0.22 s (original); 0.21 s (final) |
|
`tests/unit/test_pipeline_ledger_routes.py::test_route_policy_manifest_declares_both_routes`
| 0.71 s peak on main | <0.10 s on #25312 |
|
`tests/unit/test_listen_helm_env_overrides.py::test_materialize_step_installs_dependencies_before_the_secret_touches_disk`
| 0.69 s peak on main | <0.10 s (both runs) |
|
`tests/unit/test_batch_upload_coalescing.py::test_supervisor_drains_existing_holds_while_producer_off[true]`
| 0.93 s peak on main; 1.04 s and 1.09 s on
[#25304](#25304) | <0.10 s on
head `6ccb6d91` |
|
`tests/unit/test_home_transcribing_hold.py::test_stamped_capture_remains_completed_for_batch_replacement`
| 0.76 s peak on main; 1.10 s on both
[#25304](#25304) runs | <0.10 s
on head `6ccb6d91` |
|
`tests/unit/test_monthly_switch.py::test_switch_charges_monthly_first_then_voids_the_unpaid_yearly_invoice`
| 0.60 s on main; 1.10 s on
[#25268](#25268) | <0.10 s on
head `6ccb6d91` |

The three new follow-up nodes ran in Backend unit shards 4/8, 6/8, and
8/8 respectively; each shard passed. Local backend unit check passed
(`1792 passed in 21.08s`). The pre-push bounded gate passed;
`scripts/pr-preflight` and static guardrail checks also passed.

## Tests

No assertions were added, removed, skipped, or weakened. Existing tests
continue to run with the imports paid once during module collection.

## UI evidence

UI-Evidence: none -- backend test-only change.

## Failure class

Failure-Class: none

## Full census of main CPU-guard warnings at or above 0.7 s

The changed nodes above are the addressed subset. The following exact
node IDs are the remaining non-allowlisted tests observed at or above
0.7 s in the five main runs `43613611072`, `43609042294`, `43608838125`,
`43600956507`, and `43607443879`:

-
`tests/unit/test_backlog_release_gate.py::test_held_audio_takes_normal_priority_only_when_granted_and_never_the_vendor_table`
-
`tests/unit/test_batch_held_dead_letter.py::test_private_requeue_rpc_is_stage_bound_authenticated_and_idempotent`
-
`tests/unit/test_batch_pipeline_custody_property.py::test_phone_hears_completed_only_when_every_unit_is_terminal[false]`
-
`tests/unit/test_batch_pipeline_custody_property.py::test_phone_hears_completed_only_when_every_unit_is_terminal[true]`
-
`tests/unit/test_batch_pipeline_left_context.py::test_kill_switch_and_onset_start_take_no_context`
-
`tests/unit/test_batch_pipeline_pull_multi_lease.py::test_batch_transaction_cuts_transactions_and_round_trips_per_lease[False]`
-
`tests/unit/test_batch_pipeline_pull_multi_lease.py::test_batch_transaction_cuts_transactions_and_round_trips_per_lease[True]`
-
`tests/unit/test_batch_pipeline_pull_multi_lease.py::test_one_shard_leases_in_the_same_order_as_one_lease_per_transaction[True]`
-
`tests/unit/test_batch_pipeline_pull_multi_lease.py::test_write_stop_before_any_lease_commits_progress_without_parking_the_shard[False]`
-
`tests/unit/test_batch_pipeline_pull_multi_lease.py::test_write_stop_before_any_lease_commits_progress_without_parking_the_shard[True]`
-
`tests/unit/test_check_cloud_run_env_drift.py::test_gke_envfrom_configmap_keys_are_compared`
-
`tests/unit/test_check_cloud_run_env_drift.py::test_gke_helm_render_accepts_deployed_override_args`
-
`tests/unit/test_conversation_delete_accept.py::test_53_same_second_deletes_all_return_204_fast_and_all_end_erased`
-
`tests/unit/test_conversation_transcript_offload.py::test_live_in_progress_transcript_crosses_document_limit[enhanced-True]`
-
`tests/unit/test_conversation_transcript_offload.py::test_live_in_progress_transcript_crosses_document_limit[standard-True]`
-
`tests/unit/test_daily_summary_job_resilience.py::test_cursor_age_metric_retains_abandonment_signature_then_resets_on_fresh_tick`
-
`tests/unit/test_daily_summary_job_resilience.py::test_due_local_hours_include_half_and_quarter_hour_zones`
-
`tests/unit/test_enrichment_route.py::test_legacy_sync_handler_delegates_to_the_consumer_when_routed`
-
`tests/unit/test_episode_f_join_gate_metrics.py::test_refusal_counts_only_first_reason_and_keeps_join_without_extra_reads[owner-change0-snapshot]`
-
`tests/unit/test_lifecycle_invariants.py::test_latch_clause[batch:leased/entry_deadline]`
-
`tests/unit/test_live_stt_restart_burst_sim.py::test_sim_soniox_promotes_within_twenty_minutes_of_the_escape`
-
`tests/unit/test_memories_delete_batch_chunk.py::test_unlock_helpers_fence_deletion_visible_after_memory_page[None-conversations]`
-
`tests/unit/test_memory_replace_policy.py::test_canonical_dense_capture_is_bounded_before_atomic_replacement`
-
`tests/unit/test_monitoring_adapter_hpa_contract.py::test_hpa_and_adapter_changes_select_this_contract`
-
`tests/unit/test_pinecone_partition_migration.py::test_qualify_counts_every_split_upsert_in_generation_and_can_commit`
-
`tests/unit/test_pinecone_partition_migration.py::test_wide_page_splits_by_complete_serialized_payload_without_losing_records`
-
`tests/unit/test_pipeline_sim_vendor_drills.py::test_holds_never_outlive_the_outage_by_more_than_one_redrive[3600.0]`
-
`tests/unit/test_prerecorded_vendor_fail_fast.py::test_detect_failure_outcomes[post0-quota]`
-
`tests/unit/test_prerecorded_vendor_fail_fast.py::test_detect_outcome_accepted`
-
`tests/unit/test_record_gap_fill.py::test_empty_retained_set_needs_a_valid_start[nan]`
-
`tests/unit/test_record_gap_fill.py::test_empty_retained_set_needs_a_valid_start[None]`
-
`tests/unit/test_record_gap_fill.py::test_empty_retained_set_needs_a_valid_start[not-a-time]`
-
`tests/unit/test_record_seal_cluster_repair.py::test_jobs_kill_switch_restores_exact_old_hash_scan[off]`
-
`tests/unit/test_replay_harness_capture.py::test_bucket_names_come_from_backend_config_and_runtime_overrides`
-
`tests/unit/test_soniox_batch_async.py::test_poll_wait_releases_http_permit_and_never_repeats_submission`
-
`tests/unit/test_text_window_abstention.py::test_mixed_invalid_text_applies_owner_without_labeling_bad_segment[window0-first]`
-
`tests/unit/test_verify_backend_release_vector.py::test_deploy_script_argparse_percent_escapes[backend/scripts-*.py]`
-
`tests/unit/test_voice_message_syncing_cleanup.py::test_cleanup_leaves_other_users_and_other_folders_alone`
-
`tests/unit/test_voice_message_syncing_cleanup.py::test_voice_question_wav_in_syncing_dir_is_deleted_after_the_stream`
-
`tests/routers/test_import_transcripts_route.py::test_route_policy_records_the_byok_check_its_auth_runs`

Already allowlisted with written reasons (not changed; the `[1]`
parameterized row appeared in the main census and is covered by this
base-node allow-list entry):

-
`tests/unit/test_speaker_learning_round2.py::test_legacy_admission_bounds_candidates`
-
`tests/unit/test_sync_input_limits.py::test_opus_disk_full_mid_file_raises_capacity_pressure_and_keeps_no_prefix`
-
`tests/unit/test_batch_live_preview.py::test_all_three_cohorts_share_batch_bucket_and_summary_survives_admission_rollback`
-
`tests/unit/test_batch_pipeline_pull_multi_lease.py::test_long_heads_never_push_one_transaction_past_the_write_budget[None]`
-
`tests/unit/test_batch_pipeline_pull_multi_lease.py::test_long_heads_never_push_one_transaction_past_the_write_budget[1000000]`

The remaining nodes are workload/structural costs or runner-sensitive
isolated imports, not repeated parsing of the large deploy documents
fixed here. The HPA selector test walks 27 chart sources; the batch
transaction, custody, partition, lifecycle and outage drill nodes
exercise the volume or state space named in their assertions. No guard
exception was added for any of them.

## Still open

Merge and the post-merge “next three main runs” check belong to the
merge/verify stages. After merge, report those run links and per-test
results on the issue; then post the merge SHA so the lifecycle owner can
sync.
Git-on-my-level added a commit to Git-on-my-level/omi that referenced this pull request Nov 14, 2026
…sts stay cheap

The backend unit CPU guard fails a test above 1.00 s of call-phase CPU. Four
test files sat at 0.7-1.0 s on CI purely because they re-parsed large deploy
documents with the pure-Python YAML loader (or re-serialized them with the
pure-Python dumper) once per test:

- test_conversation_erasure_queue_deploy.py parsed the 280 KB
  deploy/runtime_env.yaml and the 82 KB deploy-backend-stack action.yml in
  every test; two tests reached 1.10 s and 0.95 s on PR BasedHardware#25304.
- test_backend_runtime_env_validator.py already loads with the C loader but
  rewrote the whole 280 KB manifest through yaml.safe_dump before validating.
- test_pipeline_ledger_routes.py parsed the 160 KB route_policy_manifest.yaml
  with the pure-Python loader.
- test_listen_helm_env_overrides.py re-parsed the 40 KB listen helm workflow
  for every _step() lookup.

Each file now parses its documents once per process with the C loader (already
used elsewhere in this suite) and hands out deep copies to tests that mutate.
No assertion, marker, skip, allowlist entry or guard limit changed.
Git-on-my-level and others added 2 commits November 15, 2026 06:54
Ruling on SCA-1760 (23:37Z): the approved design limits ledger readers to the
census routes. The export collection and section, and the assertions specific
to them, are removed. Erasure is unchanged: the ledger is still purged with the
account and deleted with its conversation, with its regression coverage.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 15, 2026
…re lifecycle ledger (#25325)

# Enable the Firestore TTL policy for the capture lifecycle ledger

Split out of #25304 on purpose. Tracking: SCA-1760. Should merge after
#25304, which adds the writers whose
rows this expires; merging it earlier is harmless.

Failure-Class: none

## What changed

`.github/actions/sync-backfill-lifecycle/action.yml`, the existing
platform step "Provision and verify sync
ledger TTL": after it enables and verifies the TTL policy on
`sync_content_ledger`, it does the same for the
`pipeline_ledger` collection group (`expires_at`). Thirteen added lines
in an existing composite action. No
new workflow, no change to triggers, permissions, secrets or inputs; the
step keeps its name and its
condition (`mode == 'platform'` and `provision_sync_ledger_ttl ==
'true'`).

## Why

Ledger rows are one small, content-free document per capture: stage,
deadlines, bounded reasons and
timestamps. They are derived state, never user content. Each row carries
its own `expires_at` (26 hours after
a terminal; 7 days after the last transition for a nonterminal row,
added in #25304). Without the TTL policy
that field does nothing and the collection grows by one row per capture
forever.

## What it deletes, exactly

Only documents in `pipeline_ledger` whose `expires_at` has passed. Rows
written before #25304 that are not
terminal have `expires_at` unset and are not touched by the policy.
Nothing outside that collection group is
affected. Raw audio and conversations are not involved. Conversation
deletion and account erasure already
remove ledger rows directly, with or without this.

## Approval basis

Standing approval from the owner (2026-11-15): expiry on derived,
content-free collections with the
retention stated, and edits to existing `.github/` actions that add no
workflow and change no triggers,
permissions or secrets, are covered by a test and are called out here.

## Rollback

Revert this PR, then disable the policy once: `gcloud firestore fields
ttls update expires_at
--collection-group=pipeline_ledger --disable-ttl`. Documents already
expired are not restored; they are
derived and are rewritten by the next transition of a live capture.

## Tests

`backend/tests/unit/test_sync_two_lane.py`: the step enables and then
verifies the policy for both ledgers,
enables exactly two, and contains no delete or disable.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25325?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/25325?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25325&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
@Git-on-my-level
Git-on-my-level merged commit 4538db3 into main Nov 15, 2026
64 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/lifecycle branch November 15, 2026 01:15
Git-on-my-level added a commit that referenced this pull request Nov 15, 2026
… wait (server) [SCA-2344] (#25309)

# End-of-recording proof: notes start when the phone proves a recording
has landed

Builds on #25304, which is merged; base is `main`. Tracking: SCA-1766,
SCA-1767. App half: #25311 (merged).
Design: `DESIGN:` comment on SCA-1767 and the change note

`backend/docs/listen_pusher_pipeline/changes/2026-11-14-capture-end-proof.md`.

Notes on uploaded audio wait 600 s after the last content arrival
because the server cannot tell an ended
recording from one with uploads still coming. The phone knows. This is
the server half: it accepts the
phone's end marker and uses it. Old clients send nothing and behave
exactly as today.

Line-Count-Exception: backend/routers/sync.py | 3883 -> 3945 | the
capture-end route and the trace header sit beside the upload route they
extend; policy and storage are in new modules, and splitting this router
is separate debt
Line-Count-Exception: backend/utils/sync/pipeline.py | 4031 -> 4041 |
the frozen legacy copy of the enrichment callback must mirror the
callback's admission call (parity test), and the sync writer declares
the clock shift it applied to the stored times; one argument, one
import, one field
Line-Count-Exception: backend/utils/sync/assignment.py | 1568 -> 1574 |
pass the writer's clock shift to the hold state on the assignment write
that already happens; no new read or write
Line-Count-Exception: backend/routers/listen/receiver.py | 2978 -> 2980
| one field on the existing batch admission status event and its import

Failure-Class: none

UI-Evidence: none -- the only client files changed are generated API
type definitions for the new route; no screen, layout or copy changes


## Clock skew (review round 2, goal-owner ruling on SCA-2344)

The marker is on the phone clock. Production's sync writer stores
uploads from a phone running ahead shifted
onto the server clock by a per-request offset (median 171 s), so the
first version read a complete recording
as `content_behind` and kept the quiet wait. Fix: the writer passes the
shift it applied, the hold state keeps
it (`content_clock_offset`) beside the row end it describes
(`content_clock_end`), and the proof adds it back
so both sides are on the phone clock. The three proof rules, the 5 s
tolerance and the quiet fallback are
unchanged. A row whose end has moved since reads `clock_unknown` and
waits. Rows that were never shifted carry
neither field. Tests:
`test_a_phone_clock_171_seconds_ahead_still_proves_a_complete_recording`
(complete,
behind, after the end, no recorded shift, moved end),
`test_the_hold_keeps_the_shift_only_for_the_arrival_that_sets_the_row_end`,
and the stored-row assertion in `test_sync_capture_time_skew.py`.

## What changed

- **`POST /v2/sync-capture-end`** (`routers/sync.py`):
`recording_session_id`, `end_type`, `last_speech_at`,
`end_decided_at`, `sent_at`, `pending_wals`. Stored as one field,
`capture_end`, on the recording's session
document (`database/capture_end.py`). It never creates a session,
changes a binding, finalizes, deletes or
  alters custody. No session: `accepted: false, retry: true`.
- `last_speech_at` may be null: a stop with no detected speech is stored
as it is. It types the end but can
never prove it (`no_speech_clock`), because an accepted upload is not
yet a transcript.
- **End proof in hold admission** (`utils/sync/processing_hold.py`,
`utils/enrichment/callback.py`): a row
that would otherwise wait and carries
`external_data.recording_session_id` reads that one document. The
wait is skipped (outcome `end_proof`) only when the phone has no file
left to upload, assigned content
reaches the phone's last speech, and nothing on the row is later than
the end. Unchanged, immaterial and
late-cap rules still apply. Any other result, a read failure included,
leaves the quiet rule as it is.
- The frozen legacy copy of the callback in `utils/sync/pipeline.py`
mirrors the same admission call, as its
parity test requires; both call the shared
`database.capture_end.proven`.
- **Why the session and not the conversation:** uploaded audio does not
always land in the conversation bound
to the recording (assignment can fall back to recorded time, live
overlap or the temporal index).
- **Ledger end fields** (`database/pipeline_ledger.py`): `record_end`
sets `end_type`, `end_at`,
`end_observed_at`, `last_speech_at` on an existing row without moving
its stage; a known end is never
replaced by a weaker one. Server-known ends are typed when a
finalization intent is accepted
(`utils/conversations/lifecycle.py`): client finalize `user_initiated`,
server recovery
  `silence_backstop`, bare capture end `unknown`.
- **Upload trace** header `X-Omi-Upload-Trace` on
`/v2/sync-local-files`: measurement only, feeds
  `omi_sync_seal_to_accept_seconds{gate}`.
- **`end_silence_seconds`** on the `mobile_batch_admission` status event
(`SYNC_CAPTURE_END_SILENCE_SECONDS`,
  default 120, clamped 60..1800, `0` withdraws it).
- Route policy entry, app-client OpenAPI and generated Dart, TypeScript
and Swift types.

## Reads and writes

Per recording: one or two calls, each one transaction with one read and
at most one write on the session
document, plus one ledger transaction (one read, one write) when the
marker is new. At admission: one read
per evaluation that would otherwise wait, only for rows with a recording
session id. No query, no scan.

## Kill switch and rollback

`SYNC_UPLOAD_WATERMARK_ENABLED=false` (default on): the route stores
nothing, admission reads nothing, the
trace header is ignored, phones get no silence timer. Revert is clean:
the only stored state is one field
on session documents.

## Risk

Notes written before late audio lands. Bounded by the existing
`MAX_LATE_RUNS = 1`: one extra notes run,
never lost audio. Watch `late_runs > 0` against its baseline.

## Tests

- `tests/unit/test_sync_capture_end.py` (new): marker shape and
refusals, proof rule, store idempotence and
supersession, admission with and without proof, ledger end fields and
precedence, trigger typing, silence
  timer bounds, callback read gating, kill switch.
- `tests/unit/test_sync_v2.py`: route stores and types the ledger end;
malformed marker 422; store outage
  503; kill switch stores nothing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Git-on-my-level added a commit that referenced this pull request Nov 15, 2026
…and wait for the full transcript (#25340)

Episode summaries wait for retained pending transcripts, recover
committed late speech through transactional revision markers, and scale
detail to the episode. Owner ruling 2026-11-15 permits all memory
categories, attributions and tiers inside the account as summary
background; account isolation, deletion, explicit rejection/invalidation
and chat's paid-plan lock checks remain.

The composer uses the shared is_prompt_memory_visible quality/paywall
predicate. It does not use chat's additional canonical self-profile/slot
predicate: summary background can describe another person, a document or
external wisdom. Category, kind, subject, attribution and date accompany
memories; missing attribution remains unknown. Background cannot
establish episode events, attendance, speaker identity or a new
commitment. Chat behavior and canonical memory writes remain unchanged.

Profile context always includes name/language; successful bounded
gathering adds timezone, stored ai_user_profile.profile_text, five
active goals and up to20 people already resolved in the transcript.
Failures/timeouts retain name/language only and count a shared fallback.
Every context source shares one8-second caller deadline, four
optional-context workers with no queue, and640 charged data reads; late
results cannot publish. No cache keeps memory content.

The episode_composer gateway lane currently rejects tools
(config_loader.py:568), so this change uses at most3 deterministic
retrieval queries: whole episode, named people/projects, and recurring
topics/commitments. Each query returns at most10 unified matches.
Canonical and historical memory generations both participate after
canonical authority succeeds; suppression wins over any legacy
duplicate. A canonical/provider failure never falls back to legacy data.
Results deduplicate and rank into the existing3500-token memory block
plus1000-token profile block. Real read-only chat-registry tools are the
immediate follow-up; no unbounded loop, gateway capability change, new
calendar context or prior-episode context is implemented tonight.

Worst logical cost:6 embedding calls+6 Pinecone queries+0
Typesense/compose, compared with1+1+160 reads before the owner ruling.
Each optional search makes one whole-operation attempt; real
proxy/owner-index autospecs guard signatures. At the supplied27000/day
baseline this is at most162000 embeddings and162000 vector queries.
The640-read data allowance covers profile, goals, people, canonical
hydration/lineage and legacy hydration/suppression; provider routing,
BYOK/quota/readiness/control reads and SDK retries are additional. There
is no extra LLM planning turn; context gathering still returns within8
seconds, but live recall/fallback rate is unverified.

Cost scenario (not a measured invoice): repository Luna
input$0.10/M/output$0.60/M gives maximum4500-token
context$0.00045/compose or$12.15/day; each extra1000 generated tokens
adds$0.00060/compose. The repo has no retrieval rate card. Using
documented vendor-list assumptions of embedding$0.13/M tokens at1000
tokens/call, regional Firestore$0.03/100k reads, and Pinecone$16/M RU:
six embeddings+646 modeled data/routing reads+six1-RU queries
total$0.0010698/compose or$28.8846/day, versus the
old$0.0001943/$5.2461. At10RU/query retrieval is$0.0019338/compose
or$52.2126/day. Add maximum context input$12.15/day and any longer
output/control reads/retries. Actual region, contract and namespace RU
are unmeasured. Sources and assumptions:
backend/docs/listen_pusher_pipeline/changes/2026-11-15-composer-review.md.

The five independent default-on controls bind on dev/prod Cloud Run
backend, backend-sync, backend-sync-backfill, backend-integration and
GKE backend-listen/pusher. Rollback the affected behavior with
EPISODE_COMPOSER_CONTEXT_ENABLED, EPISODE_COMPOSER_DETAIL_ENABLED,
EPISODE_COMPOSE_TRANSCRIPT_WAIT_ENABLED,
EPISODE_COMPOSE_TRANSCRIPT_READY_ENABLED or
CONVERSATION_NOTES_SCALED_DETAIL_ENABLED=false and roll its hosts. No
new flag or budget increase. COMPOSER_VERSION remains
episode_composer_v2 and context stays outside fingerprint(): deploying
alone recomposes no old episode.

The existing batch assignment transaction writes
episode_transcript_updated_at with accepted speech, including
appends/rollovers; exact retries preserve it. No extra assignment
document write/transaction or heavy producer import. Process-local
receipts are a fast path; a lost receipt recovers on the next qualifying
Home list/page read, with no periodic receipt sweep and no wall-clock
bound before that read. The composed_transcript_updated_at watermark
acknowledges covered/unchanged evidence without another paid call.
Removed members contribute no Home recovery signal; historical revision
timestamps stay. Wait blocker IDs suppress unrelated receipt churn,
honor the wait kill switch, and preserve
membership/visibility/regeneration wakeups. Active waits add0 Home
database reads; bounded wait remains6h.

Notes density scales only above threshold; short packets stay
byte-for-byte unchanged. notes-4 and its scaled discriminator invalidate
long-note checkpoints only on already-requested processing; unchanged
short/flag-off notes-3 checkpoints are reusable. Deploy schedules0 notes
regeneration jobs. Existing #25304 lifecycle ledger writers and
independent member-notes hold remain intact; receipt and notes
completion tests cover one paid episode compose without a restarted
delay.

Earlier paid comparison used snapshot-injected memories and bypassed
production vector search; it did not verify this new retrieval. No new
paid calls occurred after the dev gateway token was deleted. Live
grounding, provider latency/cost and serving behavior for the
owner-ruling head remain unverified. Prior durable head796eb506dd305
passed467 affected files (16089cases/16skips) and the exact installed
hook; this owner-ruling head reruns affected tests/typecheck/hook.

Failure-Class: none
INV-MEM-1: exactly three tiers and one canonical collection remain. The
explicit owner-summary Archive/background exception follows owner
ruling2026-11-15; default chat/MCP/third-party access is unchanged.
INV-MEM-2: vectors supply IDs only; authoritative owner-scoped hydration
supplies content. No raw vector payloads become prompt facts.
INV-MEM-3: canonical readiness, identity, deletion and suppression
checks still fail closed. The historical adapter remains a read-only
input to MemoryService after successful canonical checks, never a
recovery route around a failure.
INV-MEM-4: no memory writes, promotions, lifecycle mutations or
shared-graph changes; canonical promotion authority remains unchanged.

Author model: GPT-6.1 Sol. New local head awaits the lead's push, CI and
independent review. No push or deploy by this lane; origin/main merged
locally at the lead's instruction.

Line-Count-Exception: backend/database/vector_db.py | 1442 -> 1506 |
Keep the existing lifecycle owner; bounded owner-summary read options
preserve chat defaults and authoritative hydration.

Line-Count-Exception: backend/utils/batch_pipeline/projection.py | 1774
-> 1778 | Keep the existing lifecycle owner; bounded owner-summary read
options preserve chat defaults and authoritative hydration.

Line-Count-Exception: backend/utils/episodes/composer.py | 1734 -> 2025
| Keep the existing lifecycle owner; bounded owner-summary read options
preserve chat defaults and authoritative hydration.

Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py |
3970 -> 4035 | Keep the existing lifecycle owner; bounded owner-summary
read options preserve chat defaults and authoritative hydration.

Line-Count-Exception: backend/utils/memory/memory_service.py | 4709 ->
4764 | Keep the existing lifecycle owner; bounded owner-summary read
options preserve chat defaults and authoritative hydration.

Line-Count-Exception: backend/utils/sync/assignment.py | 1574 -> 1580 |
Keep the existing lifecycle owner; bounded owner-summary read options
preserve chat defaults and authoritative hydration.

Final local evidence at a346cd0: the exact installed pre-push hook
passed end to end at04:16:38Z (55 preflight checks; canonical backend
typecheck0 errors/83,294 warnings;21 backend-unit files/1205 cases;2080
passing cases across phases). The467-file affected selection passed16098
cases with16 normal marker skips at04:22:08Z; a five-file combined
context/chat ordering probe passed58 cases without collector errors.
Source is clean; new-head CI/review awaits the lead's push. No paid/live
retrieval acceptance is claimed.

Final merged head `07fad0a9228fa32501b18a7b828791e630f14b0c` includes
origin/main `e50f1f20bf40bb17066290b607779305cf77c945`, without
conflicts. Regenerated runtime env and registry reproduce the committed
files; read-lever manifest is current; flag count287 equals len(names).
Installed pre-push PASS2026-11-15T04:30:54Z:56manifest checks, canonical
typecheck0errors/83532warnings,21backend-unit files,2082passing cases
across phases. Full affected selection467files/16100passed/16normal
skips at04:41:29Z; deploymentcontracts461passed/3skips;
durable/importclosure359passed/3skips. No guard or allowlist changes. No
push or deploy by this lane.

Final review delta: dedicated cancellable owner-summary clients disable
provider retries and key/route fallback. Pinecone7.3.0 IndexAsyncio
private retry_options=JitterRetry(attempts=1), set before the first
request, redirects off; asyncio.timeout covers the request because its
async SDK ignores _request_timeout. Direct OpenAI2.38.0
AsyncOpenAI(max_retries=0, timeout=remaining), HTTPX0.28.0
AsyncHTTPTransport(retries=0), bypassing LangChain1.1.14. Gateway
isolated HTTPX request, existing gateway provider max_attempts=1.
Maximum6embedding+6Pinecone provider attempts (gateway adds6HTTP hops);
one8s context deadline cancels active IO, with cooperative transport
teardown and no retry tail. No OS-level hard real-time guarantee for a
stalled resolver/kernel. Fixed speech/membership withNmembers finalizing
notes once costs at mostN+1successful composes; notes finishing before
first compose cost1, duplicate finalizations0. Notes refresh keeps
existing pending speech timing and adds no new delay. #25309 narrows but
does not remove this race. No new jobstore reads.


Summary embedding construction resides in a new helper; clients.py is
byte-identical to main so the existing notes/L1 routing digest and
historical checkpoints do not change.
kodjima33 added a commit that referenced this pull request Nov 29, 2026
…ed audio (#26708)

## Problem

Pendant conversations that reach the server as phone uploads wait 600 s
after the last audio arrival before their first summary. Prod,
2026-11-28 15:35 to 18:35 ET, 3,790 Home-visible pendant conversations:
15% sat in that wait, with a median of 17.1 min from end of speech to
first summary.

## Change

`SYNC_PROCESSING_QUIET_SECONDS=120` on the four prod backend Cloud Run
services (`backend`, `backend-sync`, `backend-sync-backfill`,
`backend-integration`; the projection pump inherits it from
integration). No code change: 120 is the floor
`processing_hold.quiet_seconds()` already clamps to, and the knob was
added in #25304 for exactly this.

`SYNC_REPROCESS_SETTLE_SECONDS` stays 600, so a re-run after late audio
is still coalesced over ten minutes.

## Expected effect

Simulated on the same 3,790 conversations: the affected group's median
goes from 17.1 to 9.1 min, the overall median from 10.5 to 8.5 min. Of
content arrivals that follow another within ten minutes, 96% follow
within 120 s (`omi_sync_content_arrival_gap_seconds`, 24 h).

## Cost

cost-delta-usd-day: 110

That is a ceiling: about 27.7k arrivals a day land 120 to 600 s after
the previous one, and each can cost one more full processing run at
about $0.004. Immaterial appends and the one automatic late run per
conversation keep the real figure below it. Approved by Nik on
2026-11-29 with this number.

## Verification

- `backend/scripts/pre-deploy-check.sh`: 709 passed.
- `make preflight`: 21 checks passed.
- `tests/unit/test_sync_processing_hold.py`,
`tests/unit/test_sync_capture_end.py`: 132 passed.
- With the value set, `processing_hold.admission` returns `quiet_wait`
until `last_content_at + 120`, then `ready`.

After deploy: `omi_sync_processing_hold_total` by outcome (`ready`,
`late_cap`), and first-summary latency on the same cohort.

## Rollback

Remove the four overlay entries (default 600).

## Product invariants affected

- INV-MEM-4: named because the prod runtime env overlay is under its
path glob. Unchanged: this adds one notes-timing value and touches no
memory intake, consolidation or promotion setting.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/26708?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/26708?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F26708&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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