Skip to content

feat(search): fold Polish diacritics across every FTS write path (#2754) - #2754

Merged
Sinity merged 4 commits into
masterfrom
feature/search/polish-fts-fold-publish
Jul 12, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/search/polish-fts-fold-publish

Conversation

@Sinity

@Sinity Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner

Summary

Add deterministic Polish lexical folding across every FTS5 surface and every fresh-write, bulk-write, rebuild, and dangling-repair route. Plain-ASCII queries such as latwo and zrobilem now find łatwo and zrobiłem content. This fresh-master replacement preserves the logical work from PR #2753 without rewriting that branch and corrects the schema overview to index version 35.

Problem

SQLite FTS5 unicode61 remove_diacritics 2 folds ordinary Polish diacritics but cannot fold ł/Ł, because those code points have no Unicode decomposition. Query-side folding without matching write-side coverage creates silent recall loss: the original implementation missed the public ArchiveStore.rebuild_index() writer and the keyed dangling-row repair writers for threads and session work events. The prior branch also conflicted with current master and left docs/schema.md reporting index version 34 after the canonical DDL moved to version 35.

Solution

  • Derive Python, registered SQLite-function, and inline SQL-expression projections from one PL_FOLD_TABLE (ł → l, Ł → L).
  • Use unicode61 remove_diacritics 2 for messages_fts, threads_fts, and session_work_events_fts.
  • Apply the inline fold at canonical triggers, bulk/missing-row writers, full rebuilds, ArchiveStore.rebuild_index(), and both keyed dangling-derived repair paths.
  • Fold production MATCH query text at the shared escape_fts5_query chokepoint.
  • Keep trigram fallback disabled pending the measured opt-in work in polylogue-xul7.
  • Bump the rebuildable derived index tier from 34 to 35 and document polylogue ops reset --index && polylogued run; no in-place migration helper is added.
  • Regenerate topology from current master and update docs/schema.md to the canonical version 35.
  • Preserve current-master Beads records semantically: the branch changes six issue records whose updated_at values are newer than master and adds ten related interaction records.

Acceptance criteria

Criterion Status Evidence
latwo / zrobilem find seeded łatwo / zrobiłem Satisfied Real trigger-backed tests in tests/unit/storage/test_pl_fold.py
Fold is idempotent and Python/SQL projections agree Satisfied Python, registered-UDF, and inline-REPLACE agreement tests
Canonical DDL tokenizer sites cannot drift Satisfied Tokenizer contract tests cover all three surfaces
Production MATCH builders normalize query text Satisfied Shared escape_fts5_query / normalize_fts5_query routing plus static call-site audit
Rebuild and repair writers preserve folding Satisfied Public ArchiveStore.rebuild_index() test and real dangling-repair test for both derived surfaces
Trigram remains off until measured Satisfied No fallback added; polylogue-xul7 has the size/precision acceptance criteria
Derived schema change has an explicit rebuild plan Satisfied Index version 35 and documented reset/reingest command; docs/schema.md agrees

Anti-vacuity was checked independently before publishing the replacement: removing the public-rebuild fold failed test_pl_fold.py at the ASCII recall assertion; removing the work-event and thread repair folds independently failed the derived-surface test at their respective assertions. The tests seed canonical source rows before repair and exercise production entrypoints.

Verification

  • devtools test tests/unit/storage/test_pl_fold.py tests/unit/storage/test_fts_repair_sql.py tests/unit/storage/test_dangling_fts_derived_surfaces.py tests/unit/storage/test_schema_policy_contracts.py — 46 passed in 33.01s.
  • devtools test -k schema_mismatch tests/unit/daemon/test_daemon_cli.py — 2 passed, 73 deselected in 12.09s.
  • devtools render all --check — exit 0; all generated surfaces and site links are in sync.
  • devtools verify --quick — exit 0, run 20260712T090941Z-quick-1151050-a475c192; ruff format/check, mypy, render, topology, layering, schema roundtrip, manifests, workflow, docs, and test-infrastructure gates all passed.
  • .agent/scripts/bd-graph-lint — no cycles, duplicate labels, or inversions; it reports the two inherited master missing-AC records polylogue-2ilz and polylogue-nu2h, neither modified by this branch.
  • jq -e -c . .beads/issues.jsonl and .beads/interactions.jsonl — exit 0.
  • git diff --check origin/master...HEAD — exit 0.

CI and review note

At publication time, GitHub Actions jobs on the superseded PR were zero-step failures with the annotation that the account was locked due to a billing issue. Those failures did not execute repository code and are not represented as green evidence here. This ready-for-review replacement intentionally triggers whatever automated review/check capacity is available; any repeated billing-locked jobs remain an external red publish gate until they can actually run.

Ref polylogue-9jsi

Sinity and others added 4 commits July 12, 2026 11:06
Problem: unicode61's remove_diacritics option folds ordinary combining-mark
diacritics (o-acute, z-dot, a-ogonek, ...) symmetrically for indexed and
MATCH query text, but Unicode assigns l/L-stroke no canonical decomposition,
so neither NFD normalization nor remove_diacritics can fold it. A plain-ASCII
query like "latwo" never found seeded "latwo-with-stroke" content, and
remove_diacritics wasn't even enabled. Verified empirically with a live
sqlite3 fts5vocab probe before implementing (unicode61 remove_diacritics 2
folds z-dot/o-acute correctly on its own; only the stroke letter needs an
explicit fold).

What changed:
- polylogue/storage/fts/pl_fold.py: one canonical PL_FOLD_TABLE (l/L-stroke
  only) expressed three ways -- pl_fold() (Python, query-side), the
  registered SQL scalar function (ad-hoc/diagnostics), and
  pl_fold_sql_expr() (an inline REPLACE-chain embedded directly in
  trigger/insert DDL text so write-side folding does not depend on every
  connection that fires a blocks/threads/session_work_events trigger having
  registered a custom function first).
- All three unicode61 contentless FTS surfaces (messages_fts, threads_fts,
  session_work_events_fts) move to tokenize='unicode61 remove_diacritics 2'
  and fold search_text through pl_fold_sql_expr before insertion, in both
  canonical DDL sites (archive_tiers/index.py, fts/fts_lifecycle.py,
  fts/sql.py bulk-insert helpers).
- escape_fts5_query -- the single chokepoint every production MATCH builder
  routes through (8+ call sites) -- applies the identical Python pl_fold to
  query text before quoting, so write/query folding cannot drift apart.
- register_pl_fold wired into both sync (storage/sqlite/connection.py) and
  async (storage/sqlite/async_sqlite.py) read/write connection setup.
- INDEX_SCHEMA_VERSION 34 -> 35 (derived-tier rebuild: polylogue ops reset
  --index && polylogued run). docs/internals.md + docs/search.md updated.

Explicitly out of scope (per the bead's own AC): a trigram fallback lane
stays off pending a measured size/precision report -- tracked as
polylogue-xul7, not built here.

Verification: devtools test tests/unit/storage/test_pl_fold.py (12 passed,
covers idempotency, Python/SQL/REPLACE-chain agreement, the DDL-site
drift-lock, and end-to-end recall against the real trigger-backed schema)
plus the surrounding FTS suite (211 passed) and schema-version-sensitive
tests (test_archive_tiers_assertions.py, test_schema_policy_contracts.py,
test_status_diagnostics.py, test_tutorial.py, 2 targeted daemon_cli tests --
all passed except one pre-existing unrelated failure filed as
polylogue-gxly). mypy --strict clean on touched files. devtools render all
--check clean.

Ref polylogue-9jsi

Co-Authored-By: Claude <[email protected]>
Resolve the replacement branch's JSONL conflict by bead identity and
updated_at while retaining master-only and branch-only records. Preserve
master's raw lines so the resolution does not reserialize unrelated beads.

Ref polylogue-9jsi

Co-Authored-By: Claude <[email protected]>
Problem: query normalization folded Polish l-stroke globally, but the
public message-index rebuild and keyed dangling repairs still indexed raw
search_text. Running those maintenance routes silently removed the recall
guarantee until another full repair rewrote the rows.

Apply the canonical inline fold to all three missed writers. Add real-route
proofs through ArchiveStore.rebuild_index and dangling derived-surface
repair; each assertion depends on its production fold call and checks both
ASCII and literal Polish queries. Clarify the derived-tier rebuild contract
and regenerate topology against current master.

Ref polylogue-9jsi

Co-Authored-By: Claude <[email protected]>
Problem: the Polish FTS tokenizer and write-fold change bumps the derived
index tier to version 35, but the schema overview still reported version
34. The generated-surface checks do not own this manually maintained page.

Update the tier-version table so the public schema overview agrees with
the canonical index DDL and documented reset-and-reingest plan.

Ref polylogue-9jsi

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

coderabbitai Bot commented Jul 12, 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: 27 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: 2c89bd46-6e63-48d5-bd08-e89bdda6aaa4

📥 Commits

Reviewing files that changed from the base of the PR and between 54af547 and 15b631c.

📒 Files selected for processing (18)
  • .beads/interactions.jsonl
  • .beads/issues.jsonl
  • docs/internals.md
  • docs/plans/topology-target.yaml
  • docs/schema.md
  • docs/search.md
  • docs/topology-status.md
  • polylogue/storage/fts/dangling_repair.py
  • polylogue/storage/fts/fts_lifecycle.py
  • polylogue/storage/fts/pl_fold.py
  • polylogue/storage/fts/sql.py
  • polylogue/storage/search/query_support.py
  • polylogue/storage/sqlite/archive_tiers/index.py
  • polylogue/storage/sqlite/archive_tiers/write.py
  • polylogue/storage/sqlite/async_sqlite.py
  • polylogue/storage/sqlite/connection.py
  • tests/unit/storage/test_dangling_fts_derived_surfaces.py
  • tests/unit/storage/test_pl_fold.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/search/polish-fts-fold-publish

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.

@Sinity Sinity changed the title feat(search): fold Polish diacritics across every FTS write path feat(search): fold Polish diacritics across every FTS write path (#2754) Jul 12, 2026
@Sinity
Sinity merged commit 25bea6f into master Jul 12, 2026
3 of 16 checks passed
@Sinity
Sinity deleted the feature/search/polish-fts-fold-publish branch July 12, 2026 09:12
Sinity added a commit that referenced this pull request Jul 12, 2026
…2755)

## Summary

Adds bounded, resumable reconciliation for orphan rows in
`embeddings.db`, runs it through daemon convergence, and exposes a
dry-run-first maintenance command. Mutation is atomic and
writer-coordinated, preserves surviving sessions for re-embedding,
accounts for asymmetric meta/vec0 populations, and refuses to use a
schema-stale active index as deletion truth. Dry-run output reports the
bounded meta/vector/status candidate set separately from rows actually
removed.

## Problem

`embeddings.db` is not rebuilt in lockstep with `index.db`. Full
replacement or index rebuild can leave metadata, vec0, and status rows
whose message/session identities no longer exist, inflating storage and
coverage counters. A 2026-07-12 read-only census of the current active
generation found 741,267 metadata rows, including 22,442 identities
absent from the active index, plus 17,231 status rows with 303
absent-session rows.

That active index is schema v32 while the packaged index schema is v34
and daemon ingest is still running. Those counts are diagnostic only:
the active generation is not yet authoritative deletion truth, so
destructive cleanup must wait for the rebuild.

This replaces conflicting PR #2749 from fresh master after PR #2754
changed generated topology.

## Solution

- Add `polylogue/storage/embeddings/reconcile.py` with one `BEGIN
IMMEDIATE` transaction covering meta/vec0 deletion, surviving-session
recount + `needs_reindex = 1`, and absent-session status cleanup.
Exceptions roll back the whole pass and retry remains idempotent.
- Select orphan identities from the union of metadata and vec0 so
meta-only and vec0-only rows are independently counted and removed.
Identity absence is the only deletion trigger; identity-present
content-hash mismatches remain preserved for `polylogue-0k6`.
- Track the bounded candidate identity/meta/vector/status populations
separately from apply-only removal counters, so plain and JSON dry-run
output reports what would actually be removed without pretending a
mutation occurred.
- Revalidate the resolved active index path/device/inode before mutation
and before commit.
- Require apply mode to verify attached `PRAGMA idx.user_version` equals
packaged `INDEX_SCHEMA_VERSION`. Dry-run inspection remains available on
mismatched generations; daemon and CLI mutation refuse the live
v32-vs-v34 state.
- Serialize the daemon pass through `DaemonWriteCoordinator`; require
the CLI `--yes` path to hold the exclusive offline rebuild lease and
reject a running daemon.
- Bound daemon and default manual-apply passes to 500 identities. Manual
dry-run remains unbounded unless `--max-count` is supplied.
- Run one periodic daemon pass every 15 minutes once the archive is
schema-authoritative; expose `polylogue ops maintenance
embedding-orphan-reconcile` for inspect/break-glass operation.
- Regenerate topology projection/status against current master.

### Acceptance-criteria disposition

| Criterion | Disposition |
| --- | --- |
| Synthetic rebuild retains deleted-message and absent-session embedding
rows | Satisfied by real SQLite/vec0 fixtures. |
| Automatic bounded convergence removes only orphan rows and updates
counters | Satisfied; daemon coordinator route is covered. |
| Interruption/retry is atomic and idempotent | Satisfied by a real
trigger-injected failure across delete/recount/status cleanup followed
by successful retry. |
| Active vectors survive and affected surviving sessions re-enter
backlog | Satisfied; the test invokes the production pending-session
selector after reconciliation. |
| Generation/identity/content-hash guards are mutation-sensitive |
Identity/content-hash/path+inode/schema guards are covered.
Generation-pointer lifecycle remains tracked by `polylogue-b5l`; this
slice refuses schema-stale generations now. |
| Superseded changed-text rows | Deferred to the existing focused
lifecycle bead `polylogue-0k6`; this reconciler deliberately preserves
identity-present rows. |
| Live before/after cleanup proof | Deferred until the authoritative v34
index rebuild. The bead must remain open until apply records exact
before/after counts. |

## Verification

```text
devtools test tests/unit/storage/test_embedding_orphan_reconcile.py tests/unit/daemon/test_embedding_orphan_reconcile_daemon.py tests/unit/cli/test_archive_maintenance_cli.py
66 passed in 123.66s

devtools verify --quick
15/15 steps exit 0; total 24.7s
```

The focused run exercises real SQLite/vec0 rows, the production
pending-session selector, the daemon coordinator route, and plain/JSON
CLI routes. The rollback test fails if the transaction boundary is
removed; the schema/path guards and offline lease tests fail if their
production checks are removed. The manual-bound regression seeds 501
real candidates and requires the default apply pass to remove exactly
500 while leaving resumable debt.

### Adversarial review notes

- Iteration 1 found one real gap: dry-run rendered apply-only zero
removal counters despite nonzero candidates. Commit `ba5d8820b` adds
separate bounded candidate counters and production plain/JSON CLI
regressions.
- Automated Codex review found that manual apply overrode the storage
default with an unbounded `None`. Commit `a1df0b4ab` restores the
500-identity apply default and adds a 501-candidate production-route
regression; the review thread is answered and resolved.
- No further legitimate code or closure gaps remained after the
corrected diff was reviewed against every acceptance criterion.
- GitHub-hosted jobs currently fail before allocation with zero steps/no
logs under the repository billing lock, so local gates above are the
executable verification evidence.

No destructive live apply was run. Apply and bead closure remain
deferred until the active index is rebuilt from v32 to packaged v34 and
the resulting before/after census is recorded.

Ref polylogue-1dk1

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


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
  * Added tools to inspect and reconcile orphaned embedding records.
* Added a safe, read-only dry-run mode with JSON and human-readable
reports.
* Added optional cleanup mode with safeguards against concurrent or
stale index changes.
* Added automatic background maintenance to gradually process orphaned
records.
* **Bug Fixes**
* Removed obsolete embedding records and refreshed related embedding
status entries while preserving active data.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <[email protected]>
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