Skip to content

fix: retain recovered episode speech and reject unsafe scope bindings - #23828

Merged
Git-on-my-level merged 5 commits into
mainfrom
lane/p88fix
Oct 27, 2026
Merged

Git-on-my-level merged 5 commits into
mainfrom
lane/p88fix

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

What changed and why

Fix three P1 episode/projection failures identified in #23404 and #23418. Client projection binding now rejects mixed scopes among unnamed voices while preserving hash encoding v5. WAL attachment and sync finalization merge recovered member speech into running notes with transactional content receipts; close rechecks recovered member transcripts for unapplied speech. Attachment retries version conflicts three times with jitter and fresh reads, and saturated episode hooks retain bounded deferred admission until capacity returns.

Recovered text uses bounded batches so prompt truncation cannot acknowledge unseen words. Complete live prompt input and recovery share content-revision receipts, so WAL appended to the same canonical conversation skips proven live speech and preserves novel gaps. Donor repointing transfers receipt namespaces with the membership CAS inside the retry owner; absorb finalization reads the survivor's current transcript. Canonical ingest binding uses the same scope guard as persisted binding. Existing EPISODES and LIFECYCLE flags and defaults are preserved.

Failure-Class: FC-once-only-trigger-dropped-at-capacity

The admission regression is a once-only trigger lost at capacity. Companion tests cover missing scope in v5 binding and recovered speech incorrectly treated as already consumed.

Product invariants affected

INV-TASK-2: episode updates retain provisional items and never write action items, Candidates, or memories. Customer identity and serving-plane authorities are preserved (INV-DATA-1).

How it was verified

  • Local backend shard through BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/p88fix/regressions.txt BACKEND_PYTEST_WORKERS=1 bin/omi-heavy run -- nice -n 19 bash backend/test.sh (workspace bin/omi-heavy): all 16 targeted files passed again after the round-two corrections, including 78 episode-service cases, ingest trust/idempotency and the background-task inventory ratchet.
  • Fail-before/pass-after: corrected regressions run against base production sources 5f2caea10a6 fail on mixed-scope binding, lost recovered notes/close rebuild, two CAS conflicts, and saturated final hooks. The candidate passes those regressions.
  • bin/omi-heavy run -- nice -n 19 make preflight: all 35 repository checks passed (389 seconds), including Firestore guards, runtime source closure, async blocking, import purity, metadata, and file-size gates.
  • bin/omi-heavy run -- nice -n 19 bash backend/scripts/typecheck.sh: canonical full backend type check, zero errors.
  • bin/omi-heavy run -- nice -n 19 bash backend/testing/sync_cloud_tasks_stack/run.sh --only sync --state-dir /Volumes/Ephemeral/scratch/p88fix/sync-stack: hermetic Sync Cloud Tasks gauntlet passed with real local Firestore/Redis and separate admission/worker processes; sanitized evidence retained.
  • Read-only Luna rounds 1 and 2 returned FIX-FIRST; their findings were corrected with fail-before/pass-after regressions. Under acknowledged lead ruling 2fedac, no third review runs: acceptance is corrected-head CI plus the regression mapping for the lead's delta review. Terminal CI and that mapping will be attached before handoff.

These are source, hermetic unit, and local harness claims. Product deployment and production acceptance belong to the lead's release train.

Tests

  • test_transcript_hash.py: dict/model scope-only attribution correction, legacy unscoped mix, bound owner/person compatibility, v5 unchanged.
  • test_client_processing_finalize.py: router and transactional binding reject the stale digest while finalization fields survive.
  • test_episodes_service.py: recovered speech at attach, idempotent replay, existing member gap behind an applied offset, close after a provider failure, three fresh CAS attempts retaining concurrent members, full long-transcript prompt coverage in served/legacy modes, preserved speaker-evidence IDs, and ordinary-finalize/unplaced-slice failure receipts.
  • test_episodes_finalize_paths.py and test_executors.py: saturated final/intake hooks run without another append, context survives, errors surface, cancelled and shutdown work stays bounded.
  • Review regressions fail at 0b0e740ae3c and pass after correction: canonical ingest scope guard, same-row live/WAL consumption, donor receipt transfer, and fresh donor CAS attempts. The merged-survivor finalization test also proves only novel survivor speech reaches the model.
  • test_background_task_ratchet.py: both retry APIs remain subject to caller inventory; returned cast-wrapped futures transfer ownership while done callbacks alone remain detached. The new regression fails before correction; all six scanner cases pass afterward.
  • Round-two regressions fail at 90f2eff0f13 and pass after correction: absorbed callback survives two fresh CAS conflicts, legacy-only donor receipts prevent replay, and transferring 50,000 content receipts bounds every archive to 2,000 IDs while retaining order and all proof.

Risks and rollout

Recovery can add notes-model calls for retained WAL snapshots whose prior live consumption cannot be proved. Older placed cursor-only state cannot distinguish an old line from a new gap behind that cursor, so its first recovery conservatively merges the retained snapshot once. Legacy unplaced-ID receipts remain proof; new live content receipts prevent replay. Updates merge into the existing compact state. The deferred queue is process-local like the ordinary executor queue, capped at 64 pending submissions with synchronous producer backpressure when full; shutdown cancels it. Its documented background-task inventory entry retains the existing best-effort episode-overlay lifetime over durable source conversations. No new queue infrastructure or migration is required.

