Skip to content

fix(pipeline): wire the ledger's first two real writers, seal and upload-failed (C1b-1a) - #25129

Closed
Git-on-my-level wants to merge 4 commits into
mainfrom
lane/c1b1a
Closed

Git-on-my-level wants to merge 4 commits into
mainfrom
lane/c1b1a

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

C1b-1a: the in-flight ledger's first two real writers (seal, upload-failed)

pipeline_ledger.advance() had zero production callers on main, so C2's
census read an empty collection and returned 0/UNKNOWN coverage. This lands the
two ends that already exist — the seal that closes a recording and the
upload_failed terminal — with the full privacy/export/erasure/retention/
inventory surface for the now-live collection. No summary wiring.

Head: 797748f94796

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

Line-Count-Exception: backend/database/conversations.py | 4969 -> 4992 | adds delete_pipeline_ledger_row and its one call in delete_conversation so a deleted capture cannot leave a sibling ledger row; the split of this oversized file is separate debt, not this change

Why this class: the ledger is an operator measurement surface (the C2 census
reads users/{uid}/pipeline_ledger), and it was a read path over a collection
that no active writer maintained. The census returned a well-formed
empty/UNKNOWN aggregate rather than a missing-sample error — exactly the
"reader without a writer" failure. The stage table already declared deadlines
and exits; nothing ever entered a stage.

What changed

  • Seal hook (backend/database/record_audio.py, after the seal commits):
    capturing -> sealed, counted only when the seal actually closes the
    recording. Admission is a durable per-capture fact (record_admitted_at)
    written inside the seal transaction, so a reconnect that re-opens and
    re-seals the row does not count a second admission, increment attempt, or
    reset the deadline. A partial-seal repair does not count a second admission
    either.
  • failed:upload_failed terminal (backend/database/record_audio.py):
    end_type=unknown, end_at is record_upload_failed_at falling back to the
    observation time — never last speech, never the ledger-write time.
    mark_record_upload_failed now persists record_upload_failed_at.
  • Ledger contract (backend/database/pipeline_ledger.py):
    source_revision() derives an ordered revision from the source snapshot's
    update_time (integer seconds plus microseconds, so two distinct commits
    cannot collapse to one revision at 2026 epochs). advance() accepts
    source_ref/owner_ref; the ledger transaction reads both and refuses to
    create a row when the source is missing or deleted or the owner document is
    gone (fail-open for the already-committed transition). Nonterminal rows carry
    a bounded 7-day max lifetime so a stalled row cannot live forever.
  • Deletion (backend/database/conversations.py,
    backend/utils/conversations/merge_conversations.py): the sibling
    users/{uid}/pipeline_ledger/{conversation_id} row is deleted with the
    conversation, including the merge-source delete path.
  • Portability export (backend/services/users/data_export.py) and the
    recursive-erasure inventory (backend/database/user_data_deletion.py) for
    the now-live collection.
  • Retention declaration (backend/deploy/batch-pipeline/retention.json):
    pipeline_ledger joins collection_groups so scripts/batch_pipeline_ttl.py
    applies the expires_at TTL policy. Nothing here applies it: the declaration
    is inert until a deployer runs that script.
  • Stuck-row alert (backend/charts/monitoring/alert-rules.json,
    backend/charts/monitoring/alerts/pipeline-ledger.json): downgraded from
    critical/page to warning/agent with an explicit rearm_condition,
    because this change's code paths have no terminal for a sealed row until the
    notes and remaining exits land. The signal is not deleted or hidden.
  • Change note
    backend/docs/listen_pusher_pipeline/changes/2026-11-10-pipeline-in-flight-ledger.md
    and the ledger proof registered in backend/scripts/run-emulator-proofs.sh.

Fix batch 1

  • Erasure race: one bounded ledger sweep after the owner root delete, plus an emulator regression for a write landing between the walk and the root delete.
  • Rollback claim: the change note now says rows keep their expires_at stamp but do not expire until an operator applies the TTL policy, and a revert neither deletes rows nor un-provisions an applied TTL.
  • Seal authority: source_revision is wrapped in the seal transaction so ledger code cannot fail the seal.
  • Enable check: advance() moves pipeline_ledger_enabled() inside its fail-open try.
  • PIPELINE_LEDGER=off: record_admitted_at, record_upload_failed_at and the admission counter are gated on the flag, restoring the old conversation payload.
  • Deletion path: delete_pipeline_ledger_row raises instead of swallowing, and the log line no longer carries the conversation id.
  • Lifecycle inventory: record_admitted_at joins FIELDS and the seal_record_audio.commit site.
  • Vacuous tests: the seal test asserts a non-empty ledger write with stage sealed; the export test carries a real ledger row body.
  • Alert rule: stuck-row warning gains omi-tier-silent, a fresh updated, and a measurable >= 26h re-arm, pinned by a contract test.
  • Canonical name: code imports pipeline_ledger.COLLECTION, and the retention manifest entry is pinned to it.
  • Retention invariant: the manifest test asserts stage_groups() | USER_COLLECTION_GROUPS and their disjointness.
  • Retention README: states that the next batch_pipeline_ttl.py --apply also enables pipeline_ledger.expires_at and is a recorded user-data deletion decision.

