Skip to content

Generate multiple summary templates per conversation - #24801

Open
stmr wants to merge 14 commits into
BasedHardware:mainfrom
stmr:contrib/multiple-summary-templates
Open

stmr wants to merge 14 commits into
BasedHardware:mainfrom
stmr:contrib/multiple-summary-templates

Conversation

@stmr

@stmr stmr commented Nov 6, 2026 •

Copy link
Copy Markdown

Summary

Closes #4819.

  • Select up to five summary templates and generate them together; keep each saved result separate.

  • Commit a completed batch atomically and reject stale transcript, speaker, lock, deletion, or edited-result conflicts.

  • Preserve existing single-template clients and retry the selected batch after failures.

  • Preserve the stored is_locked flag when committing processing results instead of trusting the processor snapshot.

  • Make set_conversation_as_discarded a transactional read-modify-write; a missing row is a no-op.

  • Preserve recording-obligation registration and pending-summary cancellation on Developer API PATCH. Generated TypeScript and Swift clients send one app_ids query parameter per selected template.

Implementation and verification were AI-assisted. This is an unpaid contribution; no bounty is claimed.

Awaiting backend-owner sign-off: Developer API PATCH 402/404/409 compatibility for released clients, user_requested_at bypass of the enrichment age gate for explicit reprocessing, and HTTP 402 for budget-denied template reprocessing.

Verification

  • Review follow-up: 369 focused backend tests and 42 focused Flutter tests passed; localization validated for 49 locales. OpenAPI compatibility and freshness, Dart/TypeScript/Swift codegen, Swift DTO typecheck, and the route policy baseline passed. Flutter analysis reported the existing flutter/material.dart deprecation info.

  • Twelve focused backend suites on Python 3.11: 424 passed.

  • Four focused Flutter suites: 62 passed; changed client sources passed dart analyze.

  • Repeated query parsing and selection limits exercised through a local FastAPI test client with stubbed authentication and conversation lookup.

  • Selection sheet rendered in a Flutter test fixture; test fonts are placeholders, not device typography. No physical-device or production LLM run.

  • App-client OpenAPI regenerated using the repository's hermetic runner; generated Swift, TypeScript, and Dart contracts checked.

  • Local preflight reached the Swift-format gate but could not bootstrap it: this machine has Command Line Tools without the XCTest module. Hosted CI remains necessary.

UI-Evidence: none -- no tracked device screenshot; fixture layout inspected locally with placeholder test fonts.

Product invariants affected

  • INV-MEM-4
  • INV-TASK-2

Failure-Class: none

Line-Count-Exception: app/lib/backend/http/api/conversations.dart | 1490 -> 1501 | Reprocess query encoding stays with the existing HTTP adapter.
Line-Count-Exception: backend/database/conversations.py | 4855 -> 5374 | Transactional summary, restoration, visibility and concurrent-edit fences remain at the existing Firestore ownership boundary.
Line-Count-Exception: backend/routers/conversations.py | 2574 -> 2609 | Reprocessing request validation and recovery remain in the existing route.
Line-Count-Exception: backend/routers/developer.py | 2871 -> 2882 | Developer updates use the lifecycle owner's locked-row fence.
Line-Count-Exception: backend/utils/conversations/process_conversation.py | 3401 -> 3684 | Batch generation integrates with existing processing and durable effects.

@mintlify

mintlify Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit f2848d2.

Approve preview

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 6, 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 ⚠️ Failed 2026-11-06T17:50:42.596196Z
We couldn’t complete this review. Comment @codex review to try again.
cdb66e2 PR opened
ℹ️ 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.

@stmr

stmr commented Nov 6, 2026

Copy link
Copy Markdown
Author

The fork workflows are action_required. Could a maintainer approve them? Local verification is listed above; the Swift-format gate could not bootstrap on this machine because Command Line Tools lack XCTest, so hosted CI is still needed.

@cubic-dev-ai cubic-dev-ai 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.

All reported issues were addressed across 35 files

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

Comment thread app/test/helpers/reprocess_fakes.dart Resolved
Comment thread backend/routers/conversations.py Resolved
@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Nov 6, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: this is carefully engineered — I found no blocking defect in review — but it extends the reprocessing persistence model and the developer API contract enough that it needs maintainer sign-off before merge, plus the confirmations below.

What I verified on the current head:

  • backend/routers/conversations.py — app_ids is a repeated query param, mutually exclusive with app_id/source=omi, rejects duplicates/empties, capped at MAX_REPROCESS_TEMPLATE_APPS = 5, and every ID goes through _validate_reprocess_app_selection(uid, ...) so no cross-user app injection; the legacy app_id contract is untouched.
  • backend/database/conversations.py — persist_template_batch_results / persist_user_reprocess_app_results are transactional merges that refuse on deletion, is_locked, invisible rows, transcript-fence mismatch (transcript_fence_sha256), speaker-receipt mismatch, or a concurrent edit to any selected result; unselected results are merged from the transaction's snapshot so a concurrent user edit is never clobbered. Good optimistic fencing.
  • backend/utils/conversations/process_conversation.py — batch templates fan out in parallel on the llm executor and commit only if every selected template produced non-empty output (ExplicitAppSelectionFailedError → 502 otherwise), matching the all-or-nothing claim; the batch stays out of canonical notes and derived effects.
  • app side — summary_template_sheet.dart caps multi-select at maxBatchSummaryTemplates = 5 (matches the server), blocks batch while a speaker summary refresh is offered, and Retry replays the whole batch (page.dart); the l10n keys used (selectedCount, selectActionItems) already exist in the arb files.

