Skip to content

fix: retry live cap publication when a Firestore transaction expires - #22966

Merged
Git-on-my-level merged 8 commits into
mainfrom
lane/cap-publication-retry
Oct 21, 2026
Merged

Git-on-my-level merged 8 commits into
mainfrom
lane/cap-publication-retry

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Live cap publication retries an expired, aborted, deadline, unavailable, or resource-exhausted Firestore transaction on a fresh transaction (3 attempts, equal-jitter backoff well under 5s) instead of treating the retired id or the throttle as a write failure. Resource exhaustion is on the transient publication path only; other callers still retry only an expired transaction id.
  • When that budget is spent and the uploaded audio is durable, the fragment stays in a staging row for the redrive (the non-fragment path writes the held receipt once) and the socket stays up. A non-retryable error still surfaces and still closes the socket.
  • A fallback append preconditions on the staging row's update time. Custody is returned only when a read shows a row holds the fragment. Exhausted appends, a failed re-read, and a create that loses to a row without this fragment open the deterministic 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.
  • Markerless receipts are already counted. The live commit and the recovery transaction both treated an existing receipt without usage_applied as 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 stamp usage_applied on an existing receipt without incrementing; the summary moves only with a create.
  • Custody and claim rule. Seal creates one claim document per fragment id, 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 as superseded with 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.
  • Claim-set destination. Compose runs before the claim transaction commits, so the composite is named by its claim set: 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's opus_fragments therefore always describes exactly the bytes in audio_path.
  • Claim ledger permanence. Claims carry no expiry. A TTL could let a duplicate row re-claim a fragment later and count it twice, so claims stay permanent until a later cleanup can prove that every row referencing the fragment is terminal and the source is gone; that cleanup is deliberately not built here. The ledger is tiny, and account erasure already deletes it with the user.
  • cap_hold.claim treats superseded as terminal alongside completed, retained, purged, staging, and sealing.
  • omi_held_content_publication_retry counts retried_ok, exhausted, staged_unverified, and source_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_transactional boundary. 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)
  • expired transaction publishes exactly once; aborted read retries on a fresh transaction; exhausted retries leave a staging row the redrive seals once; a non-retryable InvalidArgument is not retried; a deadline after a landed commit does not increment usage twice
  • ResourceExhausted once then success publishes one fragment; ResourceExhausted past the budget stays staged and the redrive seals it once; the default non-transient path does not retry ResourceExhausted
  • A seal that wins between the fallback read and write is not overwritten; the late row's composed object survives cleanup and stays readable; usage is counted once
  • An ambiguous commit that lands the fragment, followed by a precondition failure, seals one copy and counts usage once
  • Three rejected conditional appends with the group still staging and missing the fragment open a late: row that seals once
  • A failed final read, and a create that loses to a row without the fragment whose follow-up read fails, open the late: row instead of reporting the uncommitted merge
  • The same fragment on the group and the late: row is composed once and counted once, in either seal order, and the composed audio survives cleanup
  • A create that loses to a row that already holds the fragment, whose follow-up read fails, still ends at one count
  • late.create returning AlreadyExists and then a failed read leaves the source blob in place, fails the caller, and counts source_orphaned
  • Two seals of those rows, interleaved at commit, produce one claim
  • The transaction double raises ReadAfterWriteError (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 expiry
  • A seal that composed X+Y and retired its transaction, after another row claimed Y, recomposes X alone on a different object; manifest and object agree byte for byte, X and Y are each counted once, and the X+Y composite is dropped by the post-commit cleanup, after the sealing row's own commit lands
  • A permanent commit failure after the upload counts source_orphaned and keeps the source; a failed first read (no upload) and a fragment staged for redrive do not count it
  • cap_hold.claim returns None for superseded and every other terminal or unsealed state without touching the row
  • A markerless receipt whose summary was already incremented by the deployed writer is counted exactly once through both the live commit and the recovery transaction: the marker is stamped, the summary never moves, and no upload runs
  • receive_data leaves the close code alone when staging succeeds and sets 1011 when the staging write fails
  • A ResourceExhausted read after a successful staging write does not close the socket with 1011, and the redrive seals later. Staged success is not 1011; a staging-write failure is 1011
  • Related durability, live-hold, conversation-expiry, failure-reason, and contention-retry unit files
  • Luna review (do not merge from this PR's author)

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]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-21T07:25:41.997042Z 97ddf55 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: 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".

Comment on lines 98 to +99
with external_write_fence(uid):
commit(client.transaction())
run_transactional(client, commit, transient=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment thread backend/utils/sync/live_cap_staging.py Outdated
Comment on lines +136 to +140
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)

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 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 👍 / 👎.

Comment thread backend/utils/sync/live_cap_manifest.py Outdated
Comment on lines +71 to +75
ref.create({**body, 'live_custody_version': 4})
except AlreadyExists:
return True
total.set(
{'seconds': firestore.Increment(seconds), 'count': firestore.Increment(1)},

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 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 👍 / 👎.

Comment on lines +88 to +95
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] = []

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 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 👍 / 👎.

Comment on lines 98 to +99
with external_write_fence(uid):
commit(client.transaction())
run_transactional(client, commit, transient=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Git-on-my-level and others added 2 commits October 21, 2026 09:40
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]>

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

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 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 👍 / 👎.

Comment on lines +195 to +196
if row.get('state') != 'staging':
return _stage_late_fragment(part, updates)

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 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 👍 / 👎.

Comment on lines +135 to +139
'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')),

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 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 👍 / 👎.

Comment on lines +143 to +145
def _stage_late_fragment(part: dict, updates: dict) -> dict | None:
late = cap_hold.holds(uid).document(fragment.identity)
body = _late_staging_body(part, updates)

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 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]>

@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: 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".

Comment thread backend/utils/sync/live_cap_staging.py Outdated
type(error).__name__,
)
record_publication_retry('staged_unverified')
return staged

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 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 👍 / 👎.

Comment thread backend/utils/sync/live_cap_staging.py Outdated
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

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 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 👍 / 👎.

Git-on-my-level and others added 2 commits October 21, 2026 11:09
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]>

@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: 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".

Comment thread backend/utils/sync/live_cap_staging.py Outdated
if holder and holder != identity:
continue
if not holder:
tx.create(claim_ref, {'hold_id': identity, 'fragment_id': fragment_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.

P1 Badge 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'):

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 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 👍 / 👎.

Comment on lines 472 to 473
except PreconditionFailed:
target.reload(timeout=10, retry=None)

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

@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: 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".

Comment thread backend/utils/sync/live_cap_staging.py Outdated
return {
'hold_id': identity,
'fragment_id': fragment_id,
'expire_at': datetime.now(timezone.utc) + timedelta(seconds=CLAIM_LEDGER_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 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 👍 / 👎.

Comment on lines +287 to +293
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

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 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 👍 / 👎.

Comment on lines +184 to +186
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.

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 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 👍 / 👎.

Comment on lines +426 to +428
if unresolved:
# Leave the flag set so the cleanup sweep can try this row again.
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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

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

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 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']),

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 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])

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 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 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit bccccd6 into main Oct 21, 2026
57 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/cap-publication-retry branch October 21, 2026 07:34
Git-on-my-level added a commit that referenced this pull request Oct 21, 2026
## 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. -->
airdropia pushed a commit to airdropia/omi that referenced this pull request Oct 21, 2026
….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.
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