Fix batch 2

Fix batch 2 (David R1 test-only exemption): align five pre-existing test stubs with the P1 erasure sweep; no product code changed. The sixth red check (test_monitoring_notification_contract) is blocked: omi-pipeline-ledger-stuck is warning/agent but still carries the critical notification cadence (30s/5m/4h), which needs a product-config timing fix outside this test-only push.

Deferred and documented, not hidden: the pre-deploy sealed cohort has no
record_admitted_at and is excluded from the census by name (no backfill);
end_at for failed:upload_failed is the most recent failed attempt, not the
first loss.

Fix batch 3

Fix batch 3 (David 9d79cc, lead2 3aa6c0): align omi-pipeline-ledger-stuck cadence with its warning tier (5m/1h/24h); no other rule changed.

Scope split (explicit)

  • C1b-1a (this PR): the seal writer, the failed:upload_failed terminal,
    the ledger's revision/fence contract it needs, and the custody surface
    (delete, merge-source delete, export, erasure inventory, retention
    declaration, alert downgrade).
  • C1b-1b (not this PR): the noted/done summary wiring in
    database/conversations.py — the pipeline_ledger.NOTED commit with
    source_revision, the DONE terminal, and their regression tests
    (test_summary_persistence.py,
    test_conversation_persistence_transaction_expiry.py, and the
    test_notes_writes_noted_after_real_state emulator case). Nothing in those
    hunks is included here.
  • Later: C1b-2 admission/transcript-landed stays fenced by fix(batch,sync): explicit backlog state machine with owners, deadlines and attempt budgets #24893; C1b-3
    episode/remaining terminals are outstanding.

This PR alone does not reach G2's 99.5% coverage; that needs C1b-2. It does
make C2's census start returning non-zero coverage for new captures instead of
0/UNKNOWN.

Write amplification

One document per capture, at most two transitions in this change, a 26-hour
terminal expires_at stamp, a 7-day nonterminal max lifetime, and fail-open on
every ledger error. The stamps delete nothing until a deployer applies the TTL
policy. The cost is not zero: every advance() runs its own Firestore
transaction that reads the owner, the source and the ledger document (three
reads) plus 0–1 write. The ledger write is one extra small transaction after the
real commit — never a per-frame or per-request read, and no hot-path read
consults the ledger.

Kill switch and rollback

PIPELINE_LEDGER via pipeline_ledger_enabled(), default on when absent — the
existing flag, no new env name and no flag-budget slot. Off stops ledger writes
and leaves capture behavior unchanged.

Revert the sub-PR. Capture behavior returns to today's exactly; the ledger is
write-only and fail-open with no read path, and with PIPELINE_LEDGER off the
ledger-only conversation fields are not written. Reverting the code does not
delete rows already written and does not un-provision a TTL that was applied.

Rows already written keep their expires_at stamp but do not expire until an
operator applies the TTL policy; the retention declaration stays inert until a
deployer applies it.

.github

git diff --name-only origin/main...HEAD contains zero paths under
.github/
. The old head's
.github/actions/sync-backfill-lifecycle/action.yml TTL-provisioning change is
dropped: backend/scripts/batch_pipeline_ttl.py already applies
retention.json, and provisioning is a deployer action. The dead-code
allowlist entry for backend/database/pipeline_ledger.py also stays in place
(the ratchet treats a now-used file as an advisory, not a failure); removing it
needs a separately approved .github change. No TTL --apply, no deploy, no
prod config, no new deletion policy, no new flag.

Product invariants affected

  • INV-MEM-3 — the portability export gains a content-free pipeline_ledger
    section only. It reads a per-user subcollection directly (as the existing
    export inventory does), does not bypass MemoryService for memory content,
    and does not touch the intake-pause paths. The recursive account wipe still
    erases the collection.

Tests

Unit (hermetic):

  • backend/tests/unit/test_pipeline_ledger.py — table invariants, transitions,
    fail-open (including a raising enable check), privacy, retention and revision
    ordering.
  • backend/tests/unit/test_record_audio_seal.py — reconnect re-seal admits
    exactly once, record_upload_failed_at is persisted, and the seal emits a
    non-empty sibling ledger write with stage sealed.
  • backend/tests/unit/test_record_token_lease.py — the seal transaction is
    selected by payload, not by [-1].
  • backend/tests/unit/test_audio_durable_outbox.py — the post-seal ledger write
    is the fourth transaction, not a per-frame read.
  • backend/tests/unit/test_batch_pipeline_privacy.py — the TTL manifest covers
    19 resources as stage_groups() | USER_COLLECTION_GROUPS, the two are
    disjoint, and the manifest entry equals pipeline_ledger.COLLECTION.
  • backend/tests/unit/test_delete_conversation_cascade.py — the sibling ledger
    row is in the expected delete list, and a transient ledger delete propagates.
  • backend/tests/routers/test_users_export_streaming.py,
    backend/tests/services/users/test_data_export.py,
    test_data_export_streaming.py — the export carries a real ledger row body.
  • backend/tests/support/lifecycle_writer_inventory.py —
    record_admitted_at is declared at the seal site, and
    mark_record_upload_failed declares its current payload.
  • backend/tests/unit/test_monitoring_alert_rule_contract.py,
    test_lifecycle_state_table_writers.py — alert (uid/severity/tier/mute/rearm)
    and writer inventories.

Emulator (loopback Firestore, FIRESTORE_EMULATOR_HOST=127.0.0.1:8085):

  • backend/tests/integration/test_pipeline_ledger_firestore.py — seal, duplicate
    seal, reconnect re-seal (attempt == 1, one sealed transition),
    upload-failure terminal and end_at fallback, source-delete fence, stale
    revision ordering, delete-conversation sibling cleanup, account erasure, a
    delayed ledger write between the sweep and the root delete, a raising
    source_revision, and the census window. Registered in
    backend/scripts/run-emulator-proofs.sh so it runs in CI.

Focused suite at this head: 2246 passed, including the 17-case emulator proof.
Fix batch 2 re-ran the five aligned files: 101 passed.
The full bounded pre-push gate passed; its log is recorded with this run.

…writers

`pipeline_ledger.advance()` had no production caller, so the C2 census read
an empty collection. This lands the two writers for ends that already exist,
with the custody surface the live collection needs.

- Seal (`database/record_audio.py`): `capturing -> sealed` after the seal
  commits, admitted once per capture via the durable `record_admitted_at`.
- Upload failure: `failed:upload_failed` with `end_type=unknown` and
  `record_upload_failed_at` as `end_at`, falling back to observation time.
- Ledger (`database/pipeline_ledger.py`): `source_revision`, source/owner
  deletion fence in the CAS transaction, and a bounded nonterminal lifetime.
- Custody: sibling ledger row deleted with the conversation and on the
  merge-source path; account erasure and the portability export cover the
  collection; `retention.json` declares the collection group for the
  deployer-run TTL script. The declaration is inert until applied.
- The stuck-row alert is downgraded to warning/agent with an explicit
  rearm condition, because this change's code paths have no terminal for a
  sealed row until the notes and remaining exit writers land.

No summary wiring, no new flag (`PIPELINE_LEDGER` already gates it), no
`.github` change, no TTL apply, no deploy.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 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-12T05:59:24.962025Z d5d71db 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: e65c08af67

ℹ️ 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/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 the injectable Firestore client in the new cleanup helper

The new helper uses the legacy module-level db proxy and provides no firestore_client injection point, contrary to the explicit database convention in backend/AGENTS.md. This makes ledger cleanup depend on global client patching rather than allowing callers and isolated tests to supply the same client used for the source operation. Resolve the client with get_firestore_client() at call time and accept an optional keyword-only firestore_client argument.

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

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 Write the failure terminal when the upload failure commits

On an actual upload failure, PusherRecordBarrier.fail_recording() calls mark_record_upload_failed() and adds the capture to failed_recordings; finish_recording() then returns early for that capture without calling seal_record_audio(). Consequently, placing the only failure-ledger writer in this seal-refusal branch means failed uploads receive no terminal unless a later clean reconnect explicitly attempts another seal. Captures without that reconnect remain absent from the ledger, or remain incorrectly sealed if previously admitted. Invoke the fail-open terminal writer after the failure-marker transaction commits rather than relying exclusively on a subsequent seal attempt.

Useful? React with 👍 / 👎.

