Skip to content

fix(memory): normalize required intake inline and recover through Dream - #23710

Merged
Git-on-my-level merged 16 commits into
mainfrom
lane/memreq
Oct 26, 2026
Merged

Git-on-my-level merged 16 commits into
mainfrom
lane/memreq

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Required memory submissions stayed pending because their only production caller was an undeployed maintenance job. This change normalizes required intake immediately after canonical capture commits and makes the existing Dream sweep retry stragglers. It does not deploy a job, scheduler or IAM change.

Inline capture gets one Flex attempt with a 12-second batch budget. Async callers await provider IO after the DB worker returns; raw synchronous DB-pool submissions defer to Dream. Returned single/batch memory views and prompt caches reflect successful normalization. Existing revision leases, receipts, backoff and raw-submission idempotency remain authoritative. Scheduled retries are independent of Dream cleanup gates, with rotating owner and per-owner row cursors. The sweep also completes receipts through the existing canonical consolidation/graph route without another model call. Account deletion fences precede provider calls; rejection, dismissal and locks are checked again in the completion transaction.

Historical submissions before 2026-10-26 07:55Z stay hidden until Dream's separate retrospective ramp resolves them. Its planner and two verifiers compare fully read canonical records. Uniqueness requires exhaustive coverage within 100 raw rows and the read-byte budget; top-k or paginated search cannot establish it. Larger/inaccessible corpora may resolve a proven positive duplicate while uncertain unique submissions stay pending. Lead ruling 91e4aa accepts this guard and requires coverage-tail/budget measurement in David-first, with the larger-corpus decision by October 27. Unique items use the shared processor; duplicates preserve a superseded source audit row and leave the durable Long-term survivor intact. A covering Short-term neighbor or split vote stays pending. Canonical-head, source-revision and switch fences reject stale/in-flight disabled results.

Dream uses a private planner/tool model for the new capability and its bounded 101-ref inventory. The released Review model remains unchanged with its ten-ref limit. Server authority selects the private schema, and the Review-offer boundary rejects private capabilities. User authority cannot resolve hidden intake candidates. Generated public OpenAPI/client artifacts match main.

Automatically conversation-derived required items in the SPEAKER_EVIDENCE_MODE serving cohort require confident owner-bound quotes before paid normalization or backlog search. Explicit text retains separate authority. This uses the shared provenance rule from #23669, which must ship in the same or earlier release. Original transcripts/audio and pending records are retained.

Lead owns merge, deploy and ramp. MEMORY_REQUIRED_INTAKE_ENABLED defaults on (false rolls back inline/retry). DREAM_REQUIRED_INTAKE_BACKLOG_ENABLED defaults off and requires an explicit cohort: David first, then 5%, 25%, 100% by 2026-10-28. Historical dedupe also needs normal Dream admission, eligibility and capacity; the lead must align those gates for the intended cohort. Before each expansion, hold a full scheduled lookback with zero known duplicate admissions, lost details or source/privacy/owner fence violations, declining pending age/counts and measured spend within forecast. Disable the backlog switch to contain new historical effects; preserve committed receipts.

Normalization forecast: 470/day × $0.000245 ≈ $0.115/day; 20,681 all-unique backlog items ≈ $5.07. Dream search/planning/verification and Firestore reads are additional metered costs. Recorded to Plans & Cost/margin50 and card:memreq-required-intake-20261026. No production account content was read or changed by this lane.

Required normalization re-admits inside the actual LLM worker after its queue wait, and transactionally rechecks account deletion and memory tombstone/disposition before writing a processed result. Six regressions cover account deletion and memory tombstones while queued (zero provider calls), in flight (discard the result), and immediately before the real transaction. A deterministic deadline test covers the final metadata wait. Provider SDKs, parsers and audio helpers load at use so importing the shared hook on a canonical read does not pull in model stacks; the public Flex exception identity remains unchanged.

Validation: 303 targeted backend/test.sh cases (intake, real Session dispatch, released/private schema isolation, API response/cache, privacy races, cursors, executor cancellation/bulkheads, compatibility Flex routing, consolidation queries and delete/re-add identity), 1,039 Firestore/Dream guard and regression cases (one harness deselection), 2,046 exact CI slow-guardrail cases, full-tree Pyright, additional existing Session/isolation suites, and the released app-client compatibility gate. Fake metadata/delete tests defer the external normalizer while retaining real admission, lease, deletion and evidence paths; no timing allowances or weaker admission were added. Luna privacy/deadline and final import/fixture reviews returned SHIP. Lead ruling9caa64 waives another review for the final two test-only fixture changes; production code is unchanged from reviewed e6549e5. Final-head terminal CI follows before lead handoff. Normal hooks run without skips, through omi-heavy and nice -n 19. The lead must verify serving release identity and metadata-only runtime receipts after deployment.