To confirm (none verified as broken):

  1. backend/routers/developer.py — update_conversation_endpoint now returns 404 (missing/deleted), 402 (locked), 409 (restore race) where it previously returned the conversation. That is a released dev-API error-contract change; please confirm clients handle 402 here.
  2. The batch path returns early in execute_reprocess (skipping schedule_reprocessed_learning) and before complete_explicit in process_conversation — both run for single-template reprocess. If intentional (batch writes no notes), a one-line comment at each early return would help future readers.
  3. Cost: one batch request is up to 5 parallel LLM calls inside a single rate-limited request. The cap keeps this sane; worth watching llm-executor saturation once real traffic uses it.

CI note: this fork PR ran no hosted backend/Flutter suites (only a neutral Mintlify preview). The local results look thorough, but please have a maintainer run the backend unit suite and the app tests on the merge commit before merging.

USER IMPACT: users can pick up to five summary templates at once and get each result saved separately; existing single-template and retry flows behave as before.

Leaving for human maintainer review: the reprocessing persistence model (fences, terminal-failure recovery, notes-snapshot comparisons) and the dev-API error-contract change are architecture-sensitive and deserve a maintainer's eyes beyond this automated pass.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed (the batch early-return in process_conversation.py now carries the explanatory multi-template comment; restore authority for discarded conversations moved into the batch transaction itself, which is cleaner than the old post-hoc restore) · still open (hosted CI has still run nothing on this PR - the fork workflows sit at action_required and only a neutral Mintlify preview exists; the dev-API error-contract confirmation below; the early return if app_ids: in execute_reprocess still lacks its one-line comment) · newly introduced (four backend commits extend the change beyond template batching - details below).

No blocking defect found in static review of the new head, but the persistence-model surface grew again and still needs maintainer sign-off before merge.

New since my last review, all verified against the diff:

  • backend/database/conversations.py - a monotonic _user_lifecycle_revision fence now bumps on every discard/restore/user patch, so a restore-then-discard ABA cannot masquerade as the original state while a reprocess runs. The design is fail-closed (malformed revision values make every write refuse) and needs no migration (absent field reads as 0); pydantic response models keep the underscore field out of API payloads.
  • backend/routers/developer.py + lifecycle.apply_user_conversation_patch - PATCH is now one atomic patch (title+discard) instead of two separate writes. This is where the error-contract change lives: 404 for missing/deleted, 402 for locked (paid plan), 409 for lifecycle races, where the endpoint previously returned the conversation. Correct behavior, but it is a released dev-API contract change that needs maintainer confirmation.
  • backend/utils/enrichment/age_gate.py - user-requested effects are now age-gated from the request time, not the recording age. Reprocessing a months-old conversation will now run lazy enrichment (memories/goals) that previously stayed parked. Deliberate and user-initiated, but it is a real policy change for old recordings worth a conscious OK.
  • backend/utils/enrichment/outbox.py - effects rows are now staged inside the conversation transaction and woken after commit; ordering is right (stage in txn, wake post-commit).
  • backend/tests/unit/dev_api_test_support.py - the new isolation fixture removes the hardcoded ENCRYPTION_SECRET placeholders from three suites. Good hygiene, thank you.

Nit (non-blocking): persist_template_batch_results / persist_user_reprocess_app_results silently drop non-dict entries from apps_results when merging (the isinstance(row, dict) filter). Harmless defensive cleanup today, but legacy garbage rows would vanish without a trace inside a fenced write.

Security/blast radius: app selection is validated per-ID against the caller's available apps (no cross-user injection), all fences fail closed, and locked/deleted rows are refused throughout. Blast radius if wrong is one conversation's summary state, not account-level data.

USER IMPACT: users can pick up to five summary templates at once and get each result saved side by side; retry replays the whole batch; discarding or restoring mid-generation now cancels cleanly instead of risking a stale result.

What I'd still want before merge:

  1. A maintainer approve the fork workflows so the hosted backend and Flutter suites actually run on this head - none of the 424 local backend tests has executed on CI.
  2. Confirmation that dev-API clients tolerate 402/409 on PATCH /conversations/{id}.
  3. A maintainer nod for the age-gate policy change on old recordings.

Leaving for human maintainer review: the lifecycle-revision fence architecture and the developer-API error-contract change are architecture decisions beyond what this automated pass will approve.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@stmr

stmr commented Nov 7, 2026

Copy link
Copy Markdown
Author

Thanks for the review. ddcc443f documents the batch return and keeps opaque legacy result entries instead of dropping them; 67 focused backend tests passed. Maintainer input is still needed on the developer PATCH 402/409 compatibility contract and on permitting explicitly requested, age-limited enrichment for older conversations. Fork CI still needs approval; I have not run the Firestore emulator or a device build.