Comment on lines +369 to +373
if owner_ref is not None:
owner = owner_ref.get(transaction=transaction)
if not getattr(owner, 'exists', False):
observed['outcome'] = 'deleted'
return 'deleted'

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 ledger writes against an account wipe already in progress

A delayed ledger write can survive account erasure because this check only requires the owner document to exist. purge_user_subtree() enumerates and deletes subcollections before deleting the owner document (backend/database/user_data_deletion.py:57–78), so a ledger write arriving after the ledger collection has been swept but before its source conversation is deleted passes both checks. The remaining wipe deletes the conversation and owner but never revisits the ledger, leaving the new row under the erased account. purge_batch_owner() already establishes a durable blocked privacy generation before the subtree sweep; consult that fence transactionally, or otherwise prevent these writes throughout the wipe rather than only after the root disappears.

Useful? React with 👍 / 👎.

Batch 1 for the in-flight ledger writers:

- Erasure: sweep the ledger once more after the owner root delete, so a
  delayed seal or upload-failure commit cannot outlive the account wipe.
  Add the emulator regression for the race window.
- Seal: compute source_revision defensively inside the transaction, gate
  ledger-only conversation fields on PIPELINE_LEDGER, and move the enable
  check inside advance()'s fail-open try.
- Deletion: let the sibling ledger delete raise instead of swallowing it,
  and stop logging the conversation id.
- Custody: use pipeline_ledger.COLLECTION in code, pin the retention
  manifest entry to it, and keep the stage/user TTL groups disjoint.
- Docs/alerts: correct the rollback and TTL claims, name the pre-deploy
  sealed cohort exclusion and the latest-attempt end_at, add the agent mute
  interval plus a measurable re-arm, and pin it with a contract test.
- Tests: replace vacuous seal/export assertions, declare record_admitted_at
  in the lifecycle inventory, and add fail-open/source-revision checks.

@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: 6bf34763d2

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

# root delete can write into an already-swept collection. One bounded sweep
# after the root delete removes that row; the same pattern
# ``delete_conversation`` uses for a delayed child commit.
from database import pipeline_ledger

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 ledger import to module scope

backend/AGENTS.md explicitly requires “All imports at module top level — never inside functions.” The newly added pipeline_ledger import violates that backend convention. Move it into the module-level import section; the post-root cleanup can continue referencing the same collection constant without a function-local import.

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

Useful? React with 👍 / 👎.

The P1 fix added one post-root ledger sweep to purge_user_subtree. Five
pre-existing tests modeled the wipe with fakes that did not know the new
collection:

- test_memory_retraction_source_index: the fake collection now carries its
  name as .id, and the expected event list ends with the ledger sweep.
- test_list_projection: same .id, and the recursive fake tolerates the
  ledger collection it does not model.
- test_fsr_people_generation: the fake records per-collection ids, and the
  generation head is asserted as the last document delete before the ledger
  sweep.
- test_held_content_deletion: the fake collection carries .id, and the
  expected delete list includes pipeline_ledger.COLLECTION.
- test_people_generation_inventory: re-audit purge_user_subtree after it
  began naming pipeline_ledger.COLLECTION.

No product code changed.

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

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

if admitted:
pipeline_ledger.observe_admission()
revision = max(1, source_revision)
if result is None and admitted:

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 after a proven upload-failure repair

For a capture that was sealed once and subsequently acquired a failed:upload_failed ledger terminal, a successful proof repair cannot restore the ledger to sealed. apply_seals() in backend/utils/batch_pipeline/record_seal_repair.py clears record_upload_failed and sets record_audio_closed=True without advancing the ledger, while retaining record_admitted_at. Any later successful seal therefore has admitted=False and skips this branch, leaving the repaired capture classified as terminally failed until expiry. Separate admission-counter deduplication from stage recovery and advance the ledger after the authoritative repair commits.

Useful? React with 👍 / 👎.

