Skip to content

design: D164 batched converging profile refresh and indexed neighborhood gather - #690

Merged
fazpu merged 5 commits into
mainfrom
design/bounded-profile-convergence
Nov 28, 2026
Merged

fazpu merged 5 commits into
mainfrom
design/bounded-profile-convergence

Conversation

@fazpu

@fazpu fazpu commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Why

Hosted ingestion of a 253-chunk document (302 claims) into a Project with 1,364 active entities stalled on
converging profile refresh (profile refresh + neighborhood re-clustering):

  • adjudicate_supersession was cut off at the 1,800 s Cloud Run / Cloud Tasks ceiling on all three attempts and
    dead-lettered. Run once next to the database it succeeded, but needed 893 s.
  • the version-level label_relation that follows it uses the same ConvergingProfileRefresher.refresh_for_facts
    and also exceeded 1,800 s.

Measured on the live database host (read-only, local socket):

What Cost
Distinct lemmas re-clustered 3,862, serially, one transaction each
_GATHER_NEIGHBORHOOD 83.6 ms/lemma (sequential scan on aliases; the trigram/phonetic GIN indexes are bypassed)
Neighborhood members evaluated 30,603 for 1,133 profiled entities, so each entity's locked evidence is reloaded about 27 times
_locked_profile_state per entity ~60 ms (one entity per transaction) vs 0.3 ms/entity for the existing batched _load_salient_facts_many
From Cloud Run ~100 queries/s through PgBouncer, latency-bound; the whole job cannot fit in 1,800 s

refresh_many also prepares every target before it embeds or commits any, so a cut-off attempt keeps nothing.
In this run no profile actually changed: all the time went to re-verifying current profiles.

What D164 decides (design only, no code)

  1. Chunk-committed batched refresh. Prepare, embed and commit per 64-entity chunk, with batched locks and evidence.
    A killed attempt keeps completed chunks; a retry makes no embedding calls for them. Fail-closed clearing is kept.
  2. Indexed, batched neighborhood gather and attestation. The gather runs on the existing aliases GIN indexes
    (row-set equivalence proven in the analysis). Partial salience indexes match _SELECT_SALIENT_FACTS again, added
    online. Each entity is attested once per batch instead of ~27 times, with the same lock order.
  3. No behaviour change. Same targets, ranking, profile inputs and vectors; same merge, split and review decisions
    in the same lemma order. With auto-merge on, a batch stops at the first mutation and re-gathers. Acceptance
    requires a frozen-store replay with zero diffs.
  4. Residual bound, stated. About 1,000 queries and ~20 s over a 10 ms-RTT WAN for the measured shape. Ledger
    continuation of converging refresh is a recorded follow-up with explicit triggers, not built now (YAGNI).

Files: plan/designs/bounded_profile_convergence_design.md, plan/analysis/bounded_profile_convergence_analysis.md,
the D164 entry in decisions.md, and reconciled pointers in the entity identity and registries designs and in
plan/README.md.

Process

  • Drafted by Antigravity (Gemini 4 Neon High). The coordinator rescoped it to remove a ledger-continuation chain
    (new stage handler, readiness and forget changes, five caller changes) as unneeded machinery.
  • Design review: the required GPT-6.2 sol max reviewer is unavailable until 2026-12-02 (Codex usage limit), so an
    independent Claude reviewer runs the loop now. A GPT-6.2 sol re-review is planned when available.
  • Implementation follows in a separate PR after approval.

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 2 commits November 28, 2026 21:43
…nd analysis

Bound converging profile refresh and neighborhood clustering below the 1,800 s
hosted task ceiling across any corpus size:
- chunk EntityProfileRefresher.refresh_many into 64-entity prepare->embed->commit
  cycles with batched locks and evidence loads;
- rewrite _GATHER_NEIGHBORHOOD to use existing GIN trigram/phonetic indexes on
  aliases, restore matching partial salience indexes on observations/relations,
  and batch neighborhood attestation across up to 64 lemmas / 256 entities;
- chain overflow slices through the existing unlaned PipelineStage.REFRESH_PROFILE
  stage with frozen target sets, O(1) continuation payloads, readiness tracking,
  and automatic D159 forget scrubbing.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
…n SQL proofs

Apply YAGNI revision to D164:
- Remove ledger continuation (§3: REFRESH_PROFILE handler, slice budgets,
  inline slice 0, frozen entity_ids payloads, on_complete_follow_up,
  readiness/D159 changes, caller changes, mixed-version rollout) across
  all six corpus files; callers, stages, payloads, and component versions
  stay identical to main.
- Retain §1 (64-entity chunk-committed refresh) and §2 (GIN-indexed
  batched gather, matching *_v2 salience indexes, batched attestation)
  and renumber sections cleanly.
- Add §4 Residual bound (~1,000 queries, ~8-11 s local / ~17-21 s WAN on
  the measured shape; ~360k-400k touched-lemma 0%-changed / ~120k
  100%-changed single-task ceiling at 1,800 s) with ledger continuation
  recorded as a follow-up outside D164 and its adoption trigger; keep
  the measured-shape query-count and 10 ms-RTT timing acceptance test.
- Tighten SQL proofs with verbatim quotes of _GATHER_NEIGHBORHOOD,
  p9_16_0037 salience indexes, and _SELECT_SALIENT_FACTS, covering
  float4/float8/numeric threshold equivalence, pg_trgm.similarity_threshold
  session pinning, NULL/empty/short lemmas, and the phonetic branch.

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

fazpu commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

Design review, round 1 (independent Claude reviewer; GPT-6.2 sol unavailable until 2026-12-02)

VERDICT: CHANGES_REQUESTED

The gather row-set proof (float4 cnt_sml, GIN recheck, transaction-local threshold), the salience-index diagnosis, the lock ordering and stop-at-first-mutation under auto-merge all check out against the code.

Blocking

  1. Chunked prepare → embed → commit weakens fail-closed clearing (design.md:13,25-27,109). Today attempt 1 clears every stale target before any provider call (profile_refresher.py:250-259). Under D164, a provider failure, a kill or optimistic exhaustion at chunk k leaves later chunks' stale vectors readable. _run_profile_refresh (e3.py:81-95) and reconcile.py:273 swallow ProfileRefreshContendedError, relying on stale input already having been cleared.
    Fix: batched 64-entity prepare transactions for all targets first (each commits its clears, under 1 s in total). Then embed, revalidate and commit per 64-text batch as today, with byte-identical batches and call_key. On a lock timeout, keep preparing the remaining chunks and raise afterwards. Fix the :109 test, and add a test that optimistic exhaustion leaves every stale target cleared.
  2. FOR SHARE SKIP LOCKED (auto-merge off) is a new deferral (design.md:57,72,79). Today the proposal-only pass waits on the entity row lock (_SELECT_ENTITY_FOR_UPDATE). The resolver's _BUMP_MENTION_COUNT (resolver.py:1574-1576) row-locks entities without :obs:, so SKIP LOCKED would defer lemmas with no later nomination guaranteed.
    Fix: a waiting ORDER BY entity_id FOR UPDATE in both modes; defer only on a failed :obs: try-lock. Add a test.

Non-blocking

  1. Lemma order and normalisation. Keep the SQL collation row order and re-normalise each row (normalized_lemma is not idempotent, e.g. İ). Return exactly one NeighborhoodReport per input lemma. Add a non-ASCII test.
  2. Lock keys. Pass exact Python-built {dep}:obs:{member} key strings as a pre-sorted text[], not uuid[].
  3. Lock-wait budget. A 15 s statement timeout now covers a whole chunk's lock waits. Either accept this explicitly or use per-lock lock_timeout with the same SQLSTATE translation.
  4. Scope framing (CLAUDE.md Rule 2). Drop the reader-less legacy indexes in the same migration (DROP INDEX CONCURRENTLY) or plan the drop in plan/plans/. Move ledger continuation to plan/proposals/ with its trigger, and state the linear bound as a non-goal. Cite D153's resumable concurrent-index procedure.
  5. Frozen replay must exercise real paths. Name the input and recorded vectors keyed by input_hash, and require at least one embed batch, one merge or split, one queued review and one deferral.
  6. Drop the extra 64-chunking of _load_salient_facts_many. Use one call over deduplicated U_ok.
  7. Rollback scope. An exception at lemma j now rolls back the review-queue writes of lemmas 1..j-1. Retries plus uuid5 review IDs converge, so state this as acceptable.

- Preserve fail-closed clearing in refresh_many by preparing all pending
  targets in 64-entity batched transactions before any provider call
  (continuing remaining chunks on lock timeout before raising), then
  embedding, revalidating, and committing per dense 64-text batch with
  byte-identical batches and call_key; update mid-embed and add
  optimistic-exhaustion and lock-timeout tests.
- Replace FOR SHARE SKIP LOCKED in auto_merge_enabled=False with waiting
  ORDER BY entity_id FOR UPDATE on surviving U_ok entities so concurrent
  _BUMP_MENTION_COUNT row locks do not introduce new deferrals; defer only
  on failed :obs: try-locks and add a test.
- Preserve _SELECT_ENTITY_LEMMAS SQL collation order, re-normalise each
  row via normalized_lemma, return one NeighborhoodReport per input slot,
  and add a non-ASCII test.
- Pass exact Python-built pre-sorted text[] lock keys ({dep}:obs:{member}
  and {dep}:cluster:{lemma}) to batched advisory lock statements.
- Explicitly accept the chunk-wide 15 s statement_timeout on
  _LOCK_KEYS_BATCH with D99/D157 57014 translation.
- Cite D153's resumable concurrent-index procedure for the hash-partitioned
  observations/relations *_v2 salience indexes, drop the three reader-less
  p9_16_0037 legacy indexes in the same migration after *_v2 validation
  (D160/D161), state the linear single-task bound as an explicit non-goal,
  and move ledger continuation to plan/proposals/.
- Tighten the frozen replay acceptance gate to name the Full-v45 conv-26
  store + CI fixture, key recorded vectors by input_hash, and require >= 1
  embed batch, >= 1 merge or split, >= 1 queued review, and >= 1 deferral.
- Drop extra 64-chunking of _load_salient_facts_many in clustering (one
  call over deduplicated U_ok) and document/accept batch review-queue
  rollback scope on exceptions (retries + uuid5 review IDs converge).

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

fazpu commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

Design review, round 2 (independent Claude reviewer)

VERDICT: CHANGES_REQUESTED. Eight of the nine round-1 findings are resolved (fail-closed prepare-all, waiting FOR UPDATE, lemma order and reports, text[] keys, lock budget, frozen replay gate, single facts call, rollback scope).

  1. Blocking: relations and observations are plain tables, not partitioned. In p0_02_0004:171-205 and :290-318, PARTITION BY HASH at :238 and :343 belongs to *_evidence. Production reports relkind = 'r', and storage_inventory/p9_46_0067-…json:1400 shows a plain index. A non-concurrent DROP INDEX would take ACCESS EXCLUSIVE on both tables.
    Fix:
    • Build with plain CREATE INDEX CONCURRENTLY in autocommit_block(), keeping the --sql refusal and D161's lock_timeout with bounded 55P03 retry.
    • Make the build resumable: drop and rebuild an invalid own-named index, verify the definition of an existing one, and refuse a name collision.
    • Then drop the legacy indexes with DROP INDEX CONCURRENTLY IF EXISTS.
    • Remove the partitioned wording everywhere.
    • Acceptance: assert relkind = 'r', that an interrupted build resumes, and that no ACCESS EXCLUSIVE lock is taken.
  2. Non-blocking: batched commit edge cases. Rows already current at commit are skipped and reported updated=False. The UPDATE must return the IDs it wrote and raise on a mismatch, as _commit_if_current does at profile_refresher.py:196-224.
  3. Non-blocking: stale numbers in plan/proposals/ledger_continued_profile_convergence.md:8. Sync them with design.md:98,103.

fazpu and others added 2 commits November 28, 2026 22:18
- Correct observations and relations migration from partitioned to plain
  tables (pg_class.relkind='r'; p0_02_0004:171-205,290-318, verified in
  p9_46_0067 storage inventory): build the three *_v2 salience indexes
  via plain CREATE INDEX CONCURRENTLY inside autocommit_block() with
  --sql refusal, D161 lock_timeout + bounded 55P03 retry, exact
  definition verification, invalid own-named rebuild via DROP INDEX
  CONCURRENTLY, and foreign name-collision refusal; drop legacy
  p9_16_0037 indexes via DROP INDEX CONCURRENTLY IF EXISTS (zero ACCESS
  EXCLUSIVE locks); remove partitioned wording across all corpus docs
  and add relkind='r', resume, and no-ACCESS-EXCLUSIVE acceptance checks.
- Specify _commit_batch_if_current edge cases matching _commit_if_current
  (profile_refresher.py:196-224): skip rows already current at commit
  with updated=False, return written IDs via UPDATE ... RETURNING
  entity_id and raise RuntimeError on any mismatch, use RETURNING
  entity_id on _CLEAR_PROFILE_MANY for exact updated reporting, and add
  acceptance checks.
- Sync modelled WAN time (~17-20 s, ~90-105x) and 0%-changed single-task
  lemma ceiling (~375,000-420,000) in
  plan/proposals/ledger_continued_profile_convergence.md with design.md.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
…ted transactions

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

Design review, round 3 (independent Claude reviewer): APPROVE

All round-2 findings are resolved:

  • Migration: plain tables (relkind = 'r'). It is resumable CREATE INDEX CONCURRENTLY in autocommit_block(), then DROP INDEX CONCURRENTLY IF EXISTS, matching the plain-table pattern at p9_47_0068:61-168. It takes only SHARE UPDATE EXCLUSIVE, so it is online-safe under D160/D161.
  • Batched commit: rows already current are reported updated=False, and RETURNING ID checks raise on mismatch, matching profile_refresher.py:196-224.
  • Proposal: its numbers now match the design.

The one non-blocking nit is fixed in 91b307f. The online-migration test now uses short, individually committed reads and writes instead of a long-held ACCESS SHARE holder, which concurrent DDL would correctly wait on.

GPT-6.2 sol max re-review is planned once the Codex usage limit resets (2026-12-02). The implementation PR follows this design.

@fazpu
fazpu merged commit 32a47c6 into main Nov 28, 2026
16 checks passed
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