@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed (both open items, verified on ddcc443 — the template-batch early return in backend/routers/conversations.py now carries the comment that template-only batches skip speaker-learning and derived work; and the apps_results merge in backend/database/conversations.py now preserves opaque legacy entries instead of silently dropping them, refuses the write outright when the stored value is not a list, and a test pins the preserved entry) · still open (nothing further on the code side — what remains are maintainer decisions) · newly introduced (nothing; ddcc443 is exactly the two fixes above).

Verdict: no blocking defect; the code is where my last review asked it to be. Before merge this now needs maintainer action only:

  1. Approve the fork workflows so the hosted backend and Flutter suites actually run — none of the 424 locally-passing backend tests has executed on CI on any head of this PR.
  2. Confirm released dev-API clients tolerate 402/409 on PATCH /v1/conversations/{id} (backend/routers/developer.py now maps locked conversations to 402 and lifecycle races to 409, where the endpoint previously returned the conversation).
  3. Sign off on the age-gate change (backend/utils/enrichment/age_gate.py): explicitly reprocessing an old recording now runs lazy enrichment measured from the request, instead of staying parked on recording age.

USER IMPACT: users can pick up to five summary templates at once and get each result saved side by side; retry replays the whole batch.

Leaving for human maintainer review: the lifecycle-revision fence architecture and the developer-API error-contract change remain architecture decisions this automated pass does not approve.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

Git-on-my-level added a commit that referenced this pull request Nov 10, 2026
)

## What and why

Retire summary due indexes atomically when donor tombstones, manual
title/overview edits or already-enriched merges refuse repair. Preserve
`summary_first_pending_at`. Undo/manual-field removal and discard
restore recover owed debt in the same transaction using original
acceptance plus the row's policy deadline, without replacing a non-null
due or arming a refused/owned row. Internal debt metadata stays outside
reversible user-field receipts.

The guarded operator script clears legacy residue using the serving
refusal classifier. Unknown provenance is retained for provenance
repair; processing, local-only, BYOK and active finalization ownership
are explicitly retained even when another refusal has precedence. Both
completion metadata and output-present metadata retire copied legacy
due. No serving rate, feature flag, deadline, capacity, repair-service
or released-client schema changes.

## Merge order — required hold

Merge **after #25019 and #25032. This PR must not merge before #25032.**
Both dependency PRs were OPEN when this batch began. After #25019 lands,
rebase onto current `origin/main`, regenerate inventories and retain
both sides' tests; never resolve a shared-file conflict by taking one
side wholesale. Repeat exact inventory guards after any overlapping PR
lands. #25032 owns its upstream registry/flag-budget train conflicts;
this batch does not edit them.

## Operator run plan — cl2-deploy only

1. Deploy the merged code first, then identify the exact serving
revision. Old writer sites keep re-arming due during the sweep, so a
pre-deploy sweep or dry-run is insufficient.
2. Re-run a fresh dry-run **after deployment on that serving revision**.
Verify the deployed `summary_due_at` collection-group index and inspect
class/retained/eligible/conflict counts before any apply.
3. Run a bounded **5,000 scanned-row canary**, using an apply cursor
separate from the dry-run cursor. Production `--apply` additionally
requires `--confirm-production-project based-hardware` matching the
actual client's project. Review canary counts.
4. Run the full sweep **only on lead2's go**. Re-run the
serving-revision dry-run after any intervening code deployment; restart
without a cursor to reconsider conflicts as needed.

The sweep runs **two disjoint passes** at one cutoff instant: a numeric
`summary_due_at <= now` pass, then a Timestamp `summary_due_at <=
datetime(now, UTC)` pass. Each uses `(summary_due_at, __name__)`
pagination, classifier-only projection and batches of at most 400
writes. Every clear retains the original snapshot `update_time`
precondition, including individual retries after atomic batch failure.
Concurrent re-arm/delete is skipped. `--limit` bounds the combined
scanned rows across both passes, including retained rows. Aggregate
counts remain available, with scanned/eligible/classes/written/conflicts
also reported separately under `passes.numeric` and `passes.timestamp`.
Output is counts-only; private cursor files are written to unique
same-directory `mkstemp` files, explicitly set to mode `0600`, flushed
and fsynced before atomic replacement; any failed attempt removes its
temporary file and preserves the previous checkpoint. They include a
`pass` marker plus a numeric or tagged RFC3339 due and document path,
with no IDs printed. Cursors are separate for each pass: completing
numeric scanning checkpoints `{pass: "timestamp", due: null, __name__:
null}` before the first timestamp query. Resuming a timestamp checkpoint
skips the completed numeric pass. Older unmarked cursors infer their
pass from the due type. Keep apply/dry-run cursor files separate. This
operator-only metadata cleanup is exempt from content-generation batch
privacy admission: it never reads transcripts/generated summaries or
changes protection levels or content. No production access or operator
run was performed in this lane.

## Follow-up: private atomic checkpoints

Review-desk FIX-FIRST at `f940cf9dd489` found that the predictable
`.tmp` path could expose private cursor document paths through a
pre-existing permissive file or symlink. Checkpoint publication now uses
a unique file in the checkpoint directory, explicit `0600`, flush/fsync
before `os.replace`, and unconditional temporary-file cleanup on
failure. Atomic replacement also replaces a final-path symlink without
following its target.

