Repository navigation
fix: retry live cap publication when a Firestore transaction expires - #22966
Conversation
A retired transaction id closed held live sessions during Firestore bursts. Restart the publication on a fresh transaction, and keep uploaded audio staged for the redrive when that budget is spent. Co-authored-by: Cursor <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3b0e5cf7f8
ℹ️ 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".
| with external_write_fence(uid): | ||
| commit(client.transaction()) | ||
| run_transactional(client, commit, transient=True) |
There was a problem hiding this comment.
Recheck deletion authority on every retry
If the first transaction expires and account deletion starts during the new jitter delay, the outer external_write_fence has already completed its authority reads, so the fresh transaction can recreate the user's storage/quota document after deletion has purged and verified it. Put the fence inside commit so every newly created transaction reads the deletion authorities before writing, and cover the interleaving with the required Firestore emulator.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
| if row: | ||
| merged['created_at'] = row.get('created_at', merged['created_at']) | ||
| merged['started_at'] = row.get('started_at', merged['started_at']) | ||
| merged['listed_at'] = row.get('listed_at', merged['listed_at']) | ||
| ref.set(merged) |
There was a problem hiding this comment.
Make the redrive fallback conditional
When a writer resumes after its lease expired, the redrive worker can seal the row between this preceding read and ref.set(merged). The unconditional set then overwrites the newly held manifest with stale staging data; after cleanup has deleted the old fragment objects, subsequent redrive attempts cannot compose the restored references. Use a transactional/preconditioned update that proves the row is still the staging version that was read, and cover this race in the required emulator.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
| ref.create({**body, 'live_custody_version': 4}) | ||
| except AlreadyExists: | ||
| return True | ||
| total.set( | ||
| {'seconds': firestore.Increment(seconds), 'count': firestore.Increment(1)}, |
There was a problem hiding this comment.
Keep receipt creation and summary accounting atomic
On the exhausted-transaction recovery path, ref.create and total.set are separate writes. If the process dies or the second write fails after the receipt is created, the next publication attempt sees the receipt and returns without ever incrementing the summary, permanently under-reporting held seconds/count. Persist both effects atomically or add a durable reconciliation marker, and verify the failure boundary with the required Firestore emulator.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
| class _Transaction: | ||
| _max_attempts = 5 | ||
| _read_only = False | ||
|
|
||
| def __init__(self, client: '_Client'): | ||
| self.client = client | ||
| self._id = f'txn-{len(client.transactions)}'.encode() | ||
| self.ops: list[tuple] = [] |
There was a problem hiding this comment.
Cover transaction retries in the Firestore emulator
This incident changes retry and contention behavior but tests it only with a hand-written _Transaction that directly applies buffered operations. It therefore cannot validate the real SDK's retry lifecycle, ordering constraints, or fresh transaction IDs; the backend guide explicitly requires emulator coverage for retry/contention incidents and the strict fixture for document reads plus writes.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
| with external_write_fence(uid): | ||
| commit(client.transaction()) | ||
| run_transactional(client, commit, transient=True) |
There was a problem hiding this comment.
Require an idempotency key before transient reserve retries
When reservation_id is omitted, this transaction has no receipt that can recognize an ambiguous commit. If the first commit applies and returns DeadlineExceeded, the fresh retry reads the already-increased totals and adds size and one chunk again, potentially exhausting the live-storage cap early. Either require a reservation ID for this retry path or retain the old non-transient behavior for unkeyed reservations, and cover the ambiguous commit in the required emulator.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
A throttled commit in the same burst as an expired transaction was still closing the live socket. The transient publication path now restarts on ResourceExhausted and stages the audio when that budget is spent. Co-authored-by: Cursor <[email protected]>
A fallback append could overwrite a row the sealer had already moved, and a receipt created without its usage increment was treated as finished. Staging writes that land now stay staged even if the follow-up read fails. Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cddb1cd00d
ℹ️ 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".
| part = updates['stage_parts'][-1] | ||
| if part.get('id') != fragment.identity: | ||
| return None | ||
| with external_write_fence(uid, firestore_client=client): |
There was a problem hiding this comment.
Put fallback staging creates behind the deletion fence
When retries are exhausted while no group document exists, this nontransactional fence can finish its authority reads before account deletion acquires the gate; deletion can then purge and verify the empty subtree before ref.create(merged) recreates stt_cap_holds afterward, potentially referencing an object the wipe already removed. Make the fallback authority check and create atomic in a transaction, and cover this interleaving with the Firestore emulator.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
| if row.get('state') != 'staging': | ||
| return _stage_late_fragment(part, updates) |
There was a problem hiding this comment.
Charge capacity for standalone fallback rows
When the original group has already moved out of staging, this branch persists the fragment as a separate row but returns ordinary success to LiveHeldAudio; because that caller consumes capacity only when the original group's _group_parts == 0, the extra row is later sealed and counted as another held group without consuming another quota slot. Repeated retry/sealer races can therefore exceed both the monthly group and byte reservation, so report this as a rollover or explicitly charge the standalone group, and verify the interleaving in the emulator.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
| 'metadata': updates.get('metadata'), | ||
| 'sample_rate': updates.get('sample_rate'), | ||
| 'started_at': updates.get('started_at'), | ||
| 'created_at': time.time(), | ||
| 'listed_at': updates.get('listed_at', updates.get('started_at')), |
There was a problem hiding this comment.
Preserve the late fragment's own timestamp
When a sealer race moves a fragment into its own staging row, updates still contains the original group's metadata, started_at, and listed_at, so this body stamps the standalone fragment with the earlier group's time rather than the current fragment's timestamp. The redrive then publishes the separate audio at the wrong point in the timeline; build the late row from the current fragment's fields and metadata['timestamp'], and exercise the sealer race with the emulator.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
| def _stage_late_fragment(part: dict, updates: dict) -> dict | None: | ||
| late = cap_hold.holds(uid).document(fragment.identity) | ||
| body = _late_staging_body(part, updates) |
There was a problem hiding this comment.
Keep the late manifest ID distinct from its source blob
A standalone fallback row is keyed by fragment.identity, but its only staged part was uploaded under that same identity, so seal() chooses the existing source blob as its composed target and cleanup() subsequently deletes that exact generation as a staging part. Every fallback that races the sealer can therefore end with a held manifest referencing missing audio; use a distinct group/target identity or prevent cleanup from deleting the target, and cover the redrive with the required emulator.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
A late staging row used the fragment id, so seal composed onto the part and cleanup deleted the receipt. A lost precondition also opened a second row after the same fragment had already committed. Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a6180675fa
ℹ️ 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".
| type(error).__name__, | ||
| ) | ||
| record_publication_retry('staged_unverified') | ||
| return staged |
There was a problem hiding this comment.
Verify the create winner before reporting success
When the exhausted-transaction fallback sees no group, ref.create can lose to another fragment's concurrent create; if the immediate winner read then fails transiently, this branch returns the local staged payload even though this invocation's create definitely did not land and the winning row need not contain this fragment. append consequently reports success, allowing LiveHeldAudio to discard the PCM while no manifest references the uploaded object and redrive cannot discover it. Retry the read or stage the fragment under its deterministic late-row identity instead of treating the failed verification as durable, and cover this create/read race with the Firestore emulator.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
| return _stage_late_fragment(part, updates) | ||
| # Still staging, and this fragment is not in it. A second row here | ||
| # would seal the same audio twice if the lost update had committed. | ||
| return merged |
There was a problem hiding this comment.
Preserve the fragment after precondition retries fail
When concurrent writers advance the staging row during all three preconditioned updates, every write raises FailedPrecondition; if the final read still finds a staging row without this fragment, this line nevertheless returns the local merged dictionary as success. The caller then consumes capacity and drops the PCM even though the durable row never acquired the part, leaving an orphaned blob that redrive cannot seal. Continue retrying, create the late staging row, or raise rather than returning an uncommitted payload, and exercise the repeated-contention case in the Firestore emulator.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
Exhausted conditional appends and a failed re-read were returned as staged even when the group still omitted the fragment, so the flush advanced and the bytes stayed unreferenced. Co-authored-by: Cursor <[email protected]>
An ambiguous commit can leave the same fragment on the group and the late row. Seal claims each fragment id once, and cleanup deletes a source only after that claim commits. Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c238bb0cf1
ℹ️ 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 holder and holder != identity: | ||
| continue | ||
| if not holder: | ||
| tx.create(claim_ref, {'hold_id': identity, 'fragment_id': fragment_id}) |
There was a problem hiding this comment.
Read all fragment claims before creating any
When a normal group contains two or more unclaimed fragments, this tx.create queues a write during the first loop iteration, and the next iteration calls claim_ref.get(transaction=tx). Firestore rejects reads after the first transaction write, so multi-fragment groups cannot seal and remain stuck in redrive. Collect every claim snapshot first, then enqueue the claim creates and manifest writes only after all reads have completed. The custom test transaction misses this production constraint.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
| row = ref.get().to_dict() or {} | ||
| except Exception: | ||
| raise error from None | ||
| if row.get('state') in {'staging', 'sealing'} and row.get('stage_parts'): |
There was a problem hiding this comment.
Accept a terminal row after an ambiguous seal commit
If earlier seal attempts fail and the final commit lands but its DeadlineExceeded, ServiceUnavailable, or similar reply is lost, this recovery read sees the row already in terminal held or superseded state. Restricting success to staging/sealing re-raises the transient error, causing the listen path to close the socket with 1011 even though the manifest and accounting transaction completed. Reconcile terminal states as success and leave any pending cleanup to the cleanup sweep; cover the final-attempt ambiguous commit with the Firestore emulator.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
| except PreconditionFailed: | ||
| target.reload(timeout=10, retry=None) |
There was a problem hiding this comment.
Recompose after the claimed fragment set changes
When two rows overlap on one fragment of a multi-fragment group, this row can compose all sources before the competing row commits its claim; the Firestore transaction then aborts and retries with a smaller claimed set. The existing destination makes compose raise PreconditionFailed, but this handler merely reloads that stale object, so the committed opus_fragments describes only the remaining claims while the object still contains the lost fragment's bytes. read_audio then detects an unexpected source tail and the held audio cannot be recovered. Delete and recompose the destination with a generation precondition, or key it by the exact claim set, and cover the contention retry in the emulator.
AGENTS.md reference: backend/AGENTS.md:L225-L225
Useful? React with 👍 / 👎.
Review round 5 on #22966 found both P1s in the seal path. The seal transaction read a claim, created it, then read the next claim. Firestore rejects a transactional read after the first queued write, so a group with more than one fragment could never seal and the redrive retried it forever. Every claim is now read before the first create, and the test double raises ReadAfterWriteError (the real client's class) on a transactional get after a queued write. Compose runs before the claim transaction commits. A retry that lost a fragment to another row claimed a smaller set but reloaded the destination the wider set had built, so the manifest described fewer bytes than the object held. The destination now names its claim set (chunks/{uid}/cap-held/{hold}.{sha256(sorted ids)[:16]}.opus.enc); a different set is a different object, and the wider composite is dropped as unpublished. Also: cap_hold.claim treats superseded as terminal; claims carry expire_at (created + 90 days, a timestamp for a Firestore TTL policy enabled separately); a flush that fails closed after uploading a fragment no row names increments omi_held_content_publication_retry with source_orphaned; and the durability test over an existing receipt, whose transaction double predated the usage-repair path, now asserts that repair happens once. Failure-Class: FC-test-double-accepts-payload-store-rejects
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bb95321b31
ℹ️ 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 { | ||
| 'hold_id': identity, | ||
| 'fragment_id': fragment_id, | ||
| 'expire_at': datetime.now(timezone.utc) + timedelta(seconds=CLAIM_LEDGER_SECONDS), |
There was a problem hiding this comment.
Provision the TTL used by fragment claims
In environments provisioned from this repository, expire_at is only stored as an ordinary timestamp, so every sealed fragment leaves a claim document permanently. I checked firestore.indexes.json and the deployment/scripts for stt_cap_fragment_claims; there is no TTL field override or other provisioning for this collection, while each successful seal creates up to four claims. As live held audio accumulates, this collection therefore grows without bound unless the change also provisions and verifies the TTL policy.
Useful? React with 👍 / 👎.
| staged = _stage_for_redrive(staged_updates) | ||
| if staged is not None: | ||
| logger.warning( | ||
| 'event=stt_cap_live_held outcome=staged_for_redrive exception_type=%s', | ||
| type(error).__name__, | ||
| ) | ||
| return staged |
There was a problem hiding this comment.
Record staged redrive through shared fallback telemetry
When transaction retries are exhausted and _stage_for_redrive succeeds, this branch changes publication from immediate sealing to deferred redrive while allowing the socket to continue, but it only emits the new domain-specific retry counter. That leaves the degraded fallback absent from the repository-wide fallback signal and its standard dashboards; call record_fallback with a bounded recovered/degraded outcome at this branch (the retry counter may remain for retry-specific detail).
AGENTS.md reference: backend/AGENTS.md:L314-L314
Useful? React with 👍 / 👎.
| A staged publication returns. The receive loop does not call this, and the | ||
| socket stays up so the redrive can seal. A staging write that did not land | ||
| still raises, and both listen failure sites close with 1011 through here. |
There was a problem hiding this comment.
Document the changed listen publication contract
This change establishes new listen behavior in which a durably staged publication keeps the WebSocket open while redrive seals it later, but the commit does not update backend/docs/listen_pusher_pipeline.mdx. That file is the required owner of audio and listen WebSocket contract changes, so the deferred-publication and close-code behavior needs to be recorded there for operators and other pipeline implementations.
AGENTS.md reference: backend/AGENTS.md:L159-L159
Useful? React with 👍 / 👎.
| if unresolved: | ||
| # Leave the flag set so the cleanup sweep can try this row again. | ||
| return |
There was a problem hiding this comment.
Do not advance while fragment cleanup is unresolved
When any claim lookup fails, this returns with the fragment objects and staging_cleanup flag still present, but seal() nevertheless returns success and LiveHeldAudio clears the group and advances. Capacity reserves only one extra overlap slot per 64 groups, so repeated cleanup-read failures can leave every completed group holding both its composite and its source fragments, exceeding the reserved byte ceiling until a later sweep succeeds. Propagate incomplete cleanup to the writer or account for all outstanding fragments before allowing the next group.
Useful? React with 👍 / 👎.
Review round 7 on #22966 found a double-count on the publication paths, a claim-expiry risk, and GCS calls inside the seal transaction. The live commit and the recovery transaction both treated an existing receipt without usage_applied as uncounted and incremented the summary again. The writer deployed in prod creates the receipt and increments the summary in one transaction, and recovery has never run in prod (cap enforcement off, zero recovery calls observed), so a markerless receipt is a pre-marker receipt that was already counted. Both paths now stamp the marker without incrementing; the summary moves only with a create. Claims no longer carry expire_at. A TTL could let a duplicate row re-claim a fragment later and count it twice, so claims stay permanent until a cleanup can prove every row referencing the fragment is terminal and the source is gone; account erasure already deletes the ledger with the user. The stale-wider-composite deletion moved out of the seal transaction into post-commit cleanup run by the row that committed: up to 2**MAX_FRAGMENTS - 1 sequential GCS deletes with 10s timeouts inside the callback risked transaction expiry. The drop still only names this hold's own compose destinations, never the committed set's object, a fragment source, or another hold's object. Failure-Class: FC-marker-absence-read-as-unapplied
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 97ddf555b3
ℹ️ 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".
| """Append while the group is staging. A lost precondition re-reads first.""" | ||
| for _attempt in range(_STAGING_APPEND_ATTEMPTS): | ||
| try: | ||
| ref.update(merged, option=firestore.LastUpdateOption(snapshot.update_time)) |
There was a problem hiding this comment.
Handle ambiguous fallback updates
When the normal transaction retries are exhausted and this fallback update is used, Firestore can apply the write but return DeadlineExceeded or ServiceUnavailable. Because only FailedPrecondition is caught, that transient error escapes recover, and the listen path closes the WebSocket with 1011 even though the fragment is durably staged. Re-read and reconcile the fragment after retryable update errors before surfacing the failure.
Useful? React with 👍 / 👎.
| row['seconds'], | ||
| counted, | ||
| row['created_at'], | ||
| int(row['started_at']), |
There was a problem hiding this comment.
Preserve timing when claims remove earlier fragments
When overlapping rows race and another row wins the claim for the first or a middle fragment, this transaction correctly composes only the remaining claimed parts, but the manifest is still anchored to the original row's started_at and metadata. For example, if the first 15-second part is lost, the second part is published at the first part's timestamp; losing a middle part also collapses the gap. Store timing on each part and derive or split the partial manifest from the fragments actually claimed so recovered audio is not assigned to the wrong point in the capture timeline.
Useful? React with 👍 / 👎.
| # is this hold's own compose destination — never a fragment source, | ||
| # never another hold's object — and the committed set itself is never a | ||
| # candidate, so a failure here can only leave garbage behind. | ||
| _drop_unpublished_targets(bucket, uid, identity, unpublished[0], unpublished[1]) |
There was a problem hiding this comment.
Do not fail a committed seal during stale-target cleanup
When claim contention shrinks the fragment set, the held row and summary are committed before this cleanup runs, but _drop_unpublished_targets lets transient GCS reload/delete errors propagate. The caller then closes the listen socket with 1011 even though publication succeeded, and a later seal sees the terminal row and never reconstructs the obsolete target list, so those composites leak permanently. Treat this deletion as best-effort or persist enough cleanup state for the sweep to retry it.
Useful? React with 👍 / 👎.
## Summary Fixes the 4 latent main reds found by the first nightly full run [39586610411](https://github.com/BasedHardware/omi/actions/runs/39586610411) (`main_nightly_full.yml` on main = failure). Rows 4/4 in the swarm known-red list. 1. **Hygiene / `screen-activity-batch-resilience-tests` — ImportError (TEST-ONLY).** `database/_client.py` (#22966, live in prod) imports `DeadlineExceeded`, `ResourceExhausted`, `ServiceUnavailable` from `google.api_core.exceptions`. The bare-python3 hygiene stub in `backend/tests/unit/test_screen_activity_batch_resilience.py` only defined `InvalidArgument`/`Aborted`, so the module import failed before any test ran. Prod is unaffected: pinned google-api-core 2.19.1 exports all five names (verified in the backend venv); the ImportError only reproduces in the dependency-free hygiene runner. The stub gains the three missing names, and `backend/database/_client.py` joins the check's manifest triggers — #22966 touched only `_client.py`, which the trigger list omitted, so PR CI never ran this check and the nightly full run caught it. 2. **Formatting / `dart format`: 4 files.** `app/integration_test/app_performance_test.dart`, `app/test/unit/wal_file_manager_error_path_test.dart`, `sdks/device/dart/lib/stt/stt.dart`, `sdks/device/dart/test/stt_test.dart` formatted with `dart format --line-length 120` on the same Flutter 3.44.5 toolchain the Formatting job pins. PR runs format only on PR-changed files, so these slipped through merges that never touched them. 3. **iOS job / `desktop-beta-admission-firestore-contention` — missing backend venv.** `backend/testing/desktop_beta_admission/run.sh` needs `backend/.venv` or `uv`; the iOS Compile Check job set up neither and failed in 0.06s at check setup. The identical macos-scoped selection in desktop-swift-ci installed uv and passed the same check (46.15s) in the same nightly run. This PR adds the same pinned setup-uv step (0.11.13, matching `backend/Dockerfile` UV_VERSION) before the iOS job's manifest checks step. 4. **Mobile Release Eligibility aggregate** — fails only on `IOS_COMPILE_RESULT=failure`; goes green once (3) lands. No code change. ### Exact `.github` changes (David named the nightly workflow change on 10-21) - `.github/checks-manifest.yaml` — add `backend/database/_client.py` to `screen-activity-batch-resilience-tests` triggers. - `.github/workflows/mobile-app-checks.yml` — new `Install uv for manifest checks` step in the `ios-compile-check` job, before `Run macOS-scoped iOS manifest checks` (pinned `astral-sh/setup-uv@ecd24dd710f2fb0dca1693a67af11fc4a5c5ec84`, version 0.11.13). ## Verification (local, this worktree, base cdaad3a) - `python3 backend/tests/unit/test_screen_activity_batch_resilience.py` — reproduced the exact CI ImportError before the fix; 9 tests OK after, with both bare `python3` and `backend/.venv/bin/python`. - `python3 .github/scripts/test_run_checks.py` (check-manifest-contract) — 62/62 OK after both `.github` edits, from the repo root as CI does. - Whole-repo nightly Formatting replica: `dart format --line-length 120 --set-exit-if-changed --output=none` over all 1920 tracked non-generated `.dart` files — 0 changed, exit 0. - `actionlint` on `mobile-app-checks.yml` — clean. - `scripts/pr-preflight --suggest` — no invariant citations, no failure-class declarations required (no `fix:` commits). ## Notes - No deploy needed: test stub + CI workflow + formatting only; the prod import at `database/_client.py:9` is sound against the pinned dependency set. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/23042?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/23042?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23042&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. -->
….py api_core imports Nightly main run 39586610411 failed the Hygiene check screen-activity-batch-resilience-tests: database/_client.py (cap publication retry, BasedHardware#22966) now imports DeadlineExceeded, ResourceExhausted, and ServiceUnavailable from google.api_core.exceptions, but the bare-python3 preflight stub in test_screen_activity_batch_resilience.py only defined InvalidArgument and Aborted, so the module import failed before any test ran. Prod is unaffected: the pinned google-api-core 2.19.1 exports all five names; the ImportError only reproduces in the dependency-free hygiene runner that this stub exists for. Extend the stub with the three missing names in the existing per-name style. Also add backend/database/_client.py to the check's manifest triggers. BasedHardware#22966 touched only _client.py, which the trigger list omitted, so PR CI never ran this check and the breakage surfaced only in the nightly full run.
Summary
late:row instead of reporting an uncommitted merge. An ambiguous commit may still leave the fragment on both rows. A read after a successful staging write cannot close the socket.usage_appliedas uncounted and incremented the summary again, counting its audio twice. No such receipt can exist: the writer deployed in prod today creates the receipt and increments the summary in one transaction (so a markerless receipt in prod is pre-marker, already counted), this PR's writer does the same with the marker, and recovery has never run in prod — API/sync cap enforcement is false and zero recovery calls were observed. Both paths now stampusage_appliedon an existing receipt without incrementing; the summary moves only with a create.users/{uid}/stt_cap_fragment_claims/{fragment_id}with{hold_id, fragment_id}. Inside the seal transaction every claim is read before the first claim is created, because Firestore rejects a transactional read after a queued write (ReadAfterWriteError); the previous interleaved loop could never seal a group with more than one fragment. A fragment is composed, counted, and later deleted only by the row that holds its claim. A row whose fragments were all claimed elsewhere seals assupersededwith zero seconds, does not increment the summary, and drops any composite it had published. An unconfirmed late row fails the flush without deleting the uploaded object.chunks/{uid}/cap-held/{hold_id}.{sha256(sorted fragment ids)[:16]}.opus.enc. A retry with the same claim set resolves to the same immutable object. A retry that lost a fragment to another row claims a smaller set and composes a different object instead of reloading the wider composite, and the wider composite is dropped as unpublished — by a post-commit cleanup run by the row that committed, never inside the transaction callback, where up to 2^4−1 sequential GCS deletes with 10s timeouts could outlive the transaction's own deadline. The drop only ever names this hold's own compose destinations: never the committed set's object, a fragment source, or another hold's object. The manifest'sopus_fragmentstherefore always describes exactly the bytes inaudio_path.cap_hold.claimtreatssupersededas terminal alongsidecompleted,retained,purged,staging, andsealing.omi_held_content_publication_retrycountsretried_ok,exhausted,staged_unverified, andsource_orphaned(a flush that failed closed, 1011, after uploading a fragment no row names) with a closed label set and no uid.This uses the existing
run_transactionalboundary. The default path still retries only an expired transaction id. Publication opts into the wider transient set because those writes re-read before they increment.Failure-Class: new
The PR's original class was FC-retired-transaction-treated-as-fatal (a Firestore commit rejected because its transaction id was retired wrote nothing and is recoverable). The round-6 commit additionally names the lenient transaction double (a test double that accepted a read the production store rejects) under the test-double-accepts-payload-store-rejects class in its own message. The round-7 commit declares FC-marker-absence-read-as-unapplied, whose definition this PR adds: a repair read the absence of a marker, introduced after the deployed writer already committed the marked side effect atomically with the record, as proof the side effect never ran.
Line-Count-Exception: backend/routers/listen/receiver.py | 2766 -> 2777 | Both listen 1011 sites share one close helper so staged success and a failed staging write are asserted on the real assignment.
Test plan
BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=<12 cap/held-content/redrive files> nice -n 10 backend/test.sh: 269 passed, 0 failed (round 7)late:row that seals oncelate:row instead of reporting the uncommitted mergelate:row is composed once and counted once, in either seal order, and the composed audio survives cleanuplate.createreturning AlreadyExists and then a failed read leaves the source blob in place, fails the caller, and countssource_orphanedReadAfterWriteError(the real client's class) on a transactional read after a queued write; a three-fragment group seals in one transaction with every claim read first, and every claim is a permanent{hold_id, fragment_id}document with no expirysource_orphanedand keeps the source; a failed first read (no upload) and a fragment staged for redrive do not count itcap_hold.claimreturns None forsupersededand every other terminal or unsealed state without touching the rowreceive_dataleaves the close code alone when staging succeeds and sets 1011 when the staging write fails