Skip to content

feat(embeddings): unify embedding freshness into one monotonic key - #3067

Merged
Sinity merged 3 commits into
masterfrom
feature/gpt-pro/misc02-embedding
Jul 18, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/gpt-pro/misc02-embedding

Conversation

@Sinity

@Sinity Sinity commented Jul 18, 2026 •

Copy link
Copy Markdown
Owner

Summary

Replaces four divergent embedding-freshness selectors (per-source convergence, daemon bulk backlog, manual embed backfill, and preflight) with one shared exact-key predicate driven by a new storage-neutral DerivationKey value shape, and makes success/error/resolution writes conditionally scoped to the exact generation/key they were issued for — closing the terminal-write race that could clobber a newer config-change mark with an older attempt's outcome.

Problem

polylogue-hash-boundary census (polylogue-9e5.6) found that only one of four production embedding-selection call sites compared message_embeddings_meta.content_hash against current message content; the other three (_drain_archive_embedding_backlog_once, _run_archive_backfill, _select_archive_pending_window) passed include_stale_checks=False and trusted a needs_reindex flag alone. Separately, mark_session_embedding_error unconditionally cleared needs_reindex on a non-retryable terminal error, which could clobber a concurrent config-change bulk-mark that landed mid-flight (the same race class already fixed for the success path in polylogue-y337, but left open on the error path — polylogue-iqd3). polylogue-0k6's same-ID/same-count changed-text staleness gap is the content-generation instance of the same underlying defect: selection and terminal writes did not consume one monotonic freshness generation.

Solution

  • New polylogue/storage/derivation_identity.py: a storage-neutral DerivationKey/DerivationIdentity/DerivationSubject value/protocol type (subject + exact source identity + computational recipe identity + output contract, SHA-256 digested with domain separators). Deliberately excludes attempt generation, producer/resource data, eligibility/privacy, retryability, and result hashes — those remain domain-owned. No universal derivation table or lifecycle was added.
  • New polylogue/storage/embeddings/identity.py: maps embeddings onto that shape. EmbeddingRecipe declares all twelve computational fields from polylogue-303r.7 (canonicalization, record selector, chunking version, provider, model, model revision, dimensions, task, input type, normalization, tool implementation, input/schema version); changing any one produces a different recipe_hash.
  • _archive_embedding_freshness_predicate() in materialization.py is now the sole v3 freshness classification (fresh / blocked / pending), consumed identically by all four production call sites:
    • polylogue/daemon/convergence_stages.py::_archive_pending_embedding_session_ids (also fixes config reconciliation, which previously ran against index.db even though embedding state lives in the sibling embeddings.db — now _reconcile_archive_embedding_config_change targets the correct file)
    • polylogue/daemon/embedding_backlog.py::_drain_archive_embedding_backlog_once
    • polylogue/cli/commands/embed.py::_run_archive_backfill
    • polylogue/storage/embeddings/preflight.py::_select_archive_pending_window
      The include_stale_checks bypass parameter is removed entirely (zero production references remain).
  • polylogue/storage/sqlite/archive_tiers/embedding_write.py: complete_embedding_attempt_success and record_embedding_failure/mark_session_embedding_error now validate and commit inside one transaction guarded by WHERE session_id = ? AND generation = ? AND derivation_key = ? AND attempt_state = 'pending'; a stale attempt's write touches zero rows and is recorded only as superseded evidence. resolve_embedding_failure applies the same generation/key scoping so a late acknowledgement of an old failure cannot clear a newer pending mark.
  • EMBEDDINGS_SCHEMA_VERSION 2 -> 3 in the canonical DDL (embedding_derivation_state, extended message_embeddings_meta/embedding_failures, new index). No migration chain — per repo doctrine embeddings.db is a rebuildable-but-expensive tier; the change edits canonical DDL directly, and docs/schema.md is updated to document it.