- Backfill suite through omi-heavy: **101 passed / 1 existing
loopback-only skip**, 1.33s, completed approximately 2026-11-10 17:51Z.
All eight new filesystem/security cases passed. This follow-up changes
only the backfill script and its test file; no operator --apply or
production access.
- Checkpoint follow-up head: `8159c89608d86c4c67a9bfc5d077e57c7df2f48f`.
`make preflight`: **39 checks passed in 64.42s**, completed
approximately 2026-11-10 17:55Z. Full PR non-test scope: **397 changed
lines**, within the original 500-line cap. The single authorized
checkpoint follow-up push succeeded as a fast-forward, approximately
2026-11-10 17:55:43–17:57:17Z. Its normal hook passed **39 shared checks
(67.26s), typecheck with zero errors, 250 passing changed-file tests
plus 23 explicit loopback-only skips**, and pinned formatting.
Exact-head CI is being monitored with a 90-minute deadline.

## Follow-up: two-pass sweep

Review-desk FIX-FIRST at `50f47f8058fc` found that a numeric cutoff
never selects Timestamp-valued due. The backfill now queries both types
and keeps the same classifier, fences, dry-run default and counts-only
output in each pass. Checkpoints explicitly mark the active pass and
survive interruption at the pass boundary.

Read-only inspection also confirms the serving query/repair blind spot:
`database/summary_debt_queries.py:13,24` uses a numeric cutoff/cursor;
`services/summary_debt_repair.py:50` rejects nonnumeric due and its
overdue-age arithmetic assumes a number. Those files are **unchanged**,
as requested; cl2-fixnow should route that finding to #25019's owner.

- Focused selection re-run through omi-heavy, 2026-11-10 approximately
17:12Z: **2,209 passed / 23 skipped / 86 xfailed**. Adjacent **117
passed**; extra chat/tool/strict transaction selection **55 passed**.
Per-file commands, exact timestamps and results:
`focused-results-followup-m1.json` in the supplied task directory.
- Backfill tests against synthetic loopback Firestore: **94 passed**,
receipt completed 2026-11-10T17:12:06.668829+00:00. Includes actual
mixed-type inequality behavior, refused clears, owed/future retention,
shared limits, both cursor types, interruption at the pass boundary and
bounded/fenced writes. Emulator shut down normally.
- Follow-up at earlier head `f940cf9dd4898798c72e854c0dd5226554b76866`.
`make preflight`: **39 checks passed in 46.50s**, 2026-11-10
approximately 17:15–17:16Z. Full PR scope: **388 non-test changed
lines**, within the 500-line cap.
- Only the backfill script and its test file changed in this follow-up.
Serving query and repair files remain untouched. The single follow-up
fast-forward push succeeded on 2026-11-10 approximately
17:16:32–17:17:52Z. Its normal hook passed 39 shared checks (57.04s),
typecheck with zero errors, 242 passing changed-file tests plus 23
explicit loopback-only skips, and pinned formatting. CI is being
monitored on this exact head with a 90-minute deadline.


## Verification of the preceding batch

Verification is hermetic code and synthetic loopback Firestore evidence,
not deployed-runtime evidence. Commands use
`/Users/david/workspace/omi-workspace/bin/omi-heavy run --` and the
worktree's Python 3.11, with GCP credential environment scrubbed. Pytest
files run in isolated processes under the backend unit contract.

- Requested focused selection on this batch: **2,170 passed, 22 skipped
(loopback tests run separately), 86 xfailed**, 2026-11-10
16:14:30–16:15:06Z. The old ae48104 selection measured 2,087/4/86; new
guards add passing cases and the new emulator cases increase the
explicit loopback-only skips.
- Adjacent selection: **117 passed**, 16:15:06–16:15:13Z; additional
chat/tool/strict People transaction selection: **55 passed**,
16:15:13–16:15:18Z. Exact per-file commands, timestamps and logs:
`/Volumes/scratch/cl2-fixnow-move25020/focused-results-m1.json`.
- Synthetic loopback Firestore: **22 chat edit/undo tests passed** and
**31 People-generation emulator checks passed**, 2026-11-10
approximately 16:13–16:14Z. Emulator stopped. Used the installed Java 21
in the process environment only.
- `make preflight` on commit `50f47f8058fcb904bb5bd185184c1473284783cc`:
**39 checks passed in 55.79s**, 2026-11-10 approximately 16:17–16:18Z.
The full PR has **354 non-test changed lines** (342 additions / 12
deletions), below 500.
- Regenerated the lifecycle payload inventory for changed owners and all
People fingerprints (only the four already-audited chat scopes differ);
People generator check reports no delta. Exact lifecycle
inventory/state-table guard is included above; serving lifecycle write
guard passed in preflight. Normal pre-push on
`50f47f8058fcb904bb5bd185184c1473284783cc` passed all 39 shared checks,
typecheck with zero errors, 203 passing changed-file tests plus 22
explicit loopback-only skips, and pinned formatting for all 15 PR Python
files (2026-11-10 16:18:28–16:19:46Z). The single fast-forward push
succeeded with no bypass.


UI-Evidence: none — backend metadata and an operator script only.

## Finding dispositions

| Finding (review sources) | Disposition in this batch |
|---|---|
| Predictable checkpoint temp path can follow a symlink or reuse
permissive permissions (review-desk 72a878, FIX-FIRST) | Use exclusive
unique same-directory `tempfile.mkstemp`, enforce `0600` via `fchmod`,
write/flush/fsync, then `os.replace`. Cleanup runs on failure, leaving
the previous checkpoint intact. Regressions cover the old predictable
symlink/permissive file, permissive umask, write/fsync/replace/fchmod
failures, descriptor closure and safe replacement of a final-path
symlink. |
| Numeric-only cutoff misses timestamp-valued due (review-desk e7b7dc,
FIX-FIRST) | Replaced with numeric and Timestamp passes, distinct
pass-aware checkpoints and per-pass counts. Tests cover
refused/owed/future rows in both types, shared limits, resumable pass
boundary, update-time conflicts and 400-write caps. A loopback Firestore
regression verifies actual mixed-type query behavior. |
| Unknown provenance retired as durable; #25032 late projection stranded
(pd correctness/custody/tests/merge/Kimi) | Removed from
`DURABLE_REFUSALS` and durable test cases. Regression retains the legacy
due and first-pending anchor. Missing provenance still needs its owning
repair; this batch never clears it. |
| Manual undo loses owed debt (all correctness/custody/test reviews, old
merge/CI) | Chat restore and explicit null/DELETE_FIELD removals re-arm
atomically from preserved first pending plus the stored
`first_summary_policy` deadline, falling back to `deadline_seconds()`.
Refused rows and already-armed rows never acquire a replacement due.
Real codec, strict transaction and loopback emulator coverage. |
| Every other manual removal path needs coverage (sdclear-fix1) | Title
UI and offline empty titles remain non-null manual values, covered by
retirement tests. Chat tools reject blank title/overview edits before
IO. Sync restore and generated persistence preserve manual fields. All
actual removal writers are declared in the lifecycle inventory. |
| Summary BYOK reason not excluded; terminal BYOK semantics untested (pd
correctness/custody/tests) | Explicitly retain
`summary_blocked_reason=blocked_byok`, including a competing deleted
flag and no active job. Existing finalization BYOK exclusion remains. No
terminal-BYOK policy expansion. |
| Detached queued/leased finalization rows (pd correctness) | Explicitly
retain both statuses even without a job ID, including competing
manual/discard flags. Re-arm also respects these owners. |
| Output-present enriched row can retain copied due (pd custody) | Both
completion metadata and `summary_output_present=True` take the enriched
return and retire due. Empty reprocessing preserves banked structured
content without requiring a completion stamp. |
| Discarded rows recoverable after sweep (pd correctness/tests) | The
existing restore transaction re-arms only currently owed, unarmed rows
from original acceptance and policy. Tests cover cleared legacy rows
without receipts, manual/enriched/locked refusal, existing due and
writer ownership. |
| Refusal classes can later reopen (pd correctness/custody) | Manual and
discard inverses now recover debt. Empty-output revision re-arm stays
intact and is covered by the adjacent recovery suite.
Privacy/content-floor decisions remain governed by their existing
policy; this metadata cleanup does not introduce a new privacy/content
transition. `DURABLE_REFUSALS` now documents current-obligation
retirement rather than permanent lifecycle finality. |
| Backfill bypasses batch privacy fence (pd custody) | Documented
metadata-only operator exemption: no transcript or generated summary is
read or written; only the due index is cleared with a snapshot
update-time fence. Serving content-generation fences remain unchanged. |
| Non-JSON due checkpoint (pd custody) | Timestamp cursors use private
tagged RFC3339 values and decode on resume, preserving Firestore
timestamp type and nanoseconds. Numeric cursor format remains supported.
|
| No explicit prod apply guard (pd custody) | `--apply` on
`based-hardware` requires matching `--confirm-production-project
based-hardware`; an unknown project fails closed. Synthetic unit
coverage only; no operator apply was run. |
| CLI failure path / deleted cursor not tested (pd tests) | Added
counts-only CLI error regression and resume after a deleted numeric
cursor; timestamp cursor also resumes after a missing cursor document. |
| Unchanged-title path lacks assertion (pd tests nit) | Added
no-write/no-due-move assertion for an unchanged offline title. |
| Legacy exact title assertion fails CI (old CI/merge) | Already
corrected at ae48104; retained and re-run the full revision-contract
file. |
| Update-time fence, dry-run, bounded cursor, counts-only output (all
reviews) | Preserved; original race, atomic-batch, tie/resume,
scanned-row limit, batch-size and privacy tests remain intact. |
| Deploy must precede sweep (old merge, sdclear-fix1) | Run plan below
requires code serving first and a fresh post-deploy dry-run on that
exact serving revision before the 5k canary. Old writers would keep
re-arming due during a sweep. |
| Code revert cannot restore cleared rows (pd merge, old custody) |
Rollback explicitly requires a separately authorized re-stamp keyed on
preserved `summary_first_pending_at`, current owed rows only. |
| #25019 / #25032 ordering and same-file inventories (pd merge, old
merge, sdclear-fix1) | Must merge after both, never before #25032. Both
were OPEN at intake; no premature rebase. After #25019 lands, rebase and
regenerate inventories, preserving both sides and tests rather than
taking a side wholesale. |
| Upstream #25032 registry / #25034 flag-budget conflicts (pd merge) |
Dependency-owner work outside this batch. The merge train must resolve
those before #25020; no workflow/flag-budget edits here. |
| #25018 / #24866 / #24801 / #24897 / stale #24607 overlaps (old and pd
merge) | Re-fetch before integration; if these land first, rebase and
re-run exact inventories and both branches' tests. No unrelated PR
changes or merges performed here. |
| Operator query excluded from serving-query inventory (pd merge) |
Preserve script scope. Uses the existing `summary_due_at`
COLLECTION_GROUP single-field index; cl2-deploy must verify the deployed
index with the serving-revision dry-run before canary. No production
query in this lane. |
| People audit and lifecycle inventories after shared-scope changes (all
test reviews) | Regenerated reviewed entries and four existing People
fingerprints after strict transaction and loopback emulator proof;
exact-match guards re-run. |

## Rollback

A code revert **does not restore rows whose due indexes the backfill
already cleared**. Preserve the operator receipts/cursors and stop the
sweep. A separately authorized repair must enumerate/re-stamp keyed on
the preserved `summary_first_pending_at`; only rows the current
classifier calls owed, with no competing owner and a null/missing due,
may receive `summary_first_pending_at + stored first_summary_policy
deadline` (or `deadline_seconds()` without a snapshot). Never reset the
anchor, move a non-null due, or blindly re-arm refused rows. Do not use
the due index itself to find already-cleared rows.

Failure-Class: FC-obligation-outlives-terminal-owner

Line-Count-Exception: backend/database/conversations.py | 4960 -> 4969 |
Keep atomic due retirement and guarded discard-restore re-arm at their
owning writes.

Line-Count-Exception: backend/utils/sync/assignment.py | 1538 -> 1539 |
Keep atomic summary-debt retirement at the donor redirect write.
Reconcile the template batch with upstream's discarded-restore ordering (the router still registers the
recording obligation after the atomic result commit), finalization ownership, and the shared tests.
@stmr

stmr commented Nov 21, 2026

Copy link
Copy Markdown
Author

Merged current main (e8b9a70) — 11 conflicted files (app + backend). Notable reconciliations: (1) upstream's 'discarded row stays hidden until its restore registers the recording obligation' now also runs after our atomic result commit, so the router still calls lifecycle_service.restore_discarded (visibility is committed atomically with the result first, then the obligation is registered; a registration failure surfaces as the existing 503 retry). (2) Upstream's restore_conversation_from_discarded(..., return_snapshot=True)/summary re-arm is kept; restoring a locked row is allowed again as upstream's backfill contract requires (dev PATCH keeps its own lock fence). (3) Plain (non-template) user-reprocess budget denial is back to upstream's behaviour (preserved row, no error); only explicit template requests answer 402. (4) Several upstream tests needed the new app-result snapshot/commit seams stubbed.

Threads: 4 of 5 cubic threads were already addressed (replied/resolved), 1 valid (batch plumbing test) fixed. Local: backend tests for the touched/related files (~300 files via test.sh) pass except test_verify_pusher_promotion_evidence.py (needs helm, not installed locally); OpenAPI/TS/Swift generated-contract checks up to date; Flutter reprocess/summary suites 157/157 pass. Note: on the pre-merge head several upstream tests (processing_backlog, free_tier_entrypoint_matrix, free_tier_branch, duplicate_capture_policy, summary_persistence, owner_recognition) were already failing because fork CI never ran — fixed here. Maintainer action needed: approve the fork workflow runs (action_required) so the hosted lanes execute.

@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed (nothing new was asked of the code — both items from my earlier pass were fixed on ddcc443 and remain fixed here) · still open (the three maintainer decisions below, unchanged) · newly introduced (nothing blocking: the only change since ddcc443 is the merge of current main, whose reconciliation I verified at this head).

Verdict: no blocking defect on the merged head. The main-merge reconciliation across the 11 conflicted files is correct as far as static review shows; the code side looks done, and what remains before merge are maintainer decisions, not author work.

What I verified on the merged head:

  • backend/routers/conversations.py — the restore ordering survived the merge: batch result visibility commits atomically inside the result transaction first, then the router registers the recording obligation via lifecycle_service.restore_discarded; a failed restore now surfaces as 409 ("Conversation changed during reprocessing. Please retry.") instead of passing silently. The template-batch early return carries the explanatory comment (the last code-side nit from my earlier review).
  • backend/utils/conversations/process_conversation.py:2892 and :2965 — budget-denial behavior matches upstream after the merge: 402 only when the caller named an explicit template (app_id or app_ids); a plain reprocess keeps upstream's preserved-row, no-error path. Verified in the file content at the head, not just the diff.
  • backend/database/conversations.py — persist_template_batch_results now handles terminal-failure recovery inside the same transaction (a failed row is claimed to completed via claim_conversation_status_in_txn with an expected-status CAS, and a dead_letter finalization status is cleared), and patch_user_conversation bumps _user_lifecycle_revision on discard so the restore-then-discard fence keeps holding across upstream's lifecycle changes. All fences still fail closed.
  • backend/routers/developer.py + lifecycle.apply_user_conversation_patch — the dev-API PATCH is one atomic title/discard patch with 404/402/409 mapping. Behavior looks right; the error-contract question below stands.
  • app side — summary_template_sheet.dart keeps maxBatchSummaryTemplates = 5 matching the server's MAX_REPROCESS_TEMPLATE_APPS, multi-select is disabled while a speaker-summary refresh is offered, and the provider refuses a batch in that state.