Luna's nonblocking P2: a lazy SDK import fault outside model setup handling can consume quality retries. Supported deployment dependencies are locked; lead ruling2bf926 keeps that fix in a small follow-up PR from main after this merge, with one Luna round. The validated patch is preserved and owned by memreq on card:memreq-required-intake-20261026.

Why this is a shared primitive: all required captures use the canonical post-commit hook, shared normalization receipts and source fences; the existing Dream scheduler owns retries. No per-surface repair or parallel memory writer is introduced.

Product invariants: INV-MEM-1, INV-MEM-2, INV-MEM-3, INV-MEM-4, INV-MEM-5, INV-DATA-1, INV-INT-1. New intake remains Short-term; no direct Long-term/graph promotion or legacy mutation authority is added.

Failure-Class: FC-pending-queue-without-dispatch-owner

UI-Evidence: none -- backend lifecycle, internal Dream schemas and runbooks; no rendered UI changes.

Line-Count-Exception: backend/database/memory_apply_store.py | 2865 -> 2869 | Four lines invoke shared Dream lease and required-source transaction fences at the existing canonical write boundary.
Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 3953 -> 3970 | The existing canonical commit boundary must invoke the extracted intake module and recognize its current normalization receipt for raw-submission idempotency.
Line-Count-Exception: backend/utils/memory/memory_service.py | 4698 -> 4708 | The existing write boundaries register post-normalization API view/cache refreshes; hidden candidate scope stays with the owner-search instance. Intake orchestration and backlog implementation live in separate modules.

Use one bounded Flex attempt after capture commits, shared revision receipts,
and Dream's existing schedule for independent straggler retries. Keep historical
intake hidden until retrospective neighbor checks and independent verification
resolve it, with source/head fences and a separate David-first ramp.

Failure-Class: FC-pending-queue-without-dispatch-owner
…sion

Retain canonical consolidation as the durable completion owner in Dream's
scheduled required-intake phase. Check writer mode, account generation,
sensitivity and owner-bound sources before paid work, and require a durable
survivor before retiring a redundant historical copy.

Failure-Class: FC-pending-queue-without-dispatch-owner
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T13:35:53.636355Z aff20d7 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d4bd0fcb4f

ℹ️ 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 ExecutorSaturatedError as error:
raise required.RequiredProcessingDeferred('required_intake_executor_busy') from error
try:
return future.result(timeout=remaining)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move inline normalization orchestration out of DB workers

For /v3/memories creates, routers/memories.py runs MemoryService.create_external_memory on db_executor, and the new post-commit hook reaches this blocking wait from that same worker. Each slow Flex attempt therefore occupies a shared DB worker for up to 12 seconds while also waiting for llm_executor; concurrent creates can exhaust the DB pool and delay unrelated Firestore/Redis operations. Coordinate the model wait asynchronously, borrowing DB workers only for the begin/settle steps, as the new async retry processor already does. This also violates the backend guide's explicit worker-leaf and async-orchestration requirements.

AGENTS.md reference: backend/AGENTS.md:L285-L286

Useful? React with 👍 / 👎.

Comment on lines +254 to +255
def _apply(uid, edit, records, change, key, row, *, expected_records=None, authority='dream'):
del change, expected_records

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Journal historical resolutions before reporting them applied

When Dream resolves a historical duplicate, this handler discards the ReviewChange supplied by apply_edit and directly supersedes the canonical item without recording a review_changes entry or reversible receipt. Unlike the existing memory-hygiene handlers, it consequently reports applied while the owner receives no applied-change entry or Undo action. Retaining the source as superseded history does not provide the existing Review Undo path. Journal the resolution and its reversal information atomically with the canonical mutation.

Useful? React with 👍 / 👎.

Comment on lines +145 to +147
limit=required.MAX_REQUIRED_PROCESSING_QUERY_SCAN,
captured_after=policy.BACKLOG_CUTOFF,
captured_before=current - timedelta(minutes=policy.RETRY_MIN_AGE_MINUTES),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Rotate the pending-item page within each retry owner