Verification

  • devtools test tests/unit/storage/test_embedding_freshness_invariant.py tests/unit/storage/test_embedding_contracts.py tests/unit/storage/test_embedding_orphan_reconcile.py tests/unit/cli/test_embed_status_fast.py tests/unit/daemon/test_embedding_convergence_progress.py -> 119 passed.
  • Anti-vacuity (both reverted after confirming, no residual diff):
    • Removed task from EmbeddingRecipe.identity()'s field mapping -> the 12-field parametrized mutation test failed exactly [task-changed-task], all 11 others stayed green.
    • Removed the generation/derivation_key WHERE guard from record_embedding_failure's conditional UPDATE -> test_config_change_then_old_terminal_error_cannot_clear_new_generation failed (assert 'failed_terminal' == 'pending'), proving the guard is load-bearing against the exact race polylogue-iqd3/wmsc target.
  • devtools verify --quick -> clean (ruff format, ruff check, mypy --strict, render-all-check, layering, degrade-loudly, manifests, ci-workflows, doc-commands, docs-coverage, test-infra-currency, test-clock-hygiene, pytest-timeout-overrides all ok, exit_code: 0).
  • Fixed real defects found by the above gates before this could be considered mergeable (see below).
  • devtools render topology-projection && devtools render topology-status regenerated for the two new files (polylogue/storage/derivation_identity.py, polylogue/storage/embeddings/identity.py); devtools render all --check passes clean (no "out of sync").
  • Broader regression sweep across ~22 embedding/daemon/CLI-adjacent test files: 636 passed, 1 pre-existing unrelated failure (test_web_reader.py::...redact_configured_archive_paths, an sqlite3.OperationalError: unable to open database file reproduced identically on unpatched origin/master).

Defects found and fixed during independent verification (not present in the original external patch)

  • mypy --strict found 13 errors across 5 files, including one real bug: _archive_embedding_session_state_exact_with_timeout returned a 2-tuple (0, 0) on a missing-table OperationalError from a function typed (and unpacked at its call site into three variables) as tuple[int, int, int] | None -- a guaranteed ValueError: not enough values to unpack at runtime on that path. Fixed to (0, 0, 0). The remaining errors were narrow stub-typing gaps (sqlite3's _AggregateProtocol.step stub only models single-int-arg aggregates; several object/bytes narrowing sites) and test-only typing, fixed with narrow casts/ignores or proper isinstance narrowing.
  • ruff format needed 4 files reformatted.
  • devtools verify layering failed: the new public writer entrypoints begin_embedding_attempt, supersede_embedding_attempt, complete_embedding_attempt_success were added to embedding_write.py without updating its declared entrypoint list in docs/plans/layering.yaml. Fixed.
  • devtools verify degrade-loudly failed: the new _qualified_table_columns helper repeats the existing narrow-schema-probe except sqlite3.Error pattern of its sibling _table_columns/_qualified_table_exists (both already allowlisted) but had no allowlist entry of its own. Added one with the same rationale.

Migration notes

BREAKING CHANGE (schema, operator-actionable, not automatic): EMBEDDINGS_SCHEMA_VERSION moves from 2 to 3. Per repo doctrine, embeddings.db is a rebuildable-but-expensive derived tier with no migration chain -- this is a canonical-DDL edit, not an in-place ALTER/migration script (git diff origin/master -- polylogue/storage/sqlite/migrations/ is empty).

Verified this is not a silent auto-rebuild hazard: initialize_archive_database (polylogue/storage/sqlite/archive_tiers/bootstrap.py, unchanged by this PR) raises RuntimeError("... schema version 2 is not the current embeddings tier version 3; move it aside and rebuild the archive root") for an existing v2 file, because ArchiveTier.EMBEDDINGS is not in DURABLE_MIGRATION_TIERS. The daemon's periodic embedding-backlog check catches this as a logged warning and retries every 60s rather than deleting/reinitializing anything -- an operator must explicitly move embeddings.db/-wal/-shm aside before the tier is rebuilt via fresh initialization or polylogue ops embed backfill.

Before deploying: back up (or explicitly discard, if acceptable) the existing embeddings.db set, move it aside, then let fresh initialization or polylogue ops embed backfill --yes rebuild v3. Rebuilding re-embeds the full corpus and costs real Voyage API spend -- do not do this casually on the live archive without confirming budget.

Ref polylogue-wmsc. Absorbs/validates supersession of polylogue-iqd3 and polylogue-0k6 (both already closed as superseded by wmsc).

Update: follow-up commit after a fuller background regression sweep

A full devtools verify --seed-testmon --skip-slow (~16k non-slow tests, ~913s) surfaced two genuine ripple-effect regressions from the EMBEDDINGS_SCHEMA_VERSION 2->3 bump that weren't in the original test-file list, both now fixed in a follow-up commit:

  • tests/unit/cli/test_embed_activation.py::_seed_embeddings_meta hand-rolled a 6-column message_embeddings_meta table + positional 6-value INSERT; once the workspace fixture initializes embeddings.db to the real v3 (9-column) schema first, the CREATE TABLE IF NOT EXISTS becomes a no-op and the positional insert fails (table message_embeddings_meta has 9 columns but 6 values were supplied). Fixed to a named-column insert.
  • tests/unit/devtools/test_archive_schema_fast_forward.py::test_embedding_clone_preserves_vectors_and_installs_failure_lifecycle hardcoded the pre-bump expected clone user_version (2) instead of importing EMBEDDINGS_SCHEMA_VERSION. The production fast-forward helper already targets the constant dynamically -- only the test literal was stale.

The same full-suite run also surfaced a long tail of failures in files this PR does not touch (query execution control, MCP tool contracts/declarations, rendering, insights, ChatGPT-normalization parsers, CLI diagnostics, etc.). I classified these before ignoring them, not just dismissed them:

  • Several (test_index_fast_forward_lifecycle.py, test_index_v37_fast_forward.py, test_plain_cli_snapshots.py::test_json_status_snapshot) share one root cause: a stale hardcoded expectation against INDEX_SCHEMA_VERSION (currently 39 in source on both this branch and origin/master, confirmed via grep/git show), unrelated to EMBEDDINGS_SCHEMA_VERSION and pre-existing on origin/master independent of this diff.
  • Several (test_facade_contracts.py, test_tool_usage.py) are sqlite3.OperationalError: database source_debt is locked / unable to open database file in files this PR's diff never touches (confirmed via git diff origin/master --stat) -- reproduced identically with this PR's commit fully stashed back to HEAD, i.e. independent of these changes; environmental (shared-box contention / stale temp state from a different concurrent run), not a product regression.
  • test_web_reader.py::...redact_configured_archive_paths was already confirmed pre-existing on unpatched origin/master earlier in this review.

None of these are addressed here -- fixing them is unrelated cleanup outside this PR's scope (stale INDEX_SCHEMA_VERSION snapshots and shared-box sqlite contention, not embedding freshness).

Updated verification: devtools test tests/unit/storage/test_embedding_freshness_invariant.py tests/unit/storage/test_embedding_contracts.py tests/unit/storage/test_embedding_orphan_reconcile.py tests/unit/cli/test_embed_status_fast.py tests/unit/daemon/test_embedding_convergence_progress.py tests/unit/cli/test_embed_activation.py tests/unit/devtools/test_archive_schema_fast_forward.py -> 179 passed. devtools verify --quick stays green after the follow-up commit.

@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 53 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: cb9358a3-417a-4fa6-89ca-d868dd574e9b

📥 Commits

Reviewing files that changed from the base of the PR and between 46e478f and 7185b8d.

📒 Files selected for processing (25)
  • devtools/build_topology_projection.py
  • docs/plans/degrade-loudly-allowlist.yaml
  • docs/plans/layering.yaml
  • docs/plans/topology-target.yaml
  • docs/schema.md
  • docs/topology-status.md
  • polylogue/cli/commands/embed.py
  • polylogue/daemon/convergence_stages.py
  • polylogue/daemon/embedding_backlog.py
  • polylogue/demo/seed.py
  • polylogue/storage/derivation_identity.py
  • polylogue/storage/embeddings/identity.py
  • polylogue/storage/embeddings/materialization.py
  • polylogue/storage/embeddings/preflight.py
  • polylogue/storage/embeddings/status_payload.py
  • polylogue/storage/sqlite/archive_tiers/embedding_write.py
  • polylogue/storage/sqlite/archive_tiers/embeddings.py
  • tests/unit/cli/test_embed_activation.py
  • tests/unit/cli/test_embed_status_fast.py
  • tests/unit/daemon/test_embedding_convergence_progress.py
  • tests/unit/demo/test_demo_seed_verify.py
  • tests/unit/devtools/test_archive_schema_fast_forward.py
  • tests/unit/storage/test_embedding_contracts.py
  • tests/unit/storage/test_embedding_freshness_invariant.py
  • tests/unit/storage/test_embedding_orphan_reconcile.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/gpt-pro/misc02-embedding

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@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: 4e8f5e5319

ℹ️ 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 thread polylogue/daemon/convergence_stages.py Resolved
Sinity added a commit that referenced this pull request Jul 18, 2026
Problem: CodeRabbit flagged a P1 on PR #3067 at convergence_stages.py:882 --
_reconcile_embedding_config_change() unconditionally set needs_reindex=1 on
every embedding_status row whenever recipe_changed was true, instead of only
the sessions whose embedding_derivation_state generation actually advanced
this pass. For an archive with more pending sessions than one bounded
_DAEMON_EMBED_MAX_SESSIONS (25) convergence window, message_embeddings_meta
for the not-yet-reembedded remainder still carries the old recipe_hash after
batch one, so meta_recipe_changed stays true on every subsequent pass. The
unconditional bulk mark then re-flagged the batch-one sessions that had
already succeeded under the new generation/key, and because the exact
freshness predicate also requires needs_reindex=0, newest-first selection
looped on the same first batch forever instead of covering the archive --
undermining this PR's own AC that convergence be monotonic and progress.

Independently confirmed by reading _reconcile_embedding_config_change and its
three _archive_embed_check* call sites, all invoked on every convergence pass.

Also fixed a related false-positive: model_changed compared the raw `model`
text column, which the demo-seeded synthetic embedding deliberately sets to
"demo-synthetic-embedding" for construct/verify compatibility. Since
EmbeddingRecipe.identity() already hashes the model name as one of its
declared fields, any genuine model change already flips recipe_hash and is
caught by meta_recipe_changed/advanced_generations; model_changed was
redundant for real drift and only served to permanently mis-trigger a
full-archive reindex on demo archives. It stays for logging only.

What changed (polylogue/daemon/convergence_stages.py):
- The bounded embedding_derivation_state UPDATE now uses RETURNING session_id
  (established pattern; see embedding_write.py) to capture exactly which
  sessions advanced generation this pass.
- The embedding_status bulk mark is scoped to those session_ids via
  `WHERE session_id IN (...)`, except when dimension_changed -- a dimension
  change invalidates every stored vector archive-wide (the vec0 table itself
  is dropped/recreated), so that branch legitimately stays full-table.
- model_changed no longer participates in the recipe_changed trigger.

Second finding (P2, linked comment on materialization.py:455): the demo
seed's `_seed_demo_embeddings` wrote vectors/meta/a clean embedding_status row
but never created an embedding_derivation_state row. Every production
selector uses the shared exact-key freshness predicate
(_archive_embedding_freshness_predicate), whose `d.session_id IS NOT NULL`
check is always false without that row, so the demo session was classified
pending forever -- an embedding-enabled daemon pointed at a demo archive
would attempt a paid re-embed of content seeded to be cost-free.

Fixed polylogue/demo/seed.py: `_seed_demo_embeddings` now computes the
per-message recipe_hash/derivation_key/generation and a matching
embedding_derivation_state row (attempt_state='succeeded') keyed against the
*currently configured* embedding recipe (load_polylogue_config(), same
source the reconciler and freshness predicate use) rather than the
"demo-synthetic-embedding" display label. The `model` column keeps its
existing display value (still asserted by demo/constructs.py and
test_demo_seed_verify.py); only the identity-bearing recipe_hash/
derivation_key/generation fields are corrected.

Verification:
- New regression test (production route, not toy SQL): tests/unit/storage/
  test_embedding_freshness_invariant.py::
  test_recipe_change_reconciliation_does_not_restarve_sessions_already_succeeded
  writes 30 real archive sessions, embeds them, changes the configured model,
  runs convergence pass 1 (bounded to 25), re-embeds that batch for real, then
  runs pass 2 and asserts the batch-one sessions stay needs_reindex=0 and the
  returned pending set advances to the untouched remainder. Confirmed this
  fails against the pre-fix code (re-flags the batch and returns the same 25
  again) and passes against the fix.
- New test: tests/unit/demo/test_demo_seed_verify.py::
  test_seed_demo_embedding_session_is_classified_fresh_not_pending asserts the
  demo embedding session is excluded from
  select_pending_archive_session_window's real production selector.
  Confirmed this fails against the pre-fix seed.py and passes against the fix.
- devtools test tests/unit/daemon/test_embedding_convergence_progress.py
  tests/unit/storage/test_embedding_freshness_invariant.py
  tests/unit/storage/test_embedding_contracts.py
  tests/unit/storage/test_embedding_orphan_reconcile.py
  tests/unit/cli/test_embed_status_fast.py
  tests/unit/demo/test_demo_seed_verify.py -> 127 passed
- devtools test tests/unit/demo -> 38 passed
- devtools verify --quick -> exit 0 (ruff format/check, mypy --strict,
  render all --check, layering/topology/manifests/docs-coverage lanes)

Ref polylogue PR #3067 CodeRabbit review.

Co-Authored-By: Claude <[email protected]>
Sinity and others added 3 commits July 18, 2026 05:01
Four production embedding-selection call sites (per-source convergence,
daemon bulk backlog, manual `embed` backfill, preflight) previously
diverged: only one compared message_embeddings_meta.content_hash against
current content, the other three trusted needs_reindex alone via an
include_stale_checks=False bypass. Separately, mark_session_embedding_error
unconditionally cleared needs_reindex on a non-retryable terminal error,
which could clobber a concurrent config-change bulk-mark landing mid-flight
(same race class as the already-fixed success-path guard, left open on the
error path).

Introduces a storage-neutral DerivationKey value/protocol
(polylogue/storage/derivation_identity.py) separating subject, exact
source identity, computational recipe identity, and output contract from
attempt generation, eligibility, and result integrity -- no universal
derivation table or lifecycle. Embeddings map onto it via
polylogue/storage/embeddings/identity.py (EmbeddingRecipe covers all
twelve declared computational fields). _archive_embedding_freshness_predicate()
in materialization.py is now the sole freshness classification consumed
identically by all four call sites; the include_stale_checks bypass is
removed entirely. complete_embedding_attempt_success and
record_embedding_failure/mark_session_embedding_error commit inside one
transaction guarded by session_id+generation+derivation_key+attempt_state,
so a stale attempt's terminal write touches zero rows instead of
clobbering a newer generation.

EMBEDDINGS_SCHEMA_VERSION moves 2 -> 3 (canonical DDL, no migration chain --
embeddings.db is a rebuildable-but-expensive derived tier per project
doctrine). Verified this is not a silent auto-rebuild hazard:
initialize_archive_database raises a RuntimeError requiring an explicit
operator move-aside before an old v2 file is touched.

Fixed several real defects surfaced by independent verification of this
externally-authored patch before merge: a genuine runtime bug in
status_payload.py (_archive_embedding_session_state_exact_with_timeout
returned a 2-tuple on a missing-table path against a 3-tuple return type,
unpacked into three variables at its call site -- guaranteed ValueError),
13 mypy --strict errors, 4 ruff-format violations, a layering-manifest
entrypoint-list drift, and an unallowlisted degrade-loudly except-handler.

Ref polylogue-wmsc. Absorbs/validates supersession of polylogue-iqd3 and
polylogue-0k6 (both already closed as superseded by wmsc).

Co-Authored-By: Claude <[email protected]>
A broader post-commit regression sweep beyond the originally-scoped test
files found two fixtures the EMBEDDINGS_SCHEMA_VERSION 2->3 bump broke:

- tests/unit/cli/test_embed_activation.py::_seed_embeddings_meta hand-rolled
  a 6-column message_embeddings_meta CREATE TABLE IF NOT EXISTS + positional
  6-value INSERT. Once the archive workspace fixture initializes
  embeddings.db to the real v3 (9-column) schema first, the CREATE becomes a
  no-op and the positional INSERT fails with "table message_embeddings_meta
  has 9 columns but 6 values were supplied". Fixed to an explicit named-column
  INSERT so it works against either schema shape.
- tests/unit/devtools/test_archive_schema_fast_forward.py::
  test_embedding_clone_preserves_vectors_and_installs_failure_lifecycle
  hardcoded the pre-bump expected clone user_version (2). The production
  fast-forward helper already targets EMBEDDINGS_SCHEMA_VERSION dynamically
  (no fix needed there) -- only the test's hardcoded literal was stale.
  Replaced both hardcoded "2" assertions with the imported constant so a
  future schema bump can't silently re-break this test the same way.

Both confirmed passing after the fix; devtools verify --quick stays clean.

Verification: `devtools test tests/unit/cli/test_embed_activation.py
tests/unit/devtools/test_archive_schema_fast_forward.py` -> 60 passed.

Co-Authored-By: Claude <[email protected]>
Problem: CodeRabbit flagged a P1 on PR #3067 at convergence_stages.py:882 --
_reconcile_embedding_config_change() unconditionally set needs_reindex=1 on
every embedding_status row whenever recipe_changed was true, instead of only
the sessions whose embedding_derivation_state generation actually advanced
this pass. For an archive with more pending sessions than one bounded
_DAEMON_EMBED_MAX_SESSIONS (25) convergence window, message_embeddings_meta
for the not-yet-reembedded remainder still carries the old recipe_hash after
batch one, so meta_recipe_changed stays true on every subsequent pass. The
unconditional bulk mark then re-flagged the batch-one sessions that had
already succeeded under the new generation/key, and because the exact
freshness predicate also requires needs_reindex=0, newest-first selection
looped on the same first batch forever instead of covering the archive --
undermining this PR's own AC that convergence be monotonic and progress.

Independently confirmed by reading _reconcile_embedding_config_change and its
three _archive_embed_check* call sites, all invoked on every convergence pass.

Also fixed a related false-positive: model_changed compared the raw `model`
text column, which the demo-seeded synthetic embedding deliberately sets to
"demo-synthetic-embedding" for construct/verify compatibility. Since
EmbeddingRecipe.identity() already hashes the model name as one of its
declared fields, any genuine model change already flips recipe_hash and is
caught by meta_recipe_changed/advanced_generations; model_changed was
redundant for real drift and only served to permanently mis-trigger a
full-archive reindex on demo archives. It stays for logging only.

What changed (polylogue/daemon/convergence_stages.py):
- The bounded embedding_derivation_state UPDATE now uses RETURNING session_id
  (established pattern; see embedding_write.py) to capture exactly which
  sessions advanced generation this pass.
- The embedding_status bulk mark is scoped to those session_ids via
  `WHERE session_id IN (...)`, except when dimension_changed -- a dimension
  change invalidates every stored vector archive-wide (the vec0 table itself
  is dropped/recreated), so that branch legitimately stays full-table.
- model_changed no longer participates in the recipe_changed trigger.

Second finding (P2, linked comment on materialization.py:455): the demo
seed's `_seed_demo_embeddings` wrote vectors/meta/a clean embedding_status row
but never created an embedding_derivation_state row. Every production
selector uses the shared exact-key freshness predicate
(_archive_embedding_freshness_predicate), whose `d.session_id IS NOT NULL`
check is always false without that row, so the demo session was classified
pending forever -- an embedding-enabled daemon pointed at a demo archive
would attempt a paid re-embed of content seeded to be cost-free.

Fixed polylogue/demo/seed.py: `_seed_demo_embeddings` now computes the
per-message recipe_hash/derivation_key/generation and a matching
embedding_derivation_state row (attempt_state='succeeded') keyed against the
*currently configured* embedding recipe (load_polylogue_config(), same
source the reconciler and freshness predicate use) rather than the
"demo-synthetic-embedding" display label. The `model` column keeps its
existing display value (still asserted by demo/constructs.py and
test_demo_seed_verify.py); only the identity-bearing recipe_hash/
derivation_key/generation fields are corrected.

Verification:
- New regression test (production route, not toy SQL): tests/unit/storage/
  test_embedding_freshness_invariant.py::
  test_recipe_change_reconciliation_does_not_restarve_sessions_already_succeeded
  writes 30 real archive sessions, embeds them, changes the configured model,
  runs convergence pass 1 (bounded to 25), re-embeds that batch for real, then
  runs pass 2 and asserts the batch-one sessions stay needs_reindex=0 and the
  returned pending set advances to the untouched remainder. Confirmed this
  fails against the pre-fix code (re-flags the batch and returns the same 25
  again) and passes against the fix.
- New test: tests/unit/demo/test_demo_seed_verify.py::
  test_seed_demo_embedding_session_is_classified_fresh_not_pending asserts the
  demo embedding session is excluded from
  select_pending_archive_session_window's real production selector.
  Confirmed this fails against the pre-fix seed.py and passes against the fix.
- devtools test tests/unit/daemon/test_embedding_convergence_progress.py
  tests/unit/storage/test_embedding_freshness_invariant.py
  tests/unit/storage/test_embedding_contracts.py
  tests/unit/storage/test_embedding_orphan_reconcile.py
  tests/unit/cli/test_embed_status_fast.py
  tests/unit/demo/test_demo_seed_verify.py -> 127 passed
- devtools test tests/unit/demo -> 38 passed
- devtools verify --quick -> exit 0 (ruff format/check, mypy --strict,
  render all --check, layering/topology/manifests/docs-coverage lanes)

Ref polylogue PR #3067 CodeRabbit review.

Co-Authored-By: Claude <[email protected]>
@Sinity
Sinity force-pushed the feature/gpt-pro/misc02-embedding branch from 3106f92 to 7185b8d Compare July 18, 2026 03:03
@Sinity
Sinity merged commit 2d8f689 into master Jul 18, 2026
1 of 2 checks passed
@Sinity
Sinity deleted the feature/gpt-pro/misc02-embedding branch July 18, 2026 03:04
Sinity added a commit that referenced this pull request Jul 31, 2026
First verification-triage wave over the aged ready set (132 beads
checked by read-only lanes so far): polylogue-9x22 and polylogue-cgfy
closed as complete-on-master per their own sweep notes, polylogue-wmsc
closed as already-satisfied by PR #3067 (2026-07-18, never bookkept),
polylogue-3utv annotated misframed pending the dx1 ASGI decision.

Co-Authored-By: Claude <[email protected]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 62.F054 / P1: fixed-already at the checked revision: Embedding convergence now inspects the content/recipe-addressed message output directly, including the stored recipe hash comparison at polylogue/storage/embeddings/derivation.py:448. Ordinary passes call owner.converge without re-marking all completed session flags at polylogue/daemon/embedding_owner.py:558-577, so remaining old-model rows do not repeatedly invalidate already-current messages.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 73.F061 / P2: fixed-already at the checked revision: polylogue/demo/seed.py:1495-1498 now inserts embedding_derivation_state with the synthetic session's matching source, recipe and output contract and attempt_state='succeeded'. The row is committed at :1521, so synthetic embeddings no longer lack the required keyed provenance.

Only the rows listed above are dispositioned. Held findings remain open.

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