Skip to content

feat(profile): D164 batched converging profile refresh and indexed neighborhood gather - #692

Merged
fazpu merged 8 commits into
mainfrom
feat/d164-batched-profile-convergence
Nov 29, 2026
Merged

fazpu merged 8 commits into
mainfrom
feat/d164-batched-profile-convergence

Conversation

@fazpu

@fazpu fazpu commented Nov 28, 2026

Copy link
Copy Markdown
Member

Implements the accepted D164 design (#690,
plan/designs/bounded_profile_convergence_design.md).

Why

Converging profile refresh (profile refresh + neighborhood re-clustering) ran as one unbounded,
latency-bound task. On remember.dev a 302-claim document made adjudicate_supersession and label_relation exceed the
1,800 s Cloud Run / Cloud Tasks ceiling on every attempt (893 s even next to the database). The root causes are
the per-entity evidence loads (each entity re-attested about 27 times), a gather query that bypassed the aliases GIN
indexes, salience indexes that no longer match their query, and a prepare-all pass that kept no progress
when cut off. Evidence and cost model: plan/analysis/bounded_profile_convergence_analysis.md.

What changes

  1. EntityProfileRefresher.refresh_many. A batched prepare-all pass: 64-entity transactions, with fail-closed clears
    committed before any provider call. Then embed, revalidate and commit per 64-text batch, with byte-identical requests
    and call_keys. Rows already current at commit are skipped, and RETURNING ID checks guard the writes.
  2. EntityClusterer. A transaction-local trigram threshold and a GIN-indexed gather with a proven-equivalent row
    set. Attestation is batched (up to 64 lemmas / 256 entities) with the same lock order and the same lemma slot order
    from SQL. Rows are locked with waiting FOR UPDATE; deferral happens only on a failed :obs: try-lock. With
    auto-merge on, a batch stops at the first mutation. HAC arithmetic is unchanged (fee0d0e keeps the exact
    pre-D164 summation).
  3. Migration p9_61_0082. Online and resumable CREATE INDEX CONCURRENTLY of three *_v2 salience indexes on the
    plain relations and observations tables, then DROP INDEX CONCURRENTLY of the reader-less p9_16_0037 indexes.

No stage, payload, component version, prompt, model or identity key changes, so nothing is re-extracted or re-embedded.

Tests

  • The pre-D164 implementation is kept only as a test oracle (src/tests/spine/d164_pre_oracle.py).
  • test_d164_convergence_pg.py:
    • gather row-set equivalence around similarity 0.3, including a non-default session threshold;
    • refresher and clusterer equivalence: non-ASCII lemma, deferral, mid-batch merge, fail-closed behaviour on provider
      failure and on optimistic exhaustion;
    • the measured-shape query-count and timing test.
  • test_d164_migrations_pg.py: relkind, resumable build, no AccessExclusiveLock.
  • test_d164_batch_unit.py.
  • Local results (Antigravity run): unit pack 4,013 passed, 11 skipped. The PostgreSQL 18 integration suites for D164,
    profile refresher, clustering, migrations, storage capture and workers passed. ruff and pyright are clean, and the
    storage-capture fixture and llms check pass.
  • Frozen-store replay (design §6.4) via scripts/replay_d164_retained_store.py on retained LoCoMo stores: running now;
    results will be posted here before merge.

Process

  • Implemented by Antigravity (Gemini 4 Neon High).
  • Reviewed by an independent Claude reviewer, because GPT-6.2 sol is unavailable until 2026-12-02; a GPT-6.2 sol
    re-review is planned then. Review rounds are posted as comments.

Contributor agreement

Signing on behalf of a legal entity (leave blank if accepting individually):

🤖 Generated with Claude Code

https://claude.ai/code/session_01VYytLf2PUQ2RVpEZYENzsq

fazpu and others added 6 commits November 28, 2026 23:14
Replace per-entity transactions in EntityProfileRefresher.refresh_many with
64-entity prepare transactions committing fail-closed clears before any
embedding call, followed by per-64-text-batch embed and batched revalidation
commits with byte-identical EmbeddingRequest batches and call_keys.

Add attest_profile_entities_batch for batched clustering attestation with
pre-sorted text[] advisory locks and waiting ORDER BY entity_id FOR UPDATE.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
… §2)

Rewrite neighborhood gather to UNION the two GIN-indexable branches
(normalized_lemma % lemma AND similarity >= 0.3 with transaction-local
pg_trgm.similarity_threshold='0.3', plus daitch_mokotoff overlap) over
existing aliases indexes.

Batch EntityClusterer.recluster_entities over up to 64 SQL-collation-ordered
slots / 256 entities per transaction with per-slot normalized_lemma, 1-to-1
NeighborhoodReport parity, pre-sorted text[] advisory locks, waiting entity
row locks, :obs:-only try-lock deferral in proposal mode, immediate commit
and base refresh on auto-merge mutation, and math.sumprod HAC norms.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
Build ix_observations_profile_salience_v2,
ix_relations_profile_subject_salience_v2, and
ix_relations_profile_object_salience_v2 online via resumable plain-table
CREATE INDEX CONCURRENTLY inside autocommit_block(), verify all three, and
drop the reader-less p9_16_0037 indexes via DROP INDEX CONCURRENTLY IF EXISTS
with zero ACCESS EXCLUSIVE locks.

Update catalog_contract, storage-capture head pins, and regenerate
live_corpus_profile.json.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
Add test-only pre-D164 reference oracle, unit tests, online migration
resumability/lock tests, gather equivalence tests, batched profile/clusterer
equivalence and failure-mode proofs, deterministic convergence replay,
measured-shape EXPLAIN/query-budget/WAN-timing verification, and the
scripts/replay_d164_retained_store.py script for private LoCoMo replay.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
math.sumprod accumulates with extended precision, so HAC distances could
differ from main in the last bits and flip a cut or tie decision. Keep
the cached per-cluster norm (same value, same arithmetic) and restore the
original summation for dot products and norms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VYytLf2PUQ2RVpEZYENzsq
@fazpu

fazpu commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

Implementation review, round 1 (independent Claude reviewer; head 76f76d7)

VERDICT: CHANGES_REQUESTED.

Verified correct: refresher prepare-all, contention, 57014 translation, byte-identical batches and call_keys, skip of
already-current rows and the RETURNING checks; lock keys and order; proposal and auto-merge clusterer semantics; slot order
and normalisation; the threshold pin; the migration; the storage-capture and inventory edits. The HAC arithmetic reads as
bit-identical after fee0d0e.

Blocking

  1. The measured-shape test misses the time bound. At test_d164_convergence_pg.py:2009, local_0_s was 25.26 s against
    the ≤ 20 s bound (Integration (workers)). The SQL budget held, so the time is likely pure-Python HAC: each of the 76
    lemmas in the 76-member cluster recomputes about 2,850 pairwise cosines. Profile it. If HAC dominates, cache singleton
    pair cosines per batch, keyed by entity-id pair (bit-identical), and prove that against the pre-D164 oracle. Do not loosen
    the bound without a design PR.
  2. The old implementation is still in production code, with no production callers: recluster_neighborhood, _gather,
    _GATHER_NEIGHBORHOOD (also edited), _TRY_LOCK_NEIGHBORHOOD, current_profile_entity_ids and _TRY_LOCK_ENTITY.
    The oracle imports them and the new _hac_pieces from production.
    Fix: copy the origin/main versions, including _hac_pieces, _cosine and _GATHER_NEIGHBORHOOD, into
    d164_pre_oracle.py and delete them from production. Port the test_clustering.py and
    test_clustering_lock_policy.py calls to recluster_entities. Add a randomised old-vs-new _hac_pieces test covering
    None vectors, ties, exclusions and a blob above blob_cap.
  3. The replay script's :obs: deferral check is vacuous (scripts/replay_d164_retained_store.py:487-489, :233-268,
    :466-471). Pick the target only from lemmas of nominated entities, and count real deferrals.

Non-blocking

  1. Compare full NeighborhoodReports, including black_hole_tightened and merge pairs (:1348, :1676).
  2. Add an exact float4 0.3 similarity pair to the gather boundary test.
  3. Keep merge_events.evidence and pre_merge_membership_snapshot in the snapshots, normalising UUIDs and timestamps.
  4. Label the 100%-changed WAN figure as computed.
  5. State in the migration docstring that downgrade does not recreate the legacy indexes.
  6. Add a unit test pinning recluster_entities' auto-merge lock order.

- Cache singleton vector norms and pairwise cosines per batch transaction in
  EntityClusterer.recluster_entities / _hac_pieces (bit-identical floats,
  cutting measured-shape 0%-changed local time from 21.74 s to 4.50 s).
- Delete unused pre-D164 symbols from production (recluster_neighborhood,
  _gather, _GATHER_NEIGHBORHOOD, _TRY_LOCK_NEIGHBORHOOD,
  current_profile_entity_ids, _TRY_LOCK_ENTITY), copy verbatim origin/main
  (32a47c6) versions including _hac_pieces and _cosine into
  d164_pre_oracle.py, port test_clustering.py and
  test_clustering_lock_policy.py to recluster_entities /
  attest_profile_entities_batch, and add a randomised old-vs-new HAC test.
- Fix replay_d164_retained_store.py to select its :obs: deferral target only
  from lemmas of nominated entities and count real deferrals.
- Compare full NeighborhoodReports (including black_hole_tightened and
  (survivor_id, absorbed_id) merge pairs), keep merge_events.evidence and
  pre_merge_membership_snapshot with normalised UUIDs/timestamps, add an
  exact float4 0.3 similarity pair to the gather boundary test, label the
  100%-changed WAN figure as computed, document downgrade index behaviour in
  p9_61_0082 (with regenerated live_corpus_profile.json), and add a unit test
  pinning recluster_entities' auto-merge lock order.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
@fazpu

fazpu commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

Implementation review, round 2 (independent Claude reviewer; head 44dd361): APPROVE

The code is approved. Merge gate: the design §6.4 frozen-store replay must report zero diffs; results will be posted here.

  • CI on 44dd361: all checks pass. Integration (workers): 1,391 passed, including the measured-shape timing test at its
    unchanged ≤ 20 s bound.
  • Cosine cache: a per-transaction cache of singleton-pair cosines and norms, keyed by sorted entity-id pair. Its values
    are bit-identical to pre-D164: the same expression over the same vectors, with the summation order unchanged. The cache
    never outlives a mutation, because auto-merge breaks the batch at the first one. 40 seeded trials compare doubles by their
    bytes, covering None and zero vectors, ties, exclusions and the blob_cap path.
  • Oracle: it matches origin/main 32a47c6 for _cosine, _centroid, _hac_pieces, exclusions,
    current_profile_entity_ids, _GATHER_NEIGHBORHOOD and refresh_many. recluster_neighborhood differs only in form;
    its side effects are identical.
  • Dead code: the pre-D164 paths are gone from production.
  • Ported tests: they still test the same behaviour.
  • Replay script: the deferral count is real, it compares full reports, and merge_events evidence and snapshots are
    compared.
  • Other findings: the exact 0.3 boundary pair, the computed-WAN label, the downgrade docstring and the lock-order unit
    test are all resolved.

Non-blocking:

  • _ISO_TIMESTAMP_RE masks every ISO-like string inside JSON blobs. Narrow it to keys generated at write time.
  • Confirm that the non-merge_cluster review kinds whose review_id is masked are not deterministic.

…cally

Create and clean up rememberstack_query_<clone_db> and rememberstack_graph_<clone_db> roles in _cloned_database so alembic upgrade head (p9_58_0079) succeeds against unmigrated retained stores, and sort merge_events by semantic columns rather than wall-clock decided_at.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
@fazpu

fazpu commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Frozen-store replay (design §6.4): 0 diffs on every store

scripts/replay_d164_retained_store.py compared pre-D164 (origin/main 32a47c6) with D164 on private clones. It used recorded
vectors keyed by input_hash (zero live provider calls) and local PostgreSQL 18.6 constrained to 2 CPUs and 4 GB. Compared:
entities (status, merged_into, profile fields, embedding), aliases, merge_events (evidence and snapshots; UUIDs and
timestamps normalised), review_queue and every NeighborhoodReport.

Store Exercised Diffs auto-merge off: old → new auto-merge on: old → new
conv-26 (D163 backup 20261116T100310Z-0b4f30ec) embed, 2 merges or splits, 10 and 9 reviews, 2 deferrals 0 4.0 s / 3,992 q → 1.1 s / 135 q 4.4 s / 4,098 q → 1.7 s / 204 q
conv-30 (20261116T102334Z-1a84d1f6), cut 0.35 and 0.6* embed, a merge and reviews at 0.6, deferral 0 0.6 s / 759 q → 0.11 s / 27 q 0.9 s / 1,028 q → 0.11 s / 26 q
conv-47 (20261116T095856Z-4a85b56c) embed, 6 merges or splits, 2 reviews, a deferral 0 5.0 s / 5,022 q → 0.8 s / 86 q 5.9 s / 5,770 q → 1.5 s / 214 q
Hosted-shaped brain store (read-only dump, deleted after) 1,364 entities; 1,686 merges or splits; 1,047 and 311 reviews; deferral 0 465 s / 284,406 q → 86 s / 11,250 q 490 s / 350,506 q → 215 s / 47,299 q

* conv-30 has no non-excluded pair within the default 0.35 cut, so it was also replayed at 0.6 to exercise merges and reviews.

The production job that failed on remember.dev was converging refresh for the 399 relations of the 302-claim document,
on the brain store with 2 CPUs. It took 258 s and 178,056 queries before D164 and 21.4 s and 369 queries with it,
with 0 diffs.

Harness fixes found during the run are in 97e21c8 (script only):

  • the clone now creates and drops the per-database query and graph roles, so alembic upgrade head works on older stores;
  • merge_events snapshots are now ordered by content rather than by decided_at. A first brain run reported a
    merge_events mismatch caused only by row order: counts matched and every other table matched. It re-ran with 0 diffs.

Observed: a store restored without statistics (empty pg_statistic) plans the batched gather without the GIN indexes. Production
databases are analysed. The UMC runtime records the 2026-11-27 ANALYZE that this Project needed.

@fazpu
fazpu merged commit 1f633c8 into main Nov 29, 2026
16 checks passed
fazpu added a commit that referenced this pull request Nov 29, 2026
)

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
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