If an owner accumulates 100 fresh pending items that cannot pass source admission—for example, conversation-derived submissions without confident owner quotes—every sweep reads those same oldest 100 rows and skips them at revisions is None. There is no per-owner item cursor, so later valid submissions whose inline attempts failed are never reached, even though the owner inventory keeps rotating. Persist a per-owner item cursor or otherwise advance through the pending pages so withheld rows cannot permanently block unrelated required intake.

Useful? React with 👍 / 👎.

Comment on lines +169 to +171
if not page.get('complete') or page.get('unavailable_refs'):
complete = False
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Exclude intentionally hidden candidates from search-failure checks

For an owner whose pending historical candidate appears in the lexical search's history scan, the candidate itself prevents recovery: OwnerSearch.search enumerates canonical memory IDs, its ordinary hydration hides pending-processing rows, and it adds those IDs to unavailable_refs (utils/agent_capabilities/search.py:235–238). This condition then rejects the entire candidate before the self-reference exclusion below can run. An owner with only a few memories and one historical submission therefore never seeds that submission, regardless of successful semantic search or enabled rollout gates. Distinguish intentionally hidden pending rows, including the candidate itself, from failed neighbor hydration rather than treating every unavailable history reference as incomplete dedupe evidence.

Useful? React with 👍 / 👎.

Preserve both independently added feature-flag row sets and regenerate their catalog.
Block deleted accounts before provider calls, preserve owner rejection and locks
at receipt completion, and require bounded exhaustive canonical coverage for
historical uniqueness. Rotate retry and completion pages without skipping rows.
Await inline post-commit work after the DB worker returns, preserving returned
memory views and cache invalidation. Refresh generated capability contracts.
Keep corrupt sources from pinning bounded scans, enforce both intake switches
inside canonical apply, and document the conservative uniqueness coverage tail.
Move the new flag rows away from the shared prepend hotspot.
Preserve both independently added feature-flag row sets and regenerate their catalog.
Preserve the released Review response and ten-ref contract. Select the private
intake planner schema by server authority, revalidate it through staging, and
reject private capabilities at the Review offer boundary.
Re-admit required normalization in the LLM worker after queueing, and
recheck account deletion and source tombstones in the result transaction.
Cover queued, in-flight and transaction-boundary deletion for accounts
and individual memories. Use a compliant real-clock timeout in the
late-result regression.
A slow final metadata read must not start a provider call after the
capture budget expires. Check the deadline after that read and cover
the boundary with a deterministic clock.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 977b1a4611

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +500 to +501
and not promotion.get('is_locked')
and not promotion.get('is_dismissed')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Advance scan cursors past filtered pending rows

If the oldest 100 matching pending rows are locked or dismissed, these new predicates remove the entire page inside list_pending_required_processing_items, before either caller can advance its cursor. Both retry_owner and historical prepare derive their next cursor only from returned items, so every sweep rereads the same excluded rows and later eligible submissions remain pending indefinitely. Preserve the last scanned raw position separately from the eligible results, or advance through filtered pages within the scan budget; the new rotation tests mock the query helper and therefore do not exercise this case.

Useful? React with 👍 / 👎.

Load provider SDKs and parsers at model use, and audio helpers only at
audio admission. Keep the public Flex exception identity unchanged.
Use a real apply-control fixture for receipted intake cursor tests and
patch provider/audio dependencies at their actual import boundaries.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e6549e5c3c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +349 to +351
processor=partial(
bounded_normalize, deadline=time.monotonic() + policy.INLINE_TIMEOUT_SECONDS, db_client=client
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move historical normalization waits out of DB workers

When Dream admits a unique historical submission (edit.other is empty), dream_agent.run_session.effect invokes this handler through run_blocking(db_executor, ...). This synchronous processor then calls bounded_normalize, which submits to llm_executor and blocks on future.result() for up to 12 seconds. Concurrent backlog passes can therefore occupy the shared DB pool while waiting for model capacity, delaying unrelated Firestore and Redis operations. Unlike the previously flagged inline capture path, which now releases its worker, this historical-resolution path still performs the cross-pool blocking wait. Coordinate its claim, model invocation and settlement asynchronously, as the retry processor already does; backend/AGENTS.md explicitly requires worker-leaf operations and async orchestration.

AGENTS.md reference: backend/AGENTS.md:L285-L286

Useful? React with 👍 / 👎.

Comment on lines +259 to +261
proposed = {**additions, **neighbors, ref: row}
if _bytes({**records, **proposed}) > min(24000, limits.read_bytes // 2):
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Budget the full verifier payload before admitting candidates

When the supplied inventory approaches the byte ceiling, this check admits candidates that cannot reach verification: it measures only the records, whereas dream_verify.evidence() also includes the operation, its verbatim before text and the repeated evidence references. dream_verify.batches() silently excludes any complete payload exceeding 24,000 bytes. Exercising those helpers with eight ordinary memory-shaped neighbors and a 1,900-character submission produced 22,172 bytes of accepted records but 24,224 bytes of verifier evidence, yielding no verification batch. Because historical resolutions cannot proceed without agreement or fall back to Review, such submissions remain pending on subsequent passes. Budget the complete verification envelope, including operation and reference overhead, before marking an inventory usable.

Useful? React with 👍 / 👎.

Defer external normalization in provenance and delete/re-add unit
fixtures. Keep real canonical admission, retry leases, deletion and
evidence identity assertions while avoiding provider SDK cold starts
in metadata-only tests. Retain the one-second CPU guard unchanged.
@Git-on-my-level
Git-on-my-level merged commit 61deb06 into main Oct 26, 2026
59 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/memreq branch October 26, 2026 13:43
Git-on-my-level added a commit that referenced this pull request Oct 26, 2026
…retry (#23728)

## Summary

Luna r4's nonblocking P2 on #23710: the lazy provider-SDK imports in
`normalize()` sit outside the model setup `try`, so an `ImportError`
escapes
as a raw exception and the shared processor books it as a quality
failure,
spending a retry attempt even though no model call ever ran.

This moves both imports (`utils.llm.clients`, `utils.llm.usage_tracker`)
inside the existing setup `try`, so import faults raise
`RequiredProcessingDeferred('required_intake_model_unavailable')` — the
same
transport/setup classification as every other model-unavailability fault
—
and the lease is released with `attempt_count` unchanged. The supported
image
locks these dependencies, so this is defense-in-depth for degraded
images.

Per lead ruling 2bf926 this lands as a small follow-up from main after
#23710 (merged 61deb06); the identical patch was validated by the
memreq
lane (60 intake tests, 11 clock-ratchet tests, full-tree Pyright) and is
applied here unchanged on top of current main.

## Test evidence

- New parametrized regression
`test_model_dependency_import_failure_defers_without_quality_retry`:
a synthetic `ImportError` for either dependency must defer
retryable-but-unprocessed,
  keep the capture `pending`, and leave exactly one retry receipt with
`attempt_count == 0` and no lease owner (transport deferral, not a
quality retry).
- Local backend unit shard via `backend/test.sh` with

`BACKEND_UNIT_TEST_FILE_LIST=tests/unit/test_required_memory_intake.py`:
  60 passed (58 existing + 2 new), omi-heavy + nice -n 19.

## Product invariants affected

- INV-MEM-4 — unchanged. Import faults now defer through the existing
  RequiredProcessingDeferred transport path; the item keeps its single
  consolidation route and no promotion/admission authority changes.
- INV-MEM-1 — unchanged. No tier, collection, or access-surface change;
  the capture stays pending Short-term exactly as before.

Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Oct 26, 2026
Keeps #23710's inline required-memory intake wiring intact: the
captured_after/captured_before/cursor pagination params on
list_pending_required_processing_items, list_receipted_required_processing_items,
Dream completion/retry ownership in canonical_consolidation, the inline-intake
registry/env rows, and the runbook/AGENTS ownership pointers.

Keeps #23705's retirement intact: memory-maintenance-job manifest blocks and
workflows stay deleted, MEMORY_MAINTENANCE_CAPTURED_AFTER (helper, env rows,
call sites) and MEMORY_CANONICAL_MAINTENANCE_ENABLED stay retired, validator
guards from bbe6795 unchanged, feature-flag registry re-rendered without the
job surface. No behavioral code beyond deleting the retired window call sites;
targeted shard green (841 passed).
kriegcloud pushed a commit to kriegcloud/omi that referenced this pull request Oct 26, 2026
…retry

The lazy provider-SDK imports in normalize() sat outside the model setup
try introduced with BasedHardware#23710's cold-import fix, so an ImportError escaped
as a raw exception and the shared processor booked it as a quality
failure, spending a retry attempt. Move both imports inside the setup
try so import faults raise RequiredProcessingDeferred
('required_intake_model_unavailable') and release the lease with
attempt_count unchanged, like every other transport/setup fault.

Regression: synthetic ImportError for either dependency must defer
retryable-but-unprocessed, keep the capture pending, and leave exactly
one zero-attempt retry receipt with no lease owner.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant