Skip to content

feat(sync): end-of-recording proof lets notes start without the quiet wait (server) [SCA-2344] - #25309

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

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

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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

@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-15T04:11:42.325512Z d7ca07e 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: 7a754f57cd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/routers/sync.py
Comment on lines +385 to +387
def _store_capture_end(uid: str, recording_session_id: str, marker: dict) -> str:
outcome, conversation_id = capture_end_db.store(uid, recording_session_id, marker)
if outcome == 'stored' and conversation_id:

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 Advance the enrichment wake when end proof arrives

For production uploads enrolled with sync_hold=True, utils/enrichment/outbox.py:488–497 schedules the obligation at least quiet_seconds() after arrival, and its claim path refuses to run before due_at. This endpoint only stores the marker and updates the ledger; it never advances that obligation or schedules an earlier wake. Consequently, even when a valid zero-pending marker arrives before processing, the callback cannot evaluate the new proof until the existing 600-second wait has elapsed. Update the outbox scheduling as well as callback admission, including when the marker precedes the final content assignment.

Useful? React with 👍 / 👎.

Comment on lines +86 to +88
class _Client(_FakeClient):
def transaction(self):
return _UpdatingTransaction(self.store)

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 the required strict Firestore transaction fixture

The new capture-end transaction tests use a custom client backed by _FakeTransaction, whose writes mutate a dictionary immediately and whose document reads do not enforce read-before-write ordering. These tests can therefore pass for transaction sequences that Firestore rejects. backend/AGENTS.md explicitly requires StrictFirestore for document-reference transaction tests using set/update; replace this permissive adapter with that fixture for the new store and ledger tests.

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

Useful? React with 👍 / 👎.

Comment on lines +460 to +464
if current_at is not None:
if END_TYPE_RANK[kind] < END_TYPE_RANK.get(current_kind, 0) and at <= current_at + 1:
return Plan(None, 'stale')
if kind == current_kind and abs(at - current_at) < 1:
return Plan(None, 'duplicate')

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 older same-type ends before overwriting the ledger

When two end-marker requests overlap, _store_capture_end commits the session marker and updates the ledger in separate transactions, so the older request's ledger write can execute after the newer request's. This guard rejects lower-ranked ends and near-duplicates, but accepts an older end of the same type: an existing user_initiated end at 2000 is overwritten by one at 1000. The session correctly retains the newer marker while the ledger regresses end_at, end_observed_at, and last_speech_at, corrupting end-to-ready measurements. Fence older same-type decisions in the ledger transaction as well.

Useful? React with 👍 / 👎.

Comment thread backend/utils/enrichment/callback.py Outdated
Comment on lines +71 to +73
except Exception as error:
logger.warning('event=capture_end_proof outcome=read_error exception_type=%s', type(error).__name__)
return False

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 Emit the required fallback telemetry on marker-read failure

When the session-document read fails, this new branch degrades to the quiet-wait policy but emits only a warning, returning before even recording a proof result. Consequently, the shared fallback metrics cannot distinguish dependency failures that disable end-proof acceleration from normal waiting. backend/AGENTS.md requires new fallback paths to call utils.observability.fallback.record_fallback; emit that event with a degraded outcome here, while keeping absent markers and disabled-feature checks as ordinary soft paths.

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

Useful? React with 👍 / 👎.

…mission call in the legacy callback copy

- New metric labels go through reason_label() with closed enums.
- The frozen legacy copy of the enrichment callback must stay structurally
  identical (parity tripwire), so the proof helper moves to
  database.capture_end.proven and both copies pass it to admission.

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: 27b5434865

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/utils/sync/capture_end.py Outdated
Comment on lines +162 to +166
finished = _seconds(row.get('finished_at'))
speech, decided = _number(marker.get('last_speech_at')), _number(marker.get('end_decided_at'))
if not finished or speech is None or decided is None:
return 'absent'
if finished < speech - TOLERANCE_SECONDS:

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 Compare end proof and assigned content on the same clock

For uploads from a phone whose clock is ahead of the server, utils/sync/pipeline.py subtracts capture_time_offset before persisting finished_at, but the marker retains device-clock last_speech_at and end_decided_at. Comparing these directly rejects fully assigned recordings as content_behind: with a +350-second phone skew, device last speech at 1350 becomes a stored finish at 1000, which fails this check despite zero pending files. Apply the upload's clock normalization consistently to the proof inputs, or compare against a retained device-clock content extent, so supported clock-skewed uploads can receive end-proof acceleration.

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: e26ee1958b

ℹ️ 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 +14 to +15
from utils.sync import capture_end as policy
from utils.sync.capture_end import FIELD

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 Keep capture-end policy above the database layer

The new database adapter imports utils.sync.capture_end and owns the proven() policy orchestration, reversing the strict database → utils dependency hierarchy required by backend/AGENTS.md. Consequently, storage callers now transitively load the sync policy and its observability dependencies. Keep the adapter responsible for storing/loading markers, and move proven() into the utility layer so it can call the database adapter without reversing that boundary.

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

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

/approve-ui c2bf632

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

ℹ️ 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 +102 to +104
recording = (conversation_data.get('external_data') or {}).get('recording_session_id')
if not policy.enabled() or not isinstance(recording, str) or not recording:
return False

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 Preserve recording identity on sync-assigned rows

When uploaded speech lands in a new sync conversation rather than its original live row, this lookup cannot find the accepted marker. process_segment constructs the incoming conversation without external_data.recording_session_id, and utils/capture/sync_coverage.py::annotate_identity only annotates capture_evidence; assignment.py does not populate the external-data field either. Consequently, these rows always return False here even after all speech has landed. Carry the recording identity through assignment, or resolve it through the persisted capture identity, so end-proof acceleration also works for uploads assigned away from the original live conversation.

Useful? React with 👍 / 👎.

Comment on lines +166 to +170
if finished < speech - TOLERANCE_SECONDS:
return 'content_behind'
if finished > decided + TOLERANCE_SECONDS:
return 'resumed'
return 'proven'

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 Verify pending server work before treating the end as proven

If the final WAL is assigned while an earlier accepted WAL is still queued or retrying, pending_wals=0 and a matching finished_at incorrectly produce proven: upload acceptance is asynchronous (/v2/sync-local-files returns 202), and _OrderedTurnstile only orders segments within one job. Reaching the final timestamp therefore does not establish that earlier speech has been assigned. When admission evaluates this state, it can bypass the remaining quiet wait and summarize incomplete content; subsequent arrivals also consume the single permitted late run. Require server-side completion or contiguous assignment evidence for the recording before returning proven, rather than relying solely on its maximum content timestamp.

Useful? React with 👍 / 👎.

Comment thread backend/routers/sync.py
Comment on lines +723 to +725
capture_end.observe_trace(
x_omi_upload_trace if isinstance(x_omi_upload_trace, str) else None, received_at=capture_received_at
)

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 seal-to-accept latency only after successful admission

For uploads rejected or deferred by admission, this call still records a successful acceptance latency: it runs before the memoized custody wait, cutover-standby response, backfill-capacity rejection, and fair-use restriction checks in this endpoint. observe_trace unconditionally adds the sample to omi_sync_seal_to_accept_seconds, whose documented meaning is time until server acceptance. A file retried repeatedly during a hold therefore contributes multiple pre-acceptance samples, and even a file never accepted contributes to the distribution, corrupting the gate-specific latency readout. Emit this observation only once the request has successfully obtained durable custody or an existing accepted receipt.

Useful? React with 👍 / 👎.

…d but never proves it

Review finding 3 on the app half (#25311): an explicit stop or lost pendant
with no detected speech must still be reportable, without an invented speech
time. last_speech_at is optional; proof returns no_speech_clock for it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
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
…ore upload is accepted (#25332)

# App: measure how long a sealed recording file waits before the server
accepts it

Tracking: SCA-1766. Server side that reads the header: #25309.
Independent of it: a server that does not
know the header ignores it.

The largest unexplained term in capture-to-notes latency is the upload
tail: files that sit on the phone for
hours after they are sealed. Nothing measures it per file or says which
gate held it. This adds that
measurement and changes no upload behaviour.

Failure-Class: none

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

Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2725
-> 2739 | the trace is prepared at the two existing upload sites and a
rate-limit note at the existing catch blocks; the logic is in a new file
Line-Count-Exception: app/lib/backend/http/api/conversations.dart | 1524
-> 1528 | one header on the existing upload request
Line-Count-Exception:
app/lib/services/wals/recording_transfer_coordinator.dart | 601 -> 605 |
one note at each of three existing gates

## What changed

- **`UploadTrace`** (`app/lib/services/wals/upload_trace.dart`, new):
remembers the last upload gate that
closed and when, and per oldest file the first attempt time and attempt
count. In memory, bounded.
- **Header** `X-Omi-Upload-Trace:
sealed=<epoch>;first=<epoch>;gate=<label>;attempts=<n>` on
`POST /v2/sync-local-files`, for the oldest file in the batch. `sealed`
is the file's start time plus its
length. `gate` is named only if it closed after the file was sealed;
otherwise `none`.
- **Gates noted:** `background` (a wake skipped while backgrounded),
`in_flight` (coalesced into a running
pass), `auto_upload_off`, `rate_limited`. The closed label set matches
the server's; anything else is
`other`. `offline`, `server_hold` and `retries_exhausted` are in the set
and not yet noted anywhere: those
paths do not pass through one place, and I would rather report `none`
than guess.

## What it does not touch

When or whether anything uploads. No gate reads the trace. The header is
taken by first file path inside the
existing upload call, so no uploader signature or test fake changes.

## Limits of the measurement

Memory only: after an app restart, older waits report `gate=none` and
`attempts=1`. A long tail with
`gate=none` therefore means "the app was not running or nothing woke
it", which is itself an answer.

## Product invariants affected

- INV-CAP-1 — unaffected. The trace reads timestamps and writes one
request header. It closes no uplink,
  fences no sync and discards no frame.

## Tests

`app/test/services/wals/upload_trace_test.dart` (new, 7 cases): first
attempt; a gate after the seal is named
and the first attempt time is kept; a gate before the seal is not
blamed; unknown labels fold to `other`; a
missing seal time sends nothing; an accepted upload resets the count;
memory stays bounded; the label set.
Existing coordinator, batch lane and periodic sync tests pass unchanged.

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

Updates the account-scoped UI approval policy requested by David. The
five exact outputs of the TypeScript and Swift OpenAPI generators no
longer count as UI; the Swift output also skips immutable source
inspection. Real UI files, including other generated Swift files and
renamed UI, remain gated.

Nik (43514161) and David (9387252, Git-on-my-level) can issue
current-head `/approve-ui <sha>` and `/reject-ui <sha>` commands. The
newest matching command wins. Incomplete-evidence failures, same-head
multi-PR reconciliation, the bot marker comment, and workflow
triggers/permissions are preserved. The check manifest's rationale
reflects the new policy; its registration and CI budget are unchanged.

## Consequence

9387252 is also ACTOR_ID, the account this gate checks, and coding
agents push and comment as that account. After this change, a comment
from that account can approve that account's own UI changes. The gate
will no longer separate “an agent working as David” from “David”.

## Verification

- `node --test .github/scripts/tests/ui-author-approval.test.cjs`: 18
tests pass, covering generated-only diffs, mixed UI diffs, real web UI,
both approvers, stale SHAs, revocation, ignored third accounts, Swift
inspection/rename boundaries, and existing fail-closed behavior.
- `make preflight`: passed all 14 selected checks.
- Post-commit `scripts/pr-preflight --pr-body-file ../pr-body.md`:
passed all 14 selected checks and PR metadata validation.
- [CI
Hygiene](https://github.com/BasedHardware/omi/actions/runs/43626282268/job/132544418611):
passed at `2e757e18f29a062b7540450ec37f9642a75486dc`; logs confirm all
18 gate tests and all 14 preflight checks pass. Other CI jobs were still
running when this evidence was collected.
- After merge, verify “UI author approval” succeeds without approval on
#25309 once it targets main; record its then-current head SHA.

## Product invariants affected

none

Tracks SCA-2284.
Base automatically changed from lane/lifecycle to main November 15, 2026 01:15
@mintlify

mintlify Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

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

Project Status Preview Updated
omi 🟢 Ready View Preview Nov 15, 2026, 1:25 AM

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

@Git-on-my-level Git-on-my-level changed the title feat(sync): end-of-recording proof lets notes start without the quiet wait (server) feat(sync): end-of-recording proof lets notes start without the quiet wait (server) [SCA-2344] Nov 15, 2026
Git-on-my-level and others added 2 commits November 15, 2026 11:00
… the upload was shifted

Uploads from a phone whose clock runs ahead are stored shifted onto the server
clock by a per-request offset, so a complete recording read as content_behind
and kept the quiet wait. The sync writer now passes the shift it applied, the
hold state keeps it beside the row end it describes, and the proof adds it back
before comparing. Tolerance, the three proof rules and the quiet fallback are
unchanged; a row whose end has moved since reads clock_unknown.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
# Conflicts:
#	backend/config/flag_budget.json

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

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/routers/sync.py
Comment on lines +393 to +394
end_at=marker['end_at'],
end_observed_at=marker['end_observed_at'],

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 Write the persisted marker's timestamps to the ledger

When a phone resends the same end decision with a lower pending count, capture_end_db.store returns stored but deliberately preserves the original end_at and end_observed_at. This call instead forwards the newly normalized request's timestamps. If the resend has a different send/receive offset, plan_end accepts it as a different end and overwrites the ledger even though the session retains the original end. For example, the same device decision can map to 4992 on its first receipt and 5102 on its resend, moving the ledger's end forward by 110 seconds and corrupting end-to-ready measurements. Return the persisted marker from the storage transaction and use its timestamps for the ledger update.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 2450369 into main Nov 15, 2026
72 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/lifecycle-end branch November 15, 2026 04:38
Git-on-my-level added a commit to Git-on-my-level/omi that referenced this pull request Nov 15, 2026
Brings in BasedHardware#25309 (capture-end proof lets notes start without the quiet wait).
No textual conflicts; registry doc re-rendered.

Failure-Class: none

Co-Authored-By: Claude Fable 5.2 <[email protected]>
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 16, 2026
…r a 10-minute quiet wait (#25538)

## Problem

The CEO wants notes within seconds of a conversation ending. Today a
mobile conversation's notes land about 10 minutes after its transcript
is ready.

Prod trace from 2026-11-16 of a plain mobile live recording
(conversation `a4d5bf49`):

| Event | Time (UTC) |
|---|---|
| `server_batch_audio_end` / `finished_at` | 05:51:49 |
| `record_sealed_at`, `record_admitted_at` | 05:51:58 |
| Transcript ready (`episode_transcript_updated_at`) | 05:53:30 |
| `summary_first_pending_at` | 05:53:34 |
| `summary_completed_at` / `notes_written_at` | 06:03:09 (9.5 min idle)
|

Four real conversations from the same night took 6.7, 14.7, 29.7 and
30.4 min from audio end to notes.

What the prod rows show (read-only Firestore, the same user's
`batch_live_v1` rows that night):
- The record's own transcript is projected through `replace_record`.
That path never touches the processing hold. The pipeline ledger has
`sealed`, then `transcribed` 1.5 to 5 min later.
- A phone or pendant copy (`sync_vad`) then merges into the live target.
Assignment stamps `sync_processing_hold.last_content_at`, which restarts
the 600 s arrival-quiet clock.
- When the outbox claims the row, the enrichment callback's
`processing_hold.admission` returns `quiet_wait`. The outbox rows show
`deferred_reason = quiet_wait` and `task_due_at = last_content_at +
600`.
- Live recordings never send `/v2/sync-capture-end`, and their
recording-session documents have no `capture_end`. So the end-proof path
from #25309 always returned `absent`, and the quiet rule won.
- For `a4d5bf49`, notes at exactly 600 s after a content arrival at
05:53:09 fit this path. The first-summary deadline claimed the row
early, and admission deferred it to `last + 600`.

## Fix

A batch-owned live recording reaches the server over the live socket, so
the server's own seal proves it ended. This PR reuses the capture-end
proof hook rather than adding new hold semantics:

- `utils.sync.capture_end.seal_proof(row, ledger)` is pure. It returns
`proven` when all of these hold:
  - the row is a completed `batch_live_v1` row;
- its record barrier is closed: `record_audio_closed`, not partial, no
open or failed upload;
  - record text is projected (`record_projection_revision`);
- every unit has landed: the capture's `pipeline_ledger` document holds
a `transcribed` transition at or after `record_sealed_at`. The ledger
writes `transcribed` only after the record binding's whole projection
completes (`ProjectionStore._observe_transcription`), and units are up
to an hour each, so a projected revision alone is not proof. The ledger
never moves back, so a reseal keeps the quiet wait;
- it has no notes yet: no `summary_output_present`,
`summary_completed_at` or hold `full_snapshot`.
- `database.capture_end.sealed` reads the ledger document once, and only
for rows that pass the row-only `seal_barrier`. A missing or unreadable
ledger counts as "not proven". `proven` asks it first, then the phone
marker as before. Both admissions that already pass `end_proven` pick it
up: the enrichment callback and the legacy sync pipeline. Outcome
`end_proof`, metric `omi_sync_capture_end_proof_total{result="sealed"}`.
- A reopen between admission and the summary run changes the row. The
existing first-summary claim (`claim_from_snapshot`, an `updated_at`
precondition) then fails, and the retry re-admits the fresh row. A test
pins this.
- Complete-record notes scheduling in projection
(`RECORD_NOTES_EAGER_ENABLED`, still off in prod) only runs once every
unit is ready. It applies the row barrier when the job carries the row's
current upload revision, and records `sealed` after commit, once per
committed proof.
- The seal proves only the first notes. A pendant or phone copy that
lands after notes starts a normal hold epoch: it waits the quiet window,
then gets at most the existing one automatic late run (`MAX_LATE_RUNS =
1`), and only if the change is material. The unchanged, immaterial and
late-cap rules are untouched.
- Pure sync uploads and `batch_sync_v1` rows keep the quiet rule.
- No new flag: it shares the `SYNC_UPLOAD_WATERMARK_ENABLED` kill
switch. No reads or writes added.

Contract: `backend/docs/listen_pusher_pipeline.mdx` (End-of-recording
proof).
Change note:
`backend/docs/listen_pusher_pipeline/changes/2026-11-16-sealed-live-record-end-proof.md`.

## Tests

New:
- `test_sync_capture_end.py`:
- the seal-proof truth table: lane, open barrier, partial, failed
upload, transcript pending, notes written, no seal time;
- revision 1 projected with a sibling unit pending gives no proof; all
units projected gives proof; a `transcribed` from before a reseal gives
no proof;
- only the ledger is read, and only past the barrier; an unreadable
ledger gives no proof; `sealed` is counted once; the kill switch reads
nothing; the ledger collection and stage names are pinned;
- a sealed live row gets `('end_proof', None)` while a sync-only row
still gets `quiet_wait` at `last + 600`;
- a pendant copy after sealed notes waits quiet, then `ready` (exactly
one late run, `late_runs == 1`), then `late_cap`.
- `test_sync_processing_hold.py`, using the real `enrich_conversation`
callback:
  - all units landed: the row passes admission at claim (`end_proof`);
  - a unit still transcribing: it keeps `quiet_wait` until 700;
- a reopen after admission: the real `claim_from_snapshot` precondition
fences the run.
- `test_record_complete_notes.py`:
- unit 1 projected with its sibling pending: completion returns `None`,
and the row is not due now;
  - both units ready: `due_at == now`, with exactly one `sealed` count;
  - notes already written: the row stays on its deadline.

The new tests fail with the proof switched off
(`SYNC_UPLOAD_WATERMARK_ENABLED=false`). Removing the ledger unit gate
fails 6 of them.

Run, each file in its own pytest process as CI does: 26 files, 1,357
passed, 0 failed. Files: `test_sync_capture_end`,
`test_pipeline_ledger`, `test_sync_processing_hold`,
`test_record_complete_notes`, `test_record_notes_delivery_barrier`,
`test_occasion_merge_before_processing`, `test_sync_reprocess_coalesce`,
`test_outbox_firestore`, `test_enrichment_*` (7),
`test_episodes_finalizer_hook`, `test_stt_cap_sync_hold_recovery`,
`test_sync_enrichment_custody`, `test_reason_label_enums`,
`test_pipeline_ledger_census`, `test_pipeline_ledger_routes`,
`test_batch_pipeline_projection`, `test_batch_pipeline_live`,
`test_sync_v2`, `test_episode_composer`, `test_live_member_notes_bound`.
`scripts/pr-preflight --pr-body-file` passed (41 checks).

## Risks / not covered

- Not exercised against an emulator or prod. Unit tests only.
- The proof depends on the lifecycle ledger. If the ledger write fails
(it is fail-open) or the ledger is off, the row keeps today's quiet
wait.
- A resealed record never gets the seal proof, because the ledger's
second `transcribed` is a duplicate. It keeps today's quiet wait.
- A pendant copy that would have been inside the old 10-minute window
now lands after first notes. It regenerates notes once only if material
(at least 30 s of speech or 80 words).
- A sync mark that lands after the record's own notes mark still
schedules its wake at +quiet. The proof applies at the next claim, the
same as the phone marker.
- Not changed, and still visible on some rows that night: transcription
about 20 min after the seal on some rows; notes 18 to 30 min after the
quiet deadline on others (live-episode member-notes deferral excludes
`batch_live_v1` from its bounded retry); demand tiers.

## Product invariants affected

none

Failure-Class: FC-sync-enrichment-before-merge-settles

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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