Repository navigation
Retain future canonical audio in verified owner packs - #21544
Conversation
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: 9a86f3834f
ℹ️ 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".
| canonical_name = os.getenv('BUCKET_CANONICAL_AUDIO') | ||
| if canonical_name: | ||
| with destructive_operation_gate(uid, kind='audio_conversation_deletion'): | ||
| audio_packs.delete_conversation(get_canonical_audio_bucket(), uid, conversation_id) |
There was a problem hiding this comment.
Preserve canonical captures when merging conversations
When canonical storage is configured, every call to this shared cleanup helper now performs a privacy-style canonical deletion. The manual merge path calls _delete_conversation_and_related_data for each source conversation (backend/utils/conversations/merge_conversations.py:390-401), which reaches this helper after copying only the existing playback chunks; consequently, merging conversations rewrites the source packs to remove their canonical captures without relinking them to the merged conversation. This irreversibly defeats the new retention guarantee for every manually merged recording, so canonical deletion needs to be restricted to actual user/privacy deletion or the ranges must be reassigned during merges.
Useful? React with 👍 / 👎.
| 'producer': 'pusher', | ||
| 'sample_rate': sample_rate, | ||
| 'encrypted': encrypted, | ||
| 'encryption_envelope': 'uint32le-nonce12-aes256gcm-hkdf-v1' if encrypted else None, |
There was a problem hiding this comment.
Label the encrypted capture envelope as big-endian
For enhanced-protection pusher captures, this metadata says the four-byte envelope length is little-endian, but encrypt_audio_chunk writes it with struct.pack('>I', ...) (backend/utils/encryption.py:118-120). Any archive consumer following the stored provenance will interpret the length incorrectly and be unable to decrypt most captures; advertise a big-endian envelope or change the encoding to match the declared format.
Useful? React with 👍 / 👎.
| for blob in bucket.list_blobs(prefix=owner_prefix(SOURCE_PREFIX, uid)): | ||
| if affected(json.loads(blob.metadata['capture'])): | ||
| blob.delete(if_generation_match=int(blob.generation)) |
There was a problem hiding this comment.
Reject late canonical writes for deleted conversations
A conversation deletion performs only this one-time listing and deletion, while owner_storage_write_gate is explicitly a check-only fence that does not lock writers (backend/utils/other/storage.py:133-154). A pusher upload that passed the fence before the destructive gate, or that retries after the gate is released, can therefore create its source and receipt after this scan; archive_capture never checks the conversation tombstone, so the newly retained audio survives the user's deletion indefinitely. Persist a deletion marker that archive intake checks, or otherwise make deletion drain and verify all late writes before completing.
Useful? React with 👍 / 👎.
| 'start': min(c['timestamp'] for c in chunks), | ||
| 'end': max(c['timestamp'] for c in chunks), |
There was a problem hiding this comment.
Record the full duration of each pusher capture
The normal pusher path passes one aggregate chunk per flush (backend/routers/pusher.py:318-335), so min(timestamp) and max(timestamp) are identical and every archived PCM capture is recorded as a zero-duration range; even multi-chunk callers omit the duration of the last chunk. These manifests are permanent archive metadata advertised as conversation ranges, so consumers cannot place the retained bytes accurately. Compute the end from the authoritative span or from the PCM byte length and sample rate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 61edba840e
ℹ️ 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".
| except Exception as e: | ||
| logger.error(f"Error deleting task vectors for {conversation_id}: {e}") | ||
| background_tasks.add_task(delete_conversation_audio_files, uid, conversation_id) | ||
| background_tasks.add_task(delete_conversation_audio_files, uid, conversation_id, delete_canonical=True) |
There was a problem hiding this comment.
Make canonical deletion durable before returning success
When cascade=true, a transient GCS error, gate conflict, or process termination can abort this in-process background task after the endpoint has already returned 204 and removed the conversation. There is no durable job or tombstone reconciler that retries audio_packs.delete_conversation, so the newly indefinite canonical source or pack can retain audio permanently despite a successful privacy deletion. Complete the canonical purge synchronously before success, or durably enqueue and reconcile it.
Useful? React with 👍 / 👎.
| with owner_storage_write_gate(uid, canonical): | ||
| audio_packs.archive_capture( |
There was a problem hiding this comment.
Recheck account deletion after canonical publication
If an account deletion starts after this check-only owner_storage_write_gate admits a pusher write, the account wipe can finish its one-time canonical-prefix scan before the source or receipt upload completes. Unlike the new conversation-deletion checks, archive_capture never rechecks the durable account-deletion marker after publication, so that in-flight capture can survive the completed account wipe indefinitely. Recheck account deletion after both source and receipt publication and remove racing objects, or otherwise drain admitted writers before verifying the wipe.
Useful? React with 👍 / 👎.
| if merged_into: | ||
| audio_packs.link_conversations(canonical, uid, [conversation_id], merged_into) |
There was a problem hiding this comment.
Allow retrying merges after publishing a canonical link
If canonical linking succeeds but any subsequent private-bucket deletion or conversation deletion fails, the merge handler preserves the first merged target and resets the still-existing source to completed. A user retry creates a fresh target UUID, but link_conversations then rejects the source because its durable link points to the first target, so the merge repeatedly fails and the source cannot be merged again. Either resume cleanup against the original target or make the link rollback/retarget operation recoverable before restoring the source.
Useful? React with 👍 / 👎.
…rward # Conflicts: # backend/docs/feature-flag-registry.md # config/feature-flags.yaml
…rward # Conflicts: # backend/docs/listen_pusher_pipeline.mdx
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cc4215d378
ℹ️ 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".
| 'encrypted': encrypted, | ||
| 'plaintext_sha256': digest, | ||
| }, | ||
| conversation_ranges=[], |
There was a problem hiding this comment.
Associate known mobile captures with their conversation
When /v2/sync-local-files receives its supported conversation_id query parameter, the archive call still discards that association and stores an empty range list. Consequently, a later cascade deletion of that conversation cannot match this canonical capture in delete_conversation, so the mobile audio remains indefinitely until the entire account is deleted. Pass the known conversation ID into this archive metadata; uploads without one need a durable way to attach their eventual assignment.
Useful? React with 👍 / 👎.
| for blob in bucket.list_blobs(prefix=f'{owner_prefix(SOURCE_PREFIX, uid)}{day}/'): | ||
| if blob.name in claimed: | ||
| continue |
There was a problem hiding this comment.
Distinguish recreated source generations when packing
If intake stops after uploading a source but before publishing its receipt, the packer can pack and delete that source; a later intake retry then recreates the same pathname with a new generation and publishes the receipt. Because completed manifests claim only the pathname here, every subsequent pack run skips the recreated generation forever, leaving it unpacked and outside the manifests used by consumers. Track claims by pathname and generation, or ensure the receipt is durably established before deleting the source.
Useful? React with 👍 / 👎.
| _validate_owner(manifest, uid) | ||
| if manifest['state'] != 'complete' or any(affected(e) for e in manifest['entries']): | ||
| raise RuntimeError('canonical erasure left an affected manifest') | ||
| verify_pack(bucket.blob(manifest['pack']).download_as_bytes(), manifest) |
There was a problem hiding this comment.
Avoid downloading every pack during conversation deletion
For an owner with substantial retained history, deleting one conversation downloads and verifies every canonical pack, including packs whose manifests contain no affected entry. Since packs target 256 MiB and transition to Coldline/Archive, an established account can require tens or hundreds of gigabytes of retrieval under one deletion gate, making the privacy cleanup prohibitively slow and expensive and likely to terminate before completion. Use a conversation-to-pack index or restrict byte verification to packs actually rewritten.
Useful? React with 👍 / 👎.
| except Exception as e: | ||
| if merged_into: | ||
| raise |
There was a problem hiding this comment.
Link canonical audio before destructive source cleanup
If canonical bucket validation, gate acquisition, or linking fails here before publishing a link, the function has already retracted the source memories, deleted its action items, and removed its photos. Reraising then causes merge failure handling to restore the source to completed while preserving the merged target, leaving the user with an incomplete source and a duplicate target even though no canonical link was established. Complete the fallible link before destructive source cleanup, or make this failure path resume or roll back those earlier effects.
Useful? React with 👍 / 👎.
| return committed_paths + [path] | ||
| break | ||
|
|
||
| _archive_pusher_capture(chunks, uid, conversation_id, protection_level, sample_rate) |
There was a problem hiding this comment.
Bound optional canonical work off the pusher upload path
When canonical storage is slow or unavailable after the primary playback object commits, this synchronous call keeps the pusher's awaited upload_audio_chunks_batch operation and a storage_executor worker occupied until all canonical bucket reads, uploads, and SDK retries finish. The pusher does not update its committed-run ledger or release the batch's audio budget until that return, so an outage in the optional archive can backlog or drop primary live-audio work across sessions despite the exception eventually being swallowed. Run this best-effort archive independently with a strict deadline or durable queue.
Useful? React with 👍 / 👎.
| if bucket.location.lower() != 'us-central1' or bucket.versioning_enabled: | ||
| raise RuntimeError('canonical archive requires regional location and versioning off') | ||
| if bucket.soft_delete_policy.retention_duration_seconds not in (None, 0): | ||
| raise RuntimeError('canonical archive requires soft delete off') |
There was a problem hiding this comment.
Reject canonical buckets with retention policies
A bucket with a nonzero or locked retention policy currently passes this runtime validation because only versioning and soft deletion are checked. Once captures are written there, conversation deletion and pack rewrites call generation-matched object deletes or replacements that the retention policy rejects; a locked policy can make the promised privacy erasure impossible to restore operationally. Validate that no retention period or lock is configured before accepting the canonical bucket.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1fab749784
ℹ️ 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".
| background_tasks.add_task(delete_conversation_audio_files, uid, conversation_id) | ||
| # Snapshot retained bridge donors before shared metadata cleanup removes them. | ||
| source_ids = (conversations_db.get_conversation(uid, conversation_id) or {}).get('sync_merged_from', []) | ||
| background_tasks.add_task(delete_privacy_conversation_audio, uid, conversation_id, source_ids=source_ids) |
There was a problem hiding this comment.
Purge canonical audio from the developer delete route
When canonical packing is enabled, this is the only conversation route wired to delete_privacy_conversation_audio, but the documented permanent-delete endpoint DELETE /v1/dev/user/conversations/{conversation_id} still only records a tombstone and calls delete_conversation_with_sync_sources (backend/routers/developer.py:2427-2428). That helper never erases canonical packs or sources, so deleting a pusher-created conversation through the developer API leaves its newly retained audio indefinitely; route that endpoint through the same canonical erasure path before reporting success.
Useful? React with 👍 / 👎.
| capture = json.loads(blob.metadata['capture']) | ||
| assert_capture_allowed(bucket, uid, capture['conversation_ranges']) | ||
| entry = {'source': blob.name, 'generation': str(blob.generation), **capture} |
There was a problem hiding this comment.
Resolve merge links again while packing sources
If canonical intake passes the check-only write fence before a manual merge acquires its destructive gate, the merge can publish its source-to-target link and finish the source scan before that intake uploads its source metadata. The subsequent pack run copies those stale donor ranges unchanged here—assert_capture_allowed follows the link only for validation—so the permanent manifest points at the deleted donor rather than the merged conversation and consumers querying by survivor miss the capture. Resolve _retarget_ranges when constructing each pack entry so the durable link also repairs this in-flight merge race.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a1965187a6
ℹ️ 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".
| ).decode() | ||
| } | ||
| try: | ||
| blob.upload_from_string(payload, if_generation_match=0) |
There was a problem hiding this comment.
Reconcile sources published after the deletion scan
The new deletion marker still leaves a crash window: if intake passes the initial assert_capture_allowed, conversation deletion then publishes its marker and completes both source scans, this upload can occur afterward and the process can terminate before the post-upload check removes it. Fresh evidence in the updated code is that the durable marker blocks future packing but no reconciler scans marker-blocked sources, so this orphan retains deleted conversation audio indefinitely. Make source publication atomic with the deletion fence or add durable cleanup of sources associated with deletion markers.
Useful? React with 👍 / 👎.
| if bucket.location.lower() != 'us-central1' or bucket.versioning_enabled: | ||
| raise RuntimeError('canonical archive requires regional location and versioning off') | ||
| if bucket.soft_delete_policy.retention_duration_seconds not in (None, 0): | ||
| raise RuntimeError('canonical archive requires soft delete off') |
There was a problem hiding this comment.
Enforce private access before accepting the archive bucket
If BUCKET_CANONICAL_AUDIO points to a regional bucket with versioning and soft deletion disabled but public IAM access is enabled, this validation accepts it and immediately starts writing users' raw capture audio there. The deployment runbook requires uniform bucket-level access and public-access prevention, but neither property nor the bucket IAM policy is checked here, so a configuration mistake can expose every newly archived recording. Reject buckets without enforced public-access prevention and the required access-control configuration before caching the bucket.
Useful? React with 👍 / 👎.
…out push (#21417) ## What changed and why Closes #19247 and #20603. Manual merge must finish in the running app without depending on push, and a completed result must not retain cached original rows. All manual admissions now use the existing durable merge coordinator regardless of the broader lifecycle canary. The admitted target ID remains stable through partial cleanup/retry; authoritative transfer receipts prevent already-incorporated originals from being merged again, while ordinary semantic duplicate hints retain merge eligibility. Capture/transcription rollout behavior is unchanged. The client uses typed source absence and target readiness, journals IDs by account/backend, and commits list/search/pagination/cache changes together. Cache transactions, page-cache writes and merge-journal retirement are serialized; concurrent completions retain both targets after offline reopen, failed transactions remain retryable, and queued work rechecks account/backend ownership. Merges still processing after the fast polling window remain observed at a lower bounded rate. A read failure or locked response never proves deletion, and observation never resubmits a merge. This extends Dragonire9's existing PR, preserving the contributor commits. Main's #21544 already covers the source-deletion propagation proposed by #21525; current-owner tests preserve that guard. No contributor PR is closed and no bounty is accepted or promised. ## Verification - 129 focused Flutter provider/cache/search/processing/Spotlight tests and 31 adjacent delete/undo, auth retry, date-filter and recap tests passed. Seven new regressions cover concurrent completions with/without refresh, failed cache-read retry, queued account/backend replacement, a stale former target and old-server preservation of unrelated rows pending deletion for Undo. The concurrent offline-cache regression fails at the previous green head 353761f and passes with this fix. - 97 focused file-isolated backend tests and all 34 batch-upload storage tests passed, covering route modes off/shadow/serve, atomic admission loss, source receipts, cleanup refusal, same-target retry, worker rereads and validation. - 9 integration tests passed against the pinned Firestore emulator (firebase-tools 15.22.0): competing admissions, correction transfer, lease expiry/fencing, partial cleanup failure, restart/retry into the same target without paid processing, and consumed-source refusal. - Local HTTP foreground, reopen, delayed completion and simultaneous completion/offline-reopen journeys passed twice: 16 recorded assertions. The offline case shuts down the loopback backend before reopening. Real client decoding/provider/cache/row widgets execute; auth and backend worker/storage effects are synthetic. Backend emulator tests exercise the durable owners separately. - Three cache/failed-read regressions fail on byte-exact current-main provider code and pass in this PR. The batch-upload fixture resolves the real pure merge policy while retaining isolated client/IO dependencies; all 34 file tests pass. - The nine WAL live-custody tests pass twice. Their gated-index test observes the actual disk/index persistence checkpoint and releases its gate in finally; strict durability assertions and production WAL code are unchanged. - Changed-file Flutter analysis is clean. Exact-head CI at f66450e passes: 34 successful checks, 19 conditional skips, one neutral docs preview, no failures or pending checks. Full Dart analysis/tests passed with 7,640 tests and four skips; all six backend shards, aggregate backend suite and seeded journeys passed. Linux packaging passed a same-commit retry after an Ubuntu package-download timeout. Unselected native-compile/far-timezone lanes are not claimed as verified. ## Technical readiness and release Final diff review, local integration evidence and required exact-head CI pass at f66450e. The PR remains draft for maintainer review; it has not been merged or deployed. Customer confirmation is not a technical readiness or GitHub-closure gate. Deploy the additive backend response before mobile release. No LIFECYCLE_V2_MODE serve-cohort change is needed for manual merge correctness. Existing finalization recovery infrastructure remains required (production runtime manifests already declare the conversation-finalization Cloud Tasks queue). This PR does not change production configuration, deploy, merge, or mutate customer records. Support separately owns historical-account investigation and post-release customer confirmation; those remain in the support tracker and do not keep a verified technical fix open on GitHub. ## Product invariants affected none UI-Evidence: none -- No layout/control code changed. The local HTTP journey renders the production row and verifies only the completed target remains without a merging overlay in foreground, reopen, delayed completion and concurrent-completion offline reopen. Failure-Class: new ## Failure-class transition narrative FC-merge-completion-depends-on-push records the demonstrated contract: a best-effort push is not a completion authority. Its reusable guard is typed target/source observation and a shared provider/cache commit; behavioral provider and HTTP journey tests cover recurrence. Durable manual admission removes the legacy recovery bypass rather than adding another recovery owner. Line-Count-Exception: app/lib/providers/conversation_provider.dart | 2197 -> 2420 | Keep canonical admission/projection ownership in the established owner; bounded observation and journal serialization live in small separate services.
New capture audio can be retained in owner/day tar shards without touching existing stock. This adds a default-off canonical archive intake, a resumable 256 MiB target packer, per-owner manifests, account wipe coverage and conversation pack rewrites.
The new regional bucket contracts scope every added rule to a release-specific prefix:
canonical-packs-20261015-v1/moves Standard→Coldline at day 30 and Coldline→Archive at day 120; new staging/merge/playback prefixes expire at 1/3/30 days. Existing lifecycle files are unchanged. No bucket policy has been applied, scheduler enabled, deployment made, or existing object migrated.Stored bytes are preserved (including enhanced encryption); manifests contain SHA-256, source generation, tar byte ranges, format, provenance and conversation linkage when available. Original mobile Opus is kept as captured. Desktop/pendant pusher intake today is PCM16 and is labeled accordingly. Playback retains its existing renditions. Sources are erased only after pack hash verification and embedded-manifest round-trip, with durable publication before erasure. Conversation deletion CAS-rewrites affected new packs; account deletion sweeps packs, pending intents, sources and retry receipts even with packing disabled.
Apply/rollback and current GCS list-price economics:
backend/deploy/storage-lifecycle/FORWARD.md. Only new empty regional buckets may receive these policies; versioning and soft-delete are off from creation. At 256 MiB, a regional Coldline move costs $0.000020 versus $0.004/month storage saving; Archive costs $0.000050 versus an additional $0.0007/month. GCS list pricesReview corrections commit existing playback/mobile raw objects before best-effort archival, cache bucket policy reads, and preserve canonical captures across manual merges by retargeting embedded manifests and unpublished source metadata. Owner-scoped survivor links handle late retries. Canonical erasure runs only at the explicit privacy/account boundaries, with retained bridge donors snapshotted before metadata cleanup only when the canonical bucket is configured and a final gated manifest/generation re-list. Unaffected archived packs are never downloaded by the erasure check. Durable deletion markers are checked before and after intake publication, and racing writes are removed. Full PCM tail durations and the big-endian encryption envelope are tested.
Local validation: 172 focused tests across ten suites through
backend/test.sh(storage, deletion, merge and review regressions),backend/scripts/pre-deploy-check.sh(305 tests),make preflight(34 checks), full backend type check (zero errors; existing warnings), and the complete pre-push gate passed. The CLI default-off check exits before bucket access. CI passed ona1965187a6a8f2995f744ebb7c79a703dc931537, including all six full backend shards and backend guardrails (run 38635528034). The PR check rollup remains authoritative.Failure-Class: none
The fix commits correct review findings in this new default-off feature before release; they do not describe a shipped regression.
Product invariants: none (confirmed by current preflight suggestions).
Line-Count-Exception: backend/utils/other/storage.py | 2075 -> 2209 | Connect existing upload and deletion boundaries to the separately implemented forward archive module without moving unrelated storage APIs.
Line-Count-Exception: backend/routers/conversations.py | 2309 -> 2316 | Snapshot retained bridge donor IDs at the explicit privacy boundary before shared metadata cleanup removes their ownership inventory.