omi-pipeline-ledger-stuck was downgraded to warning/agent but kept the
critical cadence. The monitoring contract requires warning timing
(group_wait 5m / group_interval 1h / repeat_interval 24h), which the
sibling gate-receipt-stale rule already uses. Only that rule's
notification_settings change; the sample-stale critical/page rule and
the gate-receipt-stale rule are untouched.
Git-on-my-level added a commit that referenced this pull request Nov 12, 2026
…2) (#25143)

# C1b-2: admission and transcript-landed writers for the in-flight
ledger

The write-only, fail-open ledger had no production caller on `main` for
either
end of a fresh capture's middle. Nothing created the admission row, so
the C2
census had no `capturing` cohort; a completed projection never advanced
past
`sealed`, so every transcribed row aged past its deadline. This lands
the two
writers that close that gap, on the files the C1b split reserved.

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

## What changed

- **Admission** (`backend/utils/batch_pipeline/live.py`):
`reserve_recording`
offers `capturing` at the durable admission that gives a capture its
batch
lane — the fresh claim and a lane already claimed on the streaming path.
The
ledger is forward-only and idempotent, so a finalizer replay, reconnect
or
competing reservation can only produce a duplicate or a forward/illegal
refusal, never a second admission. A capture without an identity or
already
deleted gets no row. The write is fail-open: it never changes the
returned
  owner.
- **Transcript landed**
(`backend/database/batch_pipeline_projection.py`): the
first durable completion of a capture's projection writes `transcribed`
on
the completion's own event clock (`now`), with the immutable completion
  summary's speech seconds and `speech_basis='transcript'`. A replay
(`changed is False`) writes nothing, and a source deletion keeps its
erasure
  fence and gets no new durable row.
- **Tests** (unit, hermetic): admission is idempotent across replays,
never
rewinds a `sealed` row, skips an identity-less or deleted capture and
cannot
be blocked by a ledger outage; the transcription writer uses the
completion
clock, skips replays, respects the deletion fence, needs a capture
identity
  and is fail-open.

## Not in this change

- The seal, upload-failure, notes and `done` writers and the ledger's
revision/erasure-fence, deletion, export and retention surface belong to
C1b-1/C1b-1a (`#25125`, `#25129`). This PR stacks no code on either: its
writers use only `advance()` as it exists on `main`, and they keep
working
unchanged when the fenced `advance(..., source_ref=..., owner_ref=...)`
  signature lands.
- Episode composed, `no_speech`/`noise` terminals and the true admission
  denominator are C1b-3.
- Partial completions (`complete_partial`) deliberately do not write
`transcribed`: a held partial has not landed the capture's whole
transcript,
  and its terminal disposition belongs to C1b-3.
- This change alone does **not** prove G2/P2 coverage: that needs the
sibling
writers merged and one full serving window. The census denominator is
still
every conversation created in the window, not only fresh batch-eligible
  captures.

## Write amplification

One `advance()` per capture admission and at most one per capture
completion.
Each is its own small Firestore transaction after the real transition;
the
ledger is never read on a hot path and no transition depends on it. A
duplicate
or refused transition reads the row and writes nothing.

## Kill switch and rollback

`PIPELINE_LEDGER` via `pipeline_ledger_enabled()` (existing flag,
default on).
Off stops all ledger writes; capture and projection behavior is
unchanged
either way because both calls are fail-open. Reverting the code returns
capture
and projection behavior exactly to today's; rows already written keep
their
stamps.

## Tests

- `backend/tests/unit/test_batch_pipeline_live.py` — admission written
once on
a fresh claim, replay is a duplicate, a sealed row is never rewound, a
ledger
outage leaves the real admission intact, identity-less/deleted captures
are
  skipped.
- `backend/tests/unit/test_batch_pipeline_projection.py` — first
completion
writes `transcribed` with the completion clock and completion-summary
speech
seconds; a replay writes nothing; a source deletion writes nothing; the
  writer is fail-open and needs a capture identity.

Focused run with the repo's Python 3.11 environment:
`tests/unit/test_batch_pipeline_live.py`,
`test_batch_pipeline_projection.py`,
`test_pipeline_ledger.py`, `test_pipeline_ledger_census.py`,
`test_restore_recording_obligation.py`,
`test_batch_record_dead_letter.py`,
`test_phase_shadow_readers.py` — 338 passed. The Firestore emulator
proof was
not run in this environment; the changes add no query or index and use
only the
existing `advance()` contract.

## Product invariants affected

None. The ledger document is content-free (stage, clocks, bounded
reason, speech
seconds, truncated owner hash) and no read path or transition depends on
it.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25143?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/25143?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25143&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. -->



Closes SCA-1761
Git-on-my-level added a commit that referenced this pull request Nov 15, 2026
…nd a tunable notes hold (#25304)

# 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,))`). #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. #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 #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](https://claude.com/claude-code)
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Closing as part of a stale-PR cleanup David asked for on 2026-11-26 (Shipping lead agent): it has had no activity for days. Nothing is lost: the branch stays, and anyone can reopen this PR if the work is still wanted. If it still matters, reopen it and refresh it against main.

@github-actions

Copy link
Copy Markdown
Contributor

Hey @Git-on-my-level 👋

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

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

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

Before your next PR, please skim:

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

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

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

Thank you for being part of the Omi community!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant