Repository navigation
fix(dream): bound GET /v1/dream/runs reads with the list read budget (SCA-4309) - #26284
Conversation
Codex Review Summary: ✅ CompletedThis 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: 8d0a2f9dfc
ℹ️ 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".
| # Unbudgeted callers (Review, direct reads) keep the released call shape, so | ||
| # the seam stays compatible with their fakes; a budget is forwarded only | ||
| # when the Dream path supplies one. | ||
| budget_kwargs: dict[str, Any] = {'budget': budget} if budget is not None else {} |
There was a problem hiding this comment.
Keep nested target lookups inside the read budget
For task, person, and missing/inactive-memory targets, forwarding the budget to the document getters does not bound the entire hydration path: get_task_workflow_control() still performs an unbudgeted .get(), users.get_person() can enter _ledger_transaction() through its learning projection, and _read_memory_record() can invoke the unbudgeted MemoryService.fetch(). These nested RPCs retain their default timeouts/retries, so a stall can still hold db_executor beyond the deadline and reach the middleware 504. The task-control lookup even starts with an already-exhausted budget when the run stream supplies a partial prefix. Propagate the budget through these nested operations or use bounded label-only readers; the new operation-bound test stubs read_record() and therefore misses these calls.
Useful? React with 👍 / 👎.
| except ListReadBudgetExhausted as exc: | ||
| if budget is None: | ||
| raise | ||
| return getattr(exc, partial_attr, fallback) |
There was a problem hiding this comment.
Emit shared fallback telemetry when truncating a report
When a report-stage read exhausts its budget, this new fallback continues with placeholder state/counts or a partial list without calling record_fallback. Although finish_list_budget() records LIST_READ_* metrics, it does not emit the shared omi_fallback_total event. backend/AGENTS.md explicitly requires new fallbacks to use utils.observability.fallback.record_fallback; emit a bounded outcome='degraded' event once per truncated request so this degraded-success path participates in the shared fallback monitoring.
AGENTS.md reference: backend/AGENTS.md:L326-L326
Useful? React with 👍 / 👎.
| runs = await run_blocking(db_executor, dream_report.list_runs, uid, limit, budget=budget) | ||
| finish_list_budget(response, budget) | ||
| return runs |
There was a problem hiding this comment.
Honor truncation in the Dream report consumer
When the owner-state read exhausts the budget, this now returns HTTP 200 with runs=[] and manual_runs_today=0. The shared Dart API layer preserves the header as ApiSuccess.truncated (app/lib/backend/http/api_result.dart:132-134), but DreamReportPage._refresh() ignores it and overwrites _report on every success (app/lib/pages/review/dream_report_page.dart:51-55). Consequently, a stalled refresh replaces existing history with the normal empty report and displays the full manual-run allowance instead of a partial/retry state. Update that consumer to honor truncation as part of changing read failures into successful reports.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ca659cf980
ℹ️ 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".
| # metadata projection. Verify the blob before the tolerant product | ||
| # decoder can silently replace corrupt/wrong-key speech with []. | ||
| raw = read_product_conversation(conversations.get_conversation_raw_snapshot, uid, key) | ||
| raw = read_product_conversation(conversations.get_conversation_raw_snapshot, uid, key, **budget_kwargs) |
There was a problem hiding this comment.
Pass the budget through conversation correction projection
For a run editing a conversation with has_transcript_corrections=True and no inline overlay, only the raw snapshot receives the budget: the subsequent prepare_conversation_for_read(raw, uid) call omits read_budget, so transcripts.load_entries() performs budgeted_document_get(..., None). This is an additional conversation-overlay path beyond the previously reported task/person/memory lookups. That RPC retains Firestore's default timeout/retries, so a stalled overlay can still outlive the list deadline, hold the db_executor worker, and reach the 90-second middleware 504 instead of returning a truncated report. Forward the same budget into the conversation projection, or use a bounded label-only reader.
Useful? React with 👍 / 👎.
…emory read (SCA-4309)
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b2b84da473
ℹ️ 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".
| # route's wire contract does not change. | ||
| budget = list_read_budget_for_request(request, route='GET /v1/dream/runs') | ||
| try: | ||
| await run_blocking(db_executor, dream_report.require_owner, uid, budget=budget) |
There was a problem hiding this comment.
Include the global kill-switch refresh in the read budget
With Dream reporting enabled, an expired ten-second kill-switch cache makes this call run mode() -> enabled() -> dream_control.allowed() -> refresh() synchronously on db_executor. That refresh still calls .get(timeout=0.5) in backend/config/dream_control.py:16 without the request budget or a no-retry policy. Retryable Firestore failures can therefore keep the worker occupied beyond the internal deadline and reach the middleware 504 before the budgeted owner-document read even starts. Thread the budget through the switch refresh with retries disabled, or avoid a synchronous refresh on this request path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 672c7d533e
ℹ️ 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".
| # metadata projection. Verify the blob before the tolerant product | ||
| # decoder can silently replace corrupt/wrong-key speech with []. | ||
| raw = read_product_conversation(conversations.get_conversation_raw_snapshot, uid, key) | ||
| raw = read_product_conversation(conversations.get_conversation_raw_snapshot, uid, key, **budget_kwargs) |
There was a problem hiding this comment.
Budget recurring-voice privacy reads during conversation hydration
For a conversation target whose decoded segments contain a recurring_voice_id, hydration still enters prepare_conversation_for_read() → recurring_voice_privacy.filter_segments() → recurring_voices.suggestable_ids(). That path starts a transaction and reads the owner and profile documents without the request timeout or no-retry policy (backend/database/recurring_voices.py:73-78,219-244). This occurs even with has_transcript_corrections=False, so forwarding the budget to the correction overlay alone will not cover it. A stalled privacy read can therefore still hold db_executor beyond the internal deadline and reach the middleware 504. Thread the budget through these transactional reads or use a bounded label-only conversation reader.
Useful? React with 👍 / 👎.
| rows = _bounded( | ||
| budget, lambda: dream_store.own_runs(uid, limit=limit, budget=budget), [], partial_attr='partial_runs' | ||
| ) |
There was a problem hiding this comment.
Stop later report stages once the read budget is exhausted
When a read exhausts the document allowance before the wall-clock deadline—for example, with OMI_LIST_READ_MAX_DOCUMENTS=1, the owner-state read exhausts it after the eligibility read—_bounded() catches the exhaustion, but the report still invokes own_runs() and subsequently dirty_count(). The request factory leaves strict_documents=False, and ListReadBudget.rpc_timeout() does not check an existing exhaustion flag in that mode, so both RPCs actually start after the budget is marked truncated. This exceeds the configured aggregate read allowance and permits another Firestore failure after truncation was already determined. Check the budget before starting later stages, or make rpc_timeout() reject an already-exhausted budget.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8299c7d285
ℹ️ 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".
| # metadata projection. Verify the blob before the tolerant product | ||
| # decoder can silently replace corrupt/wrong-key speech with []. | ||
| raw = read_product_conversation(conversations.get_conversation_raw_snapshot, uid, key) | ||
| raw = read_product_conversation(conversations.get_conversation_raw_snapshot, uid, key, **budget_kwargs) |
There was a problem hiding this comment.
Budget lake-backed transcript resolution during hydration
For a lake-backed conversation target with a cold pointer memo, the budgeted snapshot read is followed by strict transcript verification, which enters transcript_pointer.preload_pointer() → object_lake.get_space_object(). That path still performs a plain Firestore .get() in backend/utils/other/space_keys.py:173-176 and an unbudgeted download_as_bytes() in backend/utils/other/object_lake.py:695-706. A stalled key/KMS/blob read can therefore keep db_executor occupied beyond the list deadline and the 60-second pool-hold limit in backend/AGENTS.md, reaching the middleware cutoff instead of returning a truncated report. Propagate the budget through pointer resolution, including exception translation, or use a label-only reader that avoids transcript hydration.
AGENTS.md reference: backend/AGENTS.md:L279-L279
Useful? React with 👍 / 👎.
|
|
||
|
|
||
| def refresh(*, budget=None): | ||
| from utils.other.list_budget import ListReadBudgetExhausted |
There was a problem hiding this comment.
Keep the new budget imports at module scope
The new imports in load_flag() and refresh() are function-local, but backend/AGENTS.md explicitly requires “All imports at module top level — never inside functions.” Move both budget symbols into the module import section to preserve the documented import convention; lazy client construction does not require these helper imports to be deferred.
AGENTS.md reference: backend/AGENTS.md:L168-L168
Useful? React with 👍 / 👎.
| user = budgeted_document_get(user_ref, budget).to_dict() or {} | ||
| if not eligible(uid, user): |
There was a problem hiding this comment.
Include eligibility cohort discovery in the request budget
With DREAM_AGENT_ELIGIBILITY=paid and a cold or expired member-discovery cache, eligible(uid, user) calls allowlist_uids() and ultimately read_cohort_members(), whose query streams up to 500 documents with its own one-second timeout (backend/database/rollout_cohorts.py:56-66). That query neither checks nor charges the request budget: even OMI_LIST_READ_MAX_DOCUMENTS=1 permits it after this owner lookup consumes the last allowed document, and a nearly spent deadline still permits the full discovery read. Include the eligibility lookup in the shared budget, or use a bounded owner-membership check rather than expanding the entire cohort. A dependency-free probe of the production eligibility/cache functions confirmed the extra stream starts with zero documents remaining.
Useful? React with 👍 / 👎.
) #26284 gave eight test_dream_report tests 0.25-0.3 s real-clock list read budgets; test_real_clock_budget_ratchet rejects anything under 0.5 s, so Backend Unit Tests is red on main. Raise them to 0.5 s and lengthen the stub stalls to 0.7 s so every test keeps its truncation behaviour. Co-authored-by: Claude Opus 5.5 <[email protected]>
What changed and why
GET /v1/dream/runsnow builds one request-scopedListReadBudgetand threads it through every Firestore read on the path — the eligibility gate doc read, the owner state doc, the run stream, each deduped edit-target read (including the task-control generation read for action-item/candidate targets and workstream resolution), the canonical-memory item and its pre-canonical fallback frontier (deletion receipt, historical override, historical row), and the dirty count aggregation. Each RPC runs at the budget's per-RPC timeout withretry=FIRESTORE_NO_RETRY, so one stalled op ends the list at the internal deadline and returns HTTP 200 with the runs already projected plusX-Omi-List-Truncated, instead of holding to the 90 s middleware cutoff and answering a bodyless 504 and leaking adb_executorworker (SCA-4307 measurement, SCA-4308 source diagnosis, this issue SCA-4309).The untruncated response is byte-identical: without a budget every read keeps its released unbounded shape, and the budget is built only by this GET handler.
project_runstill runs ondb_executorand never fans out (backendAGENTS.mdrule 1); the response schema, thelimitbounds (1-20), the edit cap, and the POST/run_passpath are unchanged. The budget stays tunable throughOMI_LIST_READ_BUDGET_SECONDS/resolve_list_read_budget_seconds().The global switch and owner eligibility gate precede listing, so a stalled gate is a budget trip with nothing projected: it answers the same truncated 200 with
X-Omi-List-Truncatedand an empty run list, matching the issue's "any budget trip" contract. The feature/mode checks run before that read, so a disabled route still answers 404 rather than an empty 200.The canonical memory read is reused: one
include_inactive=Truedocument read decides both the item and whether the pre-canonical fallback is admitted, andMemoryService.fetch(canonical_absent=True)skips its own repeat of that read, so a miss no longer reads the same document two or three times before the receipt/override/historical frontier.Product invariants affected
Reached only through read-path plumbing in
utils/agent_capabilities/reads.pyand the store helpers it dispatches to (get_person,get_action_item,get_candidate,get_knowledge_node,read_canonical_memory_item,get_conversation_raw_snapshot,get_task_workflow_control,MemoryService.fetch). Each helper gained an optional keyword-onlybudget; tier policy, canonical promotion, visibility predicates, the fail-closed canonical/override/tombstone frontier, candidate lifecycle, and every write path are untouched. The one deliberate behavior change is fewer reads: an observed canonical absence now suppresses the fallback's duplicate read instead of re-reading the same document, with the same 404/None outcome.Follow-up from exact-head review
The cold global switch uses the GET budget and the response renders without refreshing that switch. Person labels use the owner-scoped visible identity without reconciling its voice-learning ledger. Conversation hydration shares the budget with recurring-voice authority, transcript corrections, and cold title time-zone reads. The GET uses strict document accounting and can return a fully projected prefix when the allowance runs out. Coverage exercises each path and the existing recurring-voice revocation cases.
How it was verified
backend/.venv/bin/python -m pytest backend/tests/unit/test_dream_report.py— 17 passed, including the contract tests: a fake Firestore whosestream()/get()blocks returns 200 withX-Omi-List-Truncatedinside a 0.3 s budget (assertingretry is FIRESTORE_NO_RETRYand a derived timeout on the stream), a counting fake asserting the documented op bound (one gate document, one state document, onelimit-row stream, one count, one read per unique edit target per run) with no target read, stream, or count started after the deadline, a stalled gate that answers the truncated 200 with no later read, a disabled route that still answers 404, and a memory target that reads the canonical document exactly once.test_firestore_query_shapes.py,test_firestore_index_oracle.py,test_firestore_outside_query_contract.py,test_firestore_caller_witnesses.py,test_database_entities_resilience.py,test_bounded_firestore_list_reads.py,test_dream_harness_runtime.py,test_dream_guards.py— 1007 passed;test_review_stale_answers.py,test_dream_search_budget.py,test_dream_memory_merge.py,test_memory_read_api.py,test_mcp_memory_adapter.py,test_developer_memory_adapter.py— 124 passed.bash backend/scripts/typecheck.sh— 0 errors.backend/.venv/bin/python scripts/scan_async_blockers.py --dirs routers utils— 0 selected blocking findings.backend/.venv/bin/python scripts/scan_async_blockers.py --dirs routers utils— 0 selected blocking findings.bash scripts/test-backend-python-format.shand the pinned black check on the 15 changed files — clean.TestClientwith the repository'sDreamFirestoreharness. Serving-level verification (zero 90 s GET 504s over two health ticks, budget trip returns 200 +X-Omi-List-Truncated) is Release's post-deploy step on this issue.Tests
backend/tests/unit/test_dream_report.py::test_stalled_run_stream_returns_the_runs_it_has_with_the_truncation_header— the regression test for the incident: a blocked run stream ends inside the budget with 200, the row already fetched, and the header, well under the 90 s cutoff.::test_spent_budget_stops_the_sequence_before_any_later_read— a stalled state read stops the sequence; no later stream, target read, or count starts.::test_stalled_eligibility_gate_answers_a_truncated_200— the gate's budget trip is the contract's truncated 200, not a 504 or 503, and starts no later read.::test_disabled_route_still_answers_404_before_any_read— truncation never converts a disabled route into an empty 200.::test_memory_target_reads_the_canonical_document_once— a canonical miss readsmemory_items/<id>exactly once (then receipt, override, historical row), asserting the real underlying read count rather than the mocked seam.::test_report_reads_each_edit_target_once_per_run— the documented per-request op bound.::test_get_runs_reports_the_owner_history_without_a_truncation_header— the untruncated response shape and no false header.backend/tests/support/dream_firestore.pyandfirestore_dream_query_drivers.py— the fake accepts and records the budget RPC options; the query-shape driver recordsbudgetas an RPC-only neutral.UI evidence
UI-Evidence: none — backend read path only.
Failure class (fixes)
Failure-Class: FC-bounded-read-exceeds-request-budget
Scoped cleanups (optional)
None. The ratchet exceptions below are one optional keyword-only
budgetparameter (and its one-line docs) per existing helper, split across lines by the pinned formatter — no new logic in those files.Line-Count-Exception: backend/database/action_items.py | 2224 -> 2227 | one optional keyword-only budget parameter (split across three signature lines by the pinned formatter) plus its one-line Args entry for the Dream read path
Line-Count-Exception: backend/database/conversations.py | 5671 -> 5681 | optional keyword-only budget parameter and its docstring paragraph on the existing raw conversation snapshot reader
Line-Count-Exception: backend/database/users.py | 3109 -> 3112 | optional keyword-only budget parameter and its docstring sentence on the existing person reader
Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 4221 -> 4232 | optional keyword-only budget parameter threaded through the existing canonical memory item reader and its docstring
Line-Count-Exception: backend/database/memories.py | 2010 -> 2012 | optional keyword-only budget parameter on the existing historical memory document reader
Line-Count-Exception: backend/utils/memory/memory_service.py | 4841 -> 4871 | skip-duplicate-read flag on the existing fetch/canonical-status readers and the budgeted receipt/override frontier