Repository navigation
feat(reader): embedding similarity browse (#1123) - #1178
Conversation
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (8)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ec6d4d01c9
ℹ️ 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".
ec6d4d0 to
5323b50
Compare
Add a per-conversation similarity read surface that consumes the embedding pipeline from #828 without ever calling the embedding provider — the source conversation's stored vectors are reused to issue ``vec0`` MATCH lookups against ``message_embeddings``. The endpoint is honest about the dormant default state and never collapses "disabled / unavailable / not-yet-embedded" into an empty success. Substrate: - ``GET /api/conversations/{id}/similar[?limit=N]`` (route added in ``polylogue/daemon/http.py``; logic in ``polylogue/daemon/similarity.py``) - envelope ``status`` is one of ``ready`` / ``disabled`` / ``unavailable`` / ``not_embedded`` with a machine-readable ``reason`` - ranked hits carry cosine ``score``, raw ``distance``, ``confidence`` chip (``q-canonical`` / ``q-estimated`` / ``q-heuristic``), title, provider, and ``matched_message_count`` - ``limit`` is clamped server-side to ``SIMILAR_RESULTS_MAX`` - the source conversation is excluded from its own neighbor set - reader-side fanout per source message is capped so a giant conversation never issues a thousand MATCH queries Surface: - new inspector "Similar" tab in the single-page web reader - fragment lives in ``polylogue/daemon/web_shell_similar.py`` to keep ``web_shell.py`` under its file budget - four explicit visual states (ready / disabled / unavailable / not_embedded) with actionable guidance for the disabled reasons (``embeddings_not_enabled`` vs ``no_voyage_api_key``) - clicking a hit reuses the existing single-conversation route Tests (``tests/unit/daemon/test_similarity_endpoint.py``): - pure helper contracts: confidence bands, disabled-reason partitioning, limit clamping, L2→cosine conversion, per-message aggregation with self-exclusion - substrate envelope contracts: 404 on unknown conversation, distinct ``embeddings_not_enabled`` vs ``no_voyage_api_key`` reasons, ``vec0_table_missing`` when the embedding stage has never run, limit clamp visible in the envelope - HTTP route contracts: 404 vs 200-with-status, disabled is a real response (not an error), ``?limit=`` propagation, unparseable ``limit`` falls back to the default Generated: - bumped ``polylogue/daemon/http.py`` file budget to 1420 to absorb the new handler (similarity scoring delegates to ``similarity.py``) - regenerated ``docs/plans/topology-target.yaml`` and ``docs/topology-status.md`` for the two new modules Closes #1123 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
5323b50 to
d5fa12d
Compare
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
## Summary Allow existing-session similarity to query retained vectors without Voyage acquisition credentials or provider calls. Keep counts, ranking and result metadata on one selected snapshot, and preserve typed unavailable/inconsistent states. ## Problem The ordinary daemon similarity route treated a missing Voyage key as disabled even when vectors were already materialized ([historical finding 64.F003](#1178 (comment))). Other retained-vector factories and daemon bindings imposed the same acquisition prerequisite. Generic read faults could also be rendered as `not_embedded`, and separate count/rank snapshots could cross a generation publication. ## Solution Separate retained reads from acquisition and query-text embedding, preserve the explicit archive recipe/root, and reuse the existing read-only snapshot owner for count, KNN, message mapping and title/origin projection on one worker. Close owned handles in that worker's finally. Record the attached index identity and creating thread at admission; refuse incompatible supplied handles. Check seed existence before ranking on that same handle, and expose one canonical SessionNotFoundError to all consumers. Close ordinary daemon preflight handles explicitly. Delete the fixture-only compatibility admission/projection and use canonical synthetic archives. Update API consumers, the public VectorProvider snapshot contract and implementations, both session-seed resolvers, daemon bindings, tests and guidance. Text semantic/hybrid requests without credentials remain disabled/unavailable; retained reads stay available. Missing runtime, missing or corrupt storage, contention and projection failures remain typed unavailable. Only a successful zero count for a present indexed seed establishes `not_embedded`; malformed provider hits remain counted as inconsistent. ## Verification Exact candidate: `173c2862c706655a2a1e9e77a7b3d869b64e996d`. ```sh agentctl job start polylogue pytest_focused --workspace /realm/worktrees/polylogue-retained-vector-read -- tests/unit/daemon/test_similarity_endpoint.py tests/unit/operations/test_daemon_reads.py tests/unit/api/test_embedding_readiness_api.py tests/unit/api/test_facade_contracts.py tests/unit/archive/test_near_session_seed_execution.py tests/unit/archive/test_query_search_runtime.py tests/unit/archive/test_search_lane_execution.py tests/unit/storage/test_vec.py tests/unit/storage/test_vec_dimension_refusal.py tests/unit/storage/test_vec_session_seed.py tests/unit/storage/test_vector_provider_recipe.py tests/unit/storage/test_vector_query_readiness.py tests/unit/core/test_config_resolution_regression.py tests/unit/test_protocol_conformance.py tests/unit/daemon/test_http_write_coordination.py tests/unit/daemon/test_daemon_http_contracts.py tests/unit/daemon/test_daemon_operation_route.py tests/unit/daemon/test_operation_protocol.py tests/unit/storage/test_embedding_freshness_invariant.py tests/unit/daemon/test_embedding_readiness.py tests/unit/cli/test_embed_status_fast.py tests/unit/storage/test_embedding_rebuild_survival.py tests/unit/storage/test_embedding_dedup.py tests/unit/storage/test_embedding_cross_root_reuse.py tests/unit/storage/test_embedding_contracts.py tests/unit/storage/test_store_ops.py tests/unit/cli/test_query_expression.py tests/unit/operations/test_mutations.py tests/unit/core/test_facade_api.py tests/unit/product/test_topic_pack_workflow.py tests/unit/operations/test_transcript_window_route.py tests/unit/operations/test_transcript_window_resume_selection.py tests/unit/mcp/test_session_orchestration.py -p no:randomly agentctl job start polylogue verify_quick --workspace /realm/worktrees/polylogue-retained-vector-read ``` - Job 5359: `1348 passed, 1 skipped in 162.74s`; exit 0, `pytest_passed`, 1349 selected and terminal cases, no retry. This covers all 33 affected modules. Receipt: `20261001T040225Z-focused-test-3834055-5f316a59`. The skip is the existing empty parameter set in query-expression aggregate-transform coverage. - Quick5360 passed all12 gates, exit0 on clean exacthead; receipt `20261001T040252Z-quick-3834210-65a31c84`. - Closure5299 passed on7975, exit0: ten of25 product paths in closure560; this test-only batch leaves product ASTs unchanged. No DDL, schema-version bump, archive migration or model migration. ## Self-review <details> <summary>Whole-base author review: project guide, area rules and generic checklist</summary> Author review of all 46 changed paths from integrated master07323a75cb29c3674cbd921fdfdbbf892837de3a to 173c286. I re-read the project guide, storage and daemon area rules, and generic worker checklist, then re-read every product and test diff during final integrated verification and considered its clean terminal receipts. This correction batch received two whole-base passes; the final pass found no remaining defect. Earlier passes fixed credential classification, writable fixture compatibility, split generations, ambient recipe substitution, typed runtime failures, public protocol drift, external row/thread ownership, admission provenance, seed presence before ranking and explicit preflight cleanup. Complete job 5359 passed all 33 affected modules: 1348 passed, 1 skipped in 162.74s, exit 0, with 1349 selected and terminal cases and no retry. Receipt: 20261001T040225Z-focused-test-3834055-5f316a59. Quick job 5360 passed all 12 gates on this clean exact head; receipt: 20261001T040252Z-quick-3834210-65a31c84. Closure job 5299 passed ten members among 25 product paths, closure size 560, on 7975; this test-only correction leaves the product ASTs unchanged. Project guide: 1. ✓ Siblings and owners: searched every query_by_session, count_session_embeddings, factory and binding caller. The ordinary HTTP/API route, both near:id resolvers and daemon supplied snapshots now permit retained reads without acquisition credentials; text embedding retains its requirement. The existing requires_vector_snapshot owner now excludes keyless text before vector admission while retaining session-seeded snapshots. SqliteVecProvider.query retains its disabled guard before provider lifecycle/acquisition work. 2. ✓ The fix itself: re-read new errors and consumers. operations/vector_reads.py:15 preserves core typed runtime/storage refusals, and repository_vectors.py:109 raises the existing runtime marker when the retained backend is absent. 3. ✓ Memory and limits: new projection materializes only returned message IDs and ranked session metadata; it adds no archive-wide buffer, limit or timeout. Existing vector projection and KNN semantics remain. 4. ✓ Cost per unit: repository_vectors.py:143 batches message mapping and metadata with indexed IN queries. It no longer hydrates complete messages/attachments for title/origin or issues a metadata query per hit. 5. ✓ Interruption: retained reads publish no durable state. SqliteVecProvider.read_session_similarity dispatches owned handles to one worker; supplied handles run synchronously on their creating thread. A cancelled async waiter does not close a worker handle from another thread: worker finally owns cleanup. Writer/control behavior is untouched. 6. ✓ Ordering and races: seed existence, count, ranking, mapping and metadata use one pinned handle. Admission records selected index identity and opening thread before later provider construction. The canonical substrate require_vector_seed_session predicate runs before count/rank and is reused by repository projection for external providers; retained old refs cannot turn a removed seed into unavailable. The first-promotion regression passes with the selected snapshot’s absent-session404; actual selected path is recorded at publication before query. The HTTP test attempts actual IndexGenerationStore promotion at the old count/rank seam for both conventional first publication and an already selected generation, retaining chosen titles and checking the resolved successor after cleanup. Supplied snapshots validate the requested attached path and inode, refusing replaced conventional identities; managed readers refuse indexes outside the trusted root. 7. ✓ Failure classification: corruption, missing tier/table, projection faults, locks, stale projection and missing runtime render typed unavailable. Only a successful zero count renders not_embedded; runtime recognition uses an exception type rather than message substring. 8. ✓ Silent outcomes: unresolved provider message hits still yield inconsistent with unresolved_message_hits. No failed read becomes an empty ready/not_embedded answer; tested policies remain explicit disabled/not_embedded states. 9. ✓ Cleanup on failure: the provider finally closes owned snapshots after count, query or projection failure. Shared harness tests closure on the owning thread, including injected count contention and stale query refusal; supplied snapshots remain with their owner. Daemon index-only and vector-table preflight handles now use contextlib.closing; ready and fault regressions instrument the actual measured close, verify its creating thread and probe the closed connection on that same thread. Projection uses a cursor-local sqlite3.Row and contextlib.closing, preserving a third-party connection row factory and closing its own cursor on every exit. 10. ✓ Identity and keys: canonical recipe/prose hashes and generated message identities remain authoritative. Explicit Config model/dimension/root reach the retained factory; title None is retained and Origin follows the domain model's source_name_to_origin/Origin conversion. No identity formula or reverse Provider lookup changes. 11. ✓ Lossless transforms: purchased vector bytes are neither rewritten nor reinitialized. The fixture-only projection is deleted, fixtures use canonical index/prose/ref data, and normal production acquisition keeps its credential path. 12. ✓ Degenerate inputs: existing empty/one seed, zero count, missing extension, missing/corrupt storage, incompatible dimensions and empty result contracts remain covered. SQL metadata hydration avoids constructing an empty IN query. 13. ✓ Consumers: the API forwards provider_config; both seed resolvers and daemon vector bindings are updated. rg found no provider_db_path or _legacy_compatibility references. API's acquisition-key similarity argument and fixture predecessor are removed; docs distinguish acquisition and retained reads; generated surfaces are checked by the quick gate. The public VectorProvider declares read_session_similarity and its snapshot lifetime/projection contract; the private protocol/cast is deleted. SessionNotFoundError has one core definition and unchanged PolylogueError inheritance/404 status; every internal consumer imports it there and the declared public API export exposes the same type. Its old definition/export in mutation operations is removed. The public method is async so the provider owns dispatch; the sole concrete implementation and seven fixture providers conform together. The sole production repository caller awaits it directly, and the private synchronous helper has no public callers. 14. ✓ Tests and stubs: actual daemon GET dispatch and actual API reads execute canonical sqlite-vec SQL on neutral fixtures. Restoring a key gate, replacing Config with ambient settings, reopening between count/rank/hydration, swallowing a fault, or omitting close makes the relevant regression fail. Removing the public protocol method fails the typed repository call, and using generic SqliteVecError for keyless text fails disabled/unavailable lane assertions. Actual UDS requests inject vector construction faults and prove no vector admission; API regressions cover A/B mismatches, supplied default thread affinity including construction on a different worker, replacement before/after provider construction and a third-party tuple connection. Actual snapshot-admission replacement refuses and proves cleanup. Removed seeds retain old refs in both API/HTTP cases; present-unembedded remains a measured zero. Collection-time fixture recipe capture is removed in all three sibling modules; providers pin the isolated configuration when constructed. 15. ✓ Trust boundaries: all new data is neutral synthetic prose and vectors. Tracked diff contains no archive, transcript, key, receipt or private analysis. HTTP refusal exposes typed reason rather than exception/path detail; production auth/writer ownership is unchanged. Storage and daemon area rules: 16. ✓ Derived identity: schema closure includes ten changed members among 25 product paths (core/errors, core/protocols, archive execution/search contract, and six vector-provider files). They land before any daemon reconvergence; no manual computed-identity bump is added. 17. ✓ Embeddings tier: no DDL, EMBEDDINGS_SCHEMA_VERSION, tier replacement or deletion changes. Stored session reads use open_vector_read_snapshot and read-only URI attachments, with TEMP staging only. 18. N/A Durable enum DDL: no source/user/audit DDL or vocabulary validation is changed; synthetic writes use the existing archive bootstrap and embedding write owner. 19. ✓ Writer authority: retained reads never use the writable _get_connection path. Production constructor census found only the canonical factory (owned snapshots use the classmethod); fixture-only arbitrary-path admission is removed. 20. N/A Rebuildable authority for durable mutation: this diff makes no durable mutation and uses index rows only to answer reads. 21. ✓ Daemon progress: no new deadline, retry loop or timeout is introduced. The inherited await test adds only its actual envelope to an assertion; its expectation and 25ms deadline are preserved. 22. ✓ Daemon write ownership: HTTP similarity remains read-only, and publication attempts occur only in isolated synthetic fixtures using the existing generation store. No live archive or writer path is changed. Generic worker checklist: 1. ✓ Assigned production contract: real HTTP and API regressions demonstrate key-free retained reads and zero acquisition calls, explicit configured recipe, typed fault states and coherent chosen generation. The complete 33-file selection includes the original 27 and six actual consumers of the relocated canonical error; exact-head job 5359 passed 1348 tests with one existing empty-parameter skip and no retry. 2. ✓ Defect census: searched stored-vector factories, bindings, count/rank consumers and constructors. The credential gate is removed from stored readers only; acquisition and query-text embedding remain separate. 3. ✓ Complete consumers: all in-tree API/repository and seed-resolver consumers are changed together; retired compatibility flags, fake embeddings-side sessions and removed keywords have no remaining references. 4. ✓ Typed visible failures: core runtime/read markers, operations translation, and daemon envelope retain storage/runtime uncertainty; malformed hit joins are counted explicitly. 5. ✓ Non-vacuous tests: named mutants are restored key gating, ambient recipe use, a fresh snapshot at ranking/hydration, an unavailable-to-not_embedded substitution, and a no-op handle close. Mutation error consumers now execute through their required real daemon writer, with seed writes completed before daemon startup. Fixtures use actual production projection and real publication attempts, without a compatibility projection. 6. ✓ Public boundary: inspected all 46 changed paths and the public narration; synthetic fixtures and product code/docs only. Job receipts and scratch files stay outside Git. </details> ## Residuals The focused selection proves these routes, not the complete corpus or a live operator archive. No paid provider or live archive operation was performed. Independent local review found no concrete defect on b5d9 after reading all 46 changed paths, consumers, existing findings and owner receipts; integration preserved those file blobs. Required hosted statuses and conversation resolution must pass on the pushed head before merge. Integration: merged pinned master07323a75cb29c3674cbd921fdfdbbf892837de3a normally. All46 candidate file blobs were preserved; zero path overlap with98 upstream paths. Re-read the integrated whole diff and all28 author checklist considerations, clean. Independent local review was clean on preserved b5d9 product/test blobs; final full33 and quick above ran on integrated173c2862. Manual hosted reviews are disabled by operator instruction; required forge statuses and conversation resolution remain enforced.
Summary
Adds a per-conversation similarity read surface (
GET /api/conversations/{id}/similar) and a "Similar" inspector tab in the web reader. Consumes the embedding pipeline established by #828 without ever calling the embedding provider — stored vectors of the source conversation are reused forvec0MATCH lookups. Honest about the dormant default state: never collapses "disabled" / "unavailable" / "not yet embedded" into an empty success.Problem
Per #1123, the reader needed a "find similar" entry point that respects the embedding pipeline's actual readiness:
vec0table access from UI code)Solution
Substrate (
polylogue/daemon/similarity.py, 386 lines):build_similar_payload(conv_id, *, limit)returns an envelope whosestatusis one of:ready— ranked hits attached underresultsdisabled—reasonisembeddings_not_enabledorno_voyage_api_key(distinguished so the UI can render the correct fix)unavailable—reasonisvec0_table_missingorsqlite_vec_not_loaded(pipeline never ran / extension missing)not_embedded— source conversation has no stored vectors yetscore, rawdistance,confidencechip (q-canonical/q-estimated/q-heuristic), title, provider, andmatched_message_countlimitis clamped server-side toSIMILAR_RESULTS_MAX = 50_PER_MESSAGE_K = 20) so a giant conversation never issues a thousand MATCH queriesRoute (
polylogue/daemon/http.py):_handle_get_conversation_similaris a thin operator entrypoint: parseslimit, delegates tobuild_similar_payload, 404 on missing conversation, 200 with explicitstatusfor every other case (disabled is a real response, not an error).Surface (
polylogue/daemon/web_shell_similar.py+ integration inweb_shell.py):statusvocabularyVOYAGE_API_KEYvs flipembedding_enabled = trueinpolylogue.toml)state.similarPanelskeyed by conversation idweb_shell.pyunder its file budgetRejected alternatives:
HybridSearchProvider.search_scored(query)would require a Voyage API key just to issue a similarity lookup, even though the source conversation already has its vectors stored. Reading those vectors back and using them directly asMATCHinputs is both cheaper and works on offline archives where the key has been removed.Verification
Pre-push gate (
devtools verify --quick) is green for this branch's diff.Test coverage (
tests/unit/daemon/test_similarity_endpoint.py, 16 cases)embeddings_not_enabledvsno_voyage_api_keyreasons,vec0_table_missingwhen the embedding stage has never run, limit clamp visible in the envelope?limit=propagation, unparseablelimitfalls back to the default,unavailableenvelope when pipeline dormantThe
vec0MATCH engine itself is not exercised in unit tests becausesqlite-vecmay not be loadable in every verify environment; integration with stored vectors flows through the same shared loader (try_load_sqlite_vec) used bySqliteVecProviderso the live ready-state path is the existing tested code path.File targets
polylogue/daemon/similarity.py(new, 386 lines)polylogue/daemon/web_shell_similar.py(new, 160 lines)polylogue/daemon/http.py(+38 lines: route + handler)polylogue/daemon/web_shell.py(+13 lines: tab button, dispatch, state init, JS interpolation)tests/unit/daemon/test_similarity_endpoint.py(new, 16 cases)docs/plans/file-size-budgets.yaml(http.py 1380→1420 to absorb new handler)docs/plans/topology-target.yaml,docs/topology-status.md(regenerated)Follow-ups
Closes #1123