Cost: unchanged from my earlier note — one batch request is up to 5 parallel LLM calls under a single rate-limited request.

USER IMPACT: users can pick up to five summary templates at once and get each result saved side by side; retry replays the whole batch.

Still needed before merge (maintainer side, unchanged):

  1. Hosted CI: only guard/resolve/Mintlify have run on this head — the backend and Flutter suites have never executed on CI for any head of this PR. The fork workflows need maintainer approval (or a maintainer-run suite on the merge commit).
  2. Confirm released dev-API clients tolerate 402/409 on PATCH /v1/conversations/{id}.
  3. Sign off the age-gate change (backend/utils/enrichment/age_gate.py): explicitly reprocessing an old recording now wakes lazy enrichment measured from the request time.

Leaving for human maintainer review: the developer-API error-contract change and the age-gate policy call are product decisions; the batch persistence fences remain architecture-sensitive.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@stmr

stmr commented Nov 26, 2026

Copy link
Copy Markdown
Author

@Git-on-my-level Merged upstream main in b3aac33e98, preserving the batch/lifecycle guards alongside upstream persistence declines and deferral handling. Local checks: 236 focused pytest tests and 80 Flutter tests passed; Dart formatting completed and analysis reported only SDK deprecation notices. Hosted CI approval, released-client 402/409 compatibility, and the old-recording age-gate policy still need maintainer sign-off.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This needs work before merge. The multi-template flow itself is coherent and well fenced, but the Developer API PATCH rewrite drops two existing behaviours, and the regenerated clients cannot send the new array parameter correctly.

Blocking

  • backend/routers/developer.py (update_conversation_endpoint, ~L2580) now restores through apply_user_conversation_patch -> database/conversations.py::patch_user_conversation (L3351) -> _user_restore_updates (L4238). The previous lifecycle_service.restore_discarded (utils/conversations/lifecycle.py L821) first registers the recording obligation for batch_live_v1 rows and refuses the restore if that registration is refused. The new path skips it, so restoring a discarded recording whose audio is not projected yet makes the row visible with no transcription debt. Please keep the registration on this path, and add a dev-API test that asserts it runs.
  • Same endpoint, title path: patch_user_conversation writes only structured.title + user_title, while update_conversation_title also clears summary_due_at. A rename through the Developer API no longer cancels a pending summary delivery.
  • Generated clients: docs/api-reference/app-client-openapi.json -> web/app/src/lib/omiApi.generated.ts (and the admin / personas / windows twins) build the query with String(v), and OmiApi.generated.swift uses String(appIds). With more than one ID those send app_ids=a,b, which FastAPI reads as the single ID "a,b" and the route rejects. Either make the generator repeat the parameter (style: form, explode: true) or leave app_ids out of the generated clients until it can.

Maintainer decisions (also raised in the description)

  • Developer API PATCH /v3/conversations/{id} now answers 402 (locked), 404 (soft-deleted) and 409 (conflict) where it used to return the conversation. That is a contract change for released clients.
  • backend/utils/enrichment/age_gate.py L49: user_requested_at lets an explicit reprocess schedule enrichment for a recording older than the age gate. Spend is bounded by the user asking for it, but it is a product call.
  • process_conversation.py: an explicit template reprocess denied by budget now raises 402 instead of falling through to the existing path.

What I verified and liked

  • routers/conversations.py L1030-1045: app_ids capped, required distinct and non-empty, mutually exclusive with app_id and source=omi, historical rows refused, all before any work.
  • process_conversation.py L3033-3125: the batch commits once via persist_template_batch_results against a transcript fence (transcript_hash.py::transcript_fence_sha256), the speaker-receipt hash and the lifecycle revision, so a discard/restore during generation cannot land stale results. persist_user_reprocess_app_results and persist_template_batch_results share most of that logic; consider factoring the fenced merge so the two do not drift.
  • persist_processing_result_with_lifecycle now carries the row's current is_locked rather than the processor snapshot's. Good hardening, but it applies to every caller; worth a line in the description. Same for set_conversation_as_discarded (L4128), which changed from a blind update to a read-modify-write and now returns silently on a missing row.
  • Flutter: summary_template_sheet.dart caps multi-select at maxBatchSummaryTemplates and installs suggested templates before running; conversation_detail_provider.dart keeps lastFailedReprocessAppIds so Retry repeats the batch. Removing the reprocessConversationId = '' reset in _finishReprocessLoading is safe; every reader also checks loadingReprocessConversation.

Performance / cost: the batch runs up to five app prompts in parallel (submit_with_context(llm_executor, ...)), so latency is about one call while token cost scales with the selection. Each user reprocess adds one transactional read plus a transcript decrypt for the snapshot and again at commit.

UX: the sheet gains a "Select Multiple" toggle and a "Summarize - N selected" button. The limit toast reuses frequencyMaximum ("Maximum - 5 selected"); a dedicated string would read better.

USER IMPACT: In a conversation's "Summarize with" sheet, users can pick up to five templates and get all of them in one go, each kept as its own switchable result; Retry re-runs the same set. Developer API users see new error codes on conversation PATCH.