Lead-owned backend/listen/pusher release train required after merge. No production access or mutation was used in this lane.

Reject mixed unnamed-speaker scopes at the v5 projection binding seam.
Apply recovered WAL member speech with transactional content receipts and
recheck unapplied member transcripts before closing an episode.
Retry attachment conflicts with fresh reads and queue saturated episode
hooks for admission when executor capacity returns.

Failure-Class: FC-once-only-trigger-dropped-at-capacity
Keep stored segment IDs in recovery prompts and use private slice keys for
consumption. Receipt an unplaced source ID only after its last slice lands,
so provider failure cannot consume unseen speech and normal finalization
does not replay an already recovered unplaced segment.

Exercise served and legacy notes rendering, retained speaker evidence IDs,
ordinary finalize replay, and provider failure between recovery batches.

Failure-Class: FC-once-only-trigger-dropped-at-capacity
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 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-27T20:14:42.934223Z 4041996 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: 0b0e740ae3

ℹ️ 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 +1041 to +1042
for moment in recovery.moments(conversation_id, row, now=_now(c), calendar_identity=_calendar_identity(row)):
outcome = record_moment(uid, moment, c, member_episode_id=episode_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 Release the episode worker between recovery batches

For a long recovered WAL transcript, this loop performs every batch's synchronous notes-model call while retaining the same executor slot. The intake/finalization hooks submit this entire operation to lifecycle_executor(uid, episode=True), which has only two workers in serving mode, and each model call permits a 20-second timeout. Two large recoveries can therefore monopolize the shared episode pool for minutes, delaying unrelated users' live notes and finalization hooks and eventually blocking sync producers when the deferred queue fills. Coordinate recovery asynchronously and borrow a worker per bounded step rather than holding one throughout the transcript; backend/AGENTS.md explicitly requires async coordination for long-running pipelines and prohibits holding a pool slot for more than 60 seconds.

AGENTS.md reference: backend/AGENTS.md:L270-L274

Useful? React with 👍 / 👎.

Comment thread backend/utils/episodes/service.py Outdated
Comment on lines +1154 to +1156
if episode is None:
return outcome
episode = episodes_db.get_episode_for_conversation(uid, conversation_id, firestore_client=c.firestore_client)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reconcile recovered items after a finalize-time attachment

When a WAL conversation first joins an episode during on_conversation_finalized rather than at intake, episode still contains the pre-attachment lookup result (None). _attach_synced now generates notes and provisional items, but this early return skips _reconcile for those newly created items even though the conversation's normal processing has already saved its tasks. Without another WAL append or repeated finalization, the items remain provisional instead of receiving their saved-task links, and a subsequent episode close drops them. Reload the newly attached owner and continue through reconciliation whenever attachment succeeds.

Useful? React with 👍 / 👎.

Comment on lines +1232 to +1235
'recovered_conversation_ids': list(
dict.fromkeys(
survivor_id if cid == donor_id else cid for cid in episode.get('recovered_conversation_ids') or []
)

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 recovery receipts when repointing a merged donor

When an already-recovered WAL member is merged into a survivor, this moves its recovery tracking to the survivor but leaves its consumption receipts under the donor's conversation ID. Sync assignment preserves retained donor segment IDs and text, yet the subsequent _attach_synced recovery reads receipts only for the survivor, so it sends the already-consumed donor speech through the notes model again and charges for every batch again. Repeated intake of that survivor is then idempotent, but each donor merge defeats the new receipt guarantee. Transfer the donor's recovery receipts or include its lineage receipts when checking consumption before recovering the survivor.

Useful? React with 👍 / 👎.

Use the fail-closed binding helper for canonical from-segments input too.
Record content-revision receipts for complete live prompts and reuse them
for WAL recovery, retaining legacy unplaced receipts and novel earlier gaps.
Transfer receipt namespaces with donor membership and retry donor CAS
conflicts through the same fresh three-attempt attachment owner. Absorb
finalization reads current survivor speech instead of replaying the donor.

Record the bounded queue's existing episode-overlay lifetime in the owning
background-task inventory and cover it in the local gate set.

Failure-Class: FC-once-only-trigger-dropped-at-capacity
Recognize both retry admission APIs in the background-task lifetime ratchet,
follow completion ownership through typing casts, and require the episode
caller to document its bounded derived-overlay lifetime separately from the
executor implementation. Add fail-before scanner coverage for orphaned and
returned handles.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Addressed the round-one review findings in the correction commit on this PR:

  1. Canonical from-segments binding now calls transcript_sha256_for_binding, as persisted binding does. The current wire model drops scope fields, so the precise wire-payload exploit described in the review is not reachable today; the canonical helper bypass was reproduced with scoped TranscriptSegment objects and is closed without expanding the wire schema or changing v5.
  2. Complete live prompt input now records content-revision receipts in an additional key of the existing transactional receipt store. WAL on that same canonical row skips proven live content while retaining novel earlier gaps. Truncated/filtered input does not mint a whole-input proof. Legacy unplaced-ID receipts remain effective. Older placed cursor-only state has no exact content proof, so its first recovery conservatively merges once rather than suppressing potentially novel speech.
  3. Donor repointing transfers both legacy and content-revision receipts in the same CAS as membership. Repeated intake/finalization on the survivor does not replay donor text; absorb finalization reads the current survivor and feeds its novel tail.
  4. Sync donor repointing now runs inside the fresh three-attempt attachment retry owner. Two injected version changes preserve the final survivor membership without leaving the donor behind.

All four review regressions fail at reviewed head 0b0e740ae3c and pass after correction. The 16-file local gate set, including ingest trust/idempotency and test_background_task_ratchet.py, passed; the final service rerun has 76 passing cases. The old-head CI failure was the new executor admission site's missing background-task inventory entry, now explicitly documented with its 64-entry bound, producer backpressure, cancellation, and derived-overlay shutdown limit. No check or enforcement flag is disabled.

The ratchet additionally recognizes both new retry APIs and inventories _queue_retry independently of the executor implementation. Its new scanner regression fails before the scanner correction and passes afterward (six scanner cases). Returning a cast-wrapped future transfers ownership; attaching a done callback alone remains flagged. No check or enforcement flag is disabled.

The lead authorized one delta-only Luna round in ruling 2664ef. CI and that review must pass at final head 90f2eff0f13e4993f301a1b9dcee3e7d7752c3a0 before the MERGE READY handoff. No merge, deploy, production call or customer-data mutation has been performed.

Include absorbed sync callbacks in the existing attachment retry owner,
adopt legacy unplaced donor receipts before membership moves, and split large
receipt transfers into bounded archives. Add fail-before/pass-after cases for
two conflicting absorbed callbacks, legacy proof and 50,000 content receipts.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Round-two correction delta for the lead's review. Luna r2 returned FIX-FIRST at 90f2eff0f13; lead ruling 2fedac directs fixing all three P2s, no third review, and accepts red/green regressions plus exact-head CI and this finding-to-test note before MERGE READY.

Finding Correction Fail-before / pass-after test
Absorbed SYNC_UPDATE repointed before the attachment retry owner. Pass the explicit donor to _attach_synced; re-read its owner and repoint within the same three jittered attempts. Surface exhausted conflict rather than reconciling stale state. Non-sync behavior is retained. test_donor_repoint_conflicts_retry_with_fresh_state_and_no_dead_member[True] injects two changing-version CAS failures, then asserts three distinct reads, live/survivor membership and exactly one recovered notes call. The existing [False] intake case also passes.
Repointing omitted older applied_segment_ids proof. If the donor receipt document does not exist, adopt its legacy map into the same transactional survivor receipt transfer. Existing receipt documents retain authority. test_repoint_adopts_legacy_unplaced_receipts_before_member_moves seeds proof only in the legacy map; the moved survivor retains the receipt and makes zero model calls for that speech.
A large donor transfer could put every spilled receipt in one Firestore archive. Limit each plan_write spill to SHARD_SIZE (2,000) while preserving order, all receipts, the recent base window and archive indices. test_large_donor_transfer_bounds_each_archive_and_retains_every_receipt transfers 50,000 content receipts and asserts every archive's bound and exact receipt retention/order.

All three regressions fail at 90f2eff0f13 (r2-before.log) and pass after correction (r2-after.log: 78 service and 4 receipt cases). Both review executions have been collected. No third agent review was started. No merge, deploy, production calls, data edits, flag changes, workflow changes or guard bypasses were used.

Correction commit: 4041996b6ea5dd14c9c33567f42a95fb473be00c. All 16 targeted regression files also pass again (r2-regression-gate.log). Normal push hooks and final exact-head CI are required in addition; their terminal results will be attached to the handoff record. Backend/listen/pusher release remains lead-owned.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

MERGE READY at 4041996b6ea5dd14c9c33567f42a95fb473be00c under lead acceptance ruling 2fedac.

  • Exact-head CI is terminal green with no pending, failed or cancelled checks; PR is OPEN, CLEAN, MERGEABLE. All 33 listed checks succeed and 24 are skipped. The CI waiter is collected.
  • All 480 targeted tests across 16 backend files pass. The normal push gate also passed all 37 preflights, full backend typecheck (zero errors), runtime closure, selected unit tests, API compatibility and formatting.
  • Both Luna rounds are collected. All round-two P2s have fail-before/pass-after regressions; the correction delta maps each finding to its test. No third review ran, per ruling; the lead owns final delta review.
  • Clean synthetic merge against refreshed main 0f55260be88bcdad1e1d8cb4629fe23f3ca9c6c8. Worktree status and diff checks are clean.

Lead owns merge and the backend/listen/pusher release train. No merge, deploy, flag flip, production call, customer-data mutation or GCP tier was used by this lane. Production acceptance remains a release-train responsibility.

@Git-on-my-level
Git-on-my-level merged commit 987d2b5 into main Oct 27, 2026
61 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/p88fix branch October 27, 2026 20:26
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