Not verified: I reviewed statically and did not run the backend or Flutter suites; the checks visible on this head do not include a backend unit-test run.

Still want: the dev-API restore-registration test; a test for rename + summary_due_at; a generator-level test for repeated array query parameters.

Backend owner sign-off is needed before merge: this rewrites the conversation persistence fences and changes the Developer API PATCH contract.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@stmr

stmr commented Nov 27, 2026

Copy link
Copy Markdown
Author

Addressed the review blockers:

  • Restore registers the batch_live_v1 recording obligation before changing visibility and propagates registration refusal; Developer API regression covers both outcomes: 2829318358.
  • Developer API rename clears summary_due_at; regression covers the persisted update: 2829318358.
  • OpenAPI declares app_ids as form/explode; regenerated TypeScript and Swift clients repeat the key, with generator coverage: ac614cb0ee.
  • The template-limit toast now has a dedicated string in all 49 locales: f2848d2ec0. The description also calls out the lock-preservation and discard-write changes.

Verification: 369 backend tests, 42 Flutter tests, localization, OpenAPI compatibility/freshness, Dart/TS/Swift codegen, Swift DTO typecheck, and route policy baseline passed. Flutter analysis reported the existing Material import deprecation info.

Awaiting backend-owner sign-off (unchanged): released Developer API PATCH 402/404/409 contract, user_requested_at overriding the enrichment age gate, and 402 on budget-denied template reprocessing.

@Git-on-my-level
Git-on-my-level dismissed their stale review November 28, 2026 01:21

Dismissed as resolved on f2848d2: Developer API PATCH restore now registers the recording obligation before the metadata write (lifecycle.py::_register_restore_obligation via apply_user_conversation_patch, with dev-API tests for both outcomes); rename clears summary_due_at in patch_user_conversation; and app_ids is declared form/exploded with the TypeScript and Swift generators emitting repeated keys. Maintainer decisions listed in the follow-up comment remain open.

@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed (all three blocking items, verified on f2848d2 — restore through Developer API PATCH now registers the recording obligation before any metadata write and propagates a refused registration: backend/utils/conversations/lifecycle.py::_register_restore_obligation is called from apply_user_conversation_patch, and test_developer_patch_restore_registers_before_changing_metadata covers both the registered and the refused outcome; rename now clears summary_due_at inside patch_user_conversation, matching update_conversation_title, and still syncs the search index — pinned by test_developer_patch_rename_clears_summary_delivery; app_ids is declared style: form, explode: true in backend/scripts/export_openapi.py and both generators emit repeated keys — app_ids=a&app_ids=b in the four TypeScript clients, one URLQueryItem per element in OmiApi.generated.swift — with test_generators_repeat_exploded_query_array_values) · still open (nothing on the code side) · newly introduced (nothing blocking; the limit toast now has its own string in all 49 locales).

Verdict: the code is where my earlier review asked it to be. What remains are maintainer decisions and a CI approval, not author work.

Not verified: every hosted workflow on this head sits at action_required (fork approval) — 15 runs, including Backend Unit Tests, OpenAPI Contract and Mobile App Checks. No commit on this PR has been executed by CI. I reviewed statically and did not run the suites, so the author's local numbers are the only execution evidence so far.

Non-blocking notes

  • backend/scripts/generate_swift_openapi_types.py: the + -> %2B re-encode applies to every query parameter of a method that has an exploded array, not only the array. That is the correct encoding (it matches encodeURIComponent) and today touches only the reprocess route — just worth knowing if the pattern is reused.
  • backend/routers/developer.py: RestoredRecordingRegistrationUnavailable is still unmapped there, so a refused restore surfaces as a 500. The previous restore_discarded path behaved the same on main, so not a regression; a 503 would be friendlier next time the endpoint is touched.

Cost / performance: unchanged from my earlier review — up to five app prompts run in parallel, token spend scales with the selection, and each reprocess adds one transactional read plus a transcript decrypt at snapshot and at commit.

Blast radius: persist_processing_result_with_lifecycle carrying the row's stored is_locked and the read-modify-write set_conversation_as_discarded apply to every caller, not only the batch path. Both look like hardening; they are called out in the description.

Maintainer decisions (unchanged, also listed in the description)

  1. Developer API PATCH /v1/dev/user/conversations/{id} now answers 402 (locked), 404 (soft-deleted) and 409 (conflict) where it used to return the conversation — a contract change for released clients.
  2. backend/utils/enrichment/age_gate.py: user_requested_at lets an explicit reprocess schedule enrichment for a recording older than the age gate.
  3. An explicit template reprocess denied by budget answers 402 instead of falling through.

USER IMPACT: In a conversation's "Summarize with" sheet, users can pick up to five templates and get each result saved side by side, with Retry re-running the same set; Developer API clients see new error codes on conversation PATCH.

Still want: once the fork workflows are approved, a green run on this head for Backend Unit Tests (the new dev-API tests) and OpenAPI Contract (generated-client freshness) — the generator change has not yet been exercised by the repo's own check.

Backend owner sign-off is needed before merge: the Developer API PATCH contract change and the enrichment age-gate override are product decisions, not review defects.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

This branch has not been deployed

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

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Run multiple summary templates on the same transcript without overwriting - making conversations super useful

2 participants