Skip to content

perf(topic-memory): scope SQLite FTS writes and searches to per-Scope rowid ranges - #2532

Merged
hidb4ai merged 3 commits into
oceanbase:masterfrom
Fengzdadi:perf/topic-memory-sqlite-fts-scope-rowids
Nov 11, 2026
Merged

hidb4ai merged 3 commits into
oceanbase:masterfrom
Fengzdadi:perf/topic-memory-sqlite-fts-scope-rowids

Conversation

@Fengzdadi

Copy link
Copy Markdown
Collaborator

Which issue or RFC does this PR close?

No tracking issue exists. The problem, measurements and upgrade policy are described below.

Rationale for this change

SQLiteTopicMemoryFTSIndex keeps scope_id and artifact_id UNINDEXED in pc_topic_memory_topic_fts and pc_topic_memory_chunk_fts, so neither Topic replacement nor Topic search could narrow the FTS5 cursor to one Scope:

  • replace_many deleted with WHERE scope_id = :scope_id AND artifact_id = :artifact_id. The plan is SCAN pc_topic_memory_chunk_fts VIRTUAL TABLE INDEX 0:, a scan of every Scope's rows on each table for every replaced Topic.
  • Search ran MATCH :query AND scope_id = :scope_id. fts_match_query ORs the query terms, so FTS5 returned every row in every Scope containing any term, and scope_id was checked on each of those rows. The plan is INDEX 0:M9.

Topic search runs in recall during prepare (TopicMemorySearcher) and in Topic processing's related-Topic search, so this cost sits on the per-turn latency path and grows with unrelated tenants' data.

What changes are included in this PR?

Scope rowid ranges (Topic FTS helper version 2). Each Scope hashes (SHA-256 of its UTF-8 identity) to its own range of 2^32 rowids, starting at 2^32. FTS5 bounds both MATCH cursors and plain scans by rowid, so:

  • replacement deletes with rowid BETWEEN :first AND :last AND scope_id = :scope_id AND artifact_id IN (...) (plan INDEX 0:><) and appends after the highest rowid in the range (ORDER BY rowid DESC LIMIT 1, plan INDEX 192:><);
  • both search statements add the same range to the MATCH (plan INDEX 0:M9><).

scope_id stays in every predicate, so two Scopes that share a hashed range remain separated. When a range's tail is exhausted, its rows are renumbered densely inside the same transaction. This happens at most once per 2^32 appended rows for that range.

Unchanged: the registered virtual table definitions, registered schema fingerprints, migration resources, the authoritative active Topic tables, and the OceanBase/seekDB indexes. bm25 still uses table-wide statistics, so search hits, raw scores, ordering, coverage admission and retrieved/eligible counts are identical (see testing).

Upgrade policy. Version 1 numbered helper rows globally from 1, so its rows sit below 2^32 and are distinguishable from Scope ranges with a constant-time probe (rowid < 2^32, plan INDEX 0:<).

  • Unmanaged initialization (SDK and embedded use) rebuilds a version-1 or missing helper from pc_topic_memory_active_topics / pc_topic_memory_active_chunks with exact identities and revisions, then records marker version 2. Version 3 or later is still rejected.
  • Managed Server databases upgraded from 1.3.0 or 1.4.0 get the same rebuild through the existing s1400 domain step, which already calls this index's initialize. Fresh managed databases start with version-2 rows.
  • Managed startup only validates and never rebuilds. A managed database whose helper still holds version-1 rows (for example one created by 1.4.1 or 1.5.0) keeps the previous identity filters for both writes and searches. It stays correct and performs as before until its helper is rebuilt. Replaced Topics move into their Scope's range as they are written.

The compatibility review in release/upgrade-support.json records the new persistence digest and these points.

Tests (in tests/builtin/persistence/test_topic_memory.py):

  • Replacing Topics in one Scope leaves another Scope's ranked hits and counts unchanged, and the replaced Scope returns exactly its current revisions.
  • A database whose helper is laid out as version 1 stays searchable with identical results before upgrade. Replacements work on it without leaving stale revisions. After unmanaged initialization it upgrades and keeps every Topic searchable.
  • A Scope whose rowid range fills up keeps accepting replacements and returns every current revision. The test shrinks the range width to reach this path.

Are there any user-facing changes?

No API, configuration or result changes. Topic FTS writes and searches on SQLite no longer slow down as other Scopes accumulate Topics. The persisted change is the helper's rowid layout and marker value (1 → 2). Unmanaged databases convert on first startup with this build, a one-time rebuild proportional to active Topic rows.

Older builds running against a converted unmanaged database refuse marker version 2, as before for unknown versions. Running an older build against a managed SQLite database after this build has written helper rows is not supported: rows that build adds receive global rowids outside their Scope's range. A helper rebuild repairs that layout.

How was this change tested?

Measurements were taken on macOS with SQLite 3.41.2, using one script run against upstream/master (b8b1890) and against this branch. Scope A holds one Topic. Each FTS table holds N rows spread across 500 other Scopes, and every row contains the query terms. Each value is the minimum of 7 runs. Scope A's results were 1 topic hit and 1 detail hit in every run.

N rows per table in other Scopes replace_many before after search (fts, "billing webhooks retry") before after
0 1.31 ms 1.27 ms 2.18 ms 1.10 ms
50,000 73.61 ms 1.21 ms 276.67 ms 11.78 ms
200,000 232.13 ms 1.31 ms 1,156.11 ms 38.01 ms

The remaining search time at 200,000 rows comes from bm25's table-wide document-frequency count, which FTS5 performs once per query term over the whole table. In a standalone FTS5 reproduction with the same rows, the range-bounded query took 0.3 ms without bm25() and 13–23 ms with it. Keeping scores identical requires keeping those statistics.

Other shapes (after this change):

  • Rows in Scope A itself (20,000 / 50,000, all matching): replace_many 18 / 44 ms, because the delete reads the Scope's own range. Search 188 / 492 ms, because every own row matches and is scored, as before.
  • A database that still holds version-1 rows (20,000 / 50,000 in other Scopes) uses the previous path. Before: replace_many 11.0–11.4 / 27.2–27.3 ms, search 45.7–46.1 / 124–126 ms. After: 11.8–12.0 / 27.5–28.3 ms and 46.2–46.7 / 122–128 ms, within run-to-run noise.

Result parity: 720 searches compared before and after. They covered 9 Scopes (including case-variant, non-ASCII and 200-character IDs) plus a missing Scope; 8 queries; candidate limits 3/20/100; and admission floors of none, 0.0 and 1.0. The corpus had multi-chunk Topics, batched and single replacements, and repeated revisions. The serialized TopicMemorySearchChannels (hits, raw bm25 scores, order, retrieved/eligible counts) were byte-identical.

Commands:

  • uv run python -m pytest tests/builtin/persistence/test_topic_memory.py tests/builtin/persistence/test_topic_memory_integrity.py tests/builtin/runtime/test_topic_memory_search.py tests/builtin/runtime/test_topic_memory_processing.py tests/builtin/runtime/test_topic_memory_security.py tests/builtin/persistence/test_artifact_current_eligibility.py tests/e2e/test_lexical_projection_upgrade.py tests/e2e/test_lexical_admission.py
  • uv run python -m pytest tests/builtin/persistence/test_full_server_migrations.py tests/builtin/persistence/test_release140_server_migrations.py tests/builtin/persistence/test_atomic_evidence_upgrade_history.py tests/builtin/persistence/test_candidate_schema_replay.py tests/test_upgrade_release_gate.py tests/test_migration_revision_names.py
  • make check (passed)
  • make unit-test: 8141 passed and 417 skipped. 4 failed in tests/test_ci_installation_roles.py; those fail identically on unmodified upstream/master on this machine, where the child virtual environment's Python aborts.

Mutation checks confirmed that the new tests fail in three cases: when the version-1 fallback is removed, when range compaction is removed, and when the scoped delete ignores the Topic identity.

Not validated:

  • Installed-release upgrades (tests/release_upgrades) and the full e2e suite were not run. Local migration tests exercise the s1400 rebuild path only through the in-repo chain.
  • This PR does not convert managed SQLite databases created by 1.4.1 or 1.5.0. Their write and search cost is unchanged until a Server maintenance step rebuilds the helper.
  • OceanBase and seekDB were not run; their Topic indexes are unchanged.
  • tox across Python versions was not run.

Alternatives considered

  • Indexed identity token, as in Atomic Memory ('i' || hex(scope_id) || 'x' || hex(artifact_id) with identity_token MATCH deletes and identity_token:"i<scope>x"* search). Rejected for three reasons:
    • It changes the registered FTS virtual table DDL, which requires a new Server revision on both source chains with new schema resources and fingerprints for every vector/Code profile.
    • The extra indexed token adds one token to every row's bm25 document length, which shifts raw scores (exposed through channel scores) and can reorder close results.
    • Its Scope prefix query expands one term per Topic in the Scope. Atomic Memory falls back to an unscoped match above 64 rows for that reason.
  • A separate indexed Scope token. It avoids prefix expansion but has the same DDL, revision and bm25 costs.
  • A registered maintenance revision in this PR to convert managed databases now. Deferred to a follow-up so that this change stays out of the shared revision chain. Managed databases stay correct on the previous path in the meantime.
  • Scope-local bm25 statistics to remove the remaining search cost. Rejected because it changes scores and ranking semantics.

AI usage statement

Claude Code, Claude Opus 5.5.

Copilot AI balanced review requested due to automatic review settings November 7, 2026 05:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 051edab. No correctness findings in the reviewed SQLite FTS paths. Merge readiness is blocked by a conflict in release/upgrade-support.json: git merge-tree against current master (89d960e) reproduces it. Please reconcile the compatibility rationale, refresh the persistence digest for the resolved tree, and rerun the release/upgrade checks before merging.

@hireview001 hireview001 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Resolve merge conflicts with the target branch.

… rowid ranges

The SQLite Topic FTS helper kept scope_id UNINDEXED, so replacing one
Topic scanned every Scope's rows and each search matched every Scope's
rows before filtering scope_id.

Helper version 2 hashes each Scope to its own 2**32-rowid range above
2**32. Replacement deletes and appends inside that range, and both
search statements bound their MATCH cursors to it. Virtual table DDL,
registered fingerprints and bm25's table-wide statistics are unchanged,
so search hits, scores and ordering are identical.

Unmanaged initialization and the existing s1400 domain step rebuild
version-1 helpers from the active Topic tables. A managed database that
still holds version-1 rows (below 2**32) keeps the previous identity
filters until its helper is rebuilt.
@Fengzdadi
Fengzdadi force-pushed the perf/topic-memory-sqlite-fts-scope-rowids branch from 051edab to b7dcaff Compare November 8, 2026 05:33
Copilot AI balanced review requested due to automatic review settings November 8, 2026 05:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@Fengzdadi

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Rebased onto master (ed8902b); the head is now b7dcaff.

  • Conflict: only release/upgrade-support.json. The resolution keeps master's rationale unchanged, including the new Topic Memory processing-diagnostics paragraph, and appends this PR's SQLite Topic FTS helper paragraph after it. The code and test patch is identical to 051edab apart from line offsets: master's 76d1f30 also edited tests/builtin/persistence/test_topic_memory.py, and it merged cleanly with this PR's tests.
  • Digest: persistence_sha256 is recomputed from the resolved tree with managed_digest (f8abed92…). scripts/upgrade_release_gate.py passes.
  • Checks rerun on b7dcaff:
    • make check.
    • tests/test_upgrade_release_gate.py, tests/test_migration_revision_names.py, tests/builtin/persistence/test_full_server_migrations.py, test_release140_server_migrations.py, test_atomic_evidence_upgrade_history.py, test_candidate_schema_replay.py.
    • The Topic suites: test_topic_memory.py, test_topic_memory_integrity.py, tests/builtin/runtime/test_topic_memory_{search,processing,security}.py, test_artifact_current_eligibility.py, tests/e2e/test_lexical_projection_upgrade.py, tests/e2e/test_lexical_admission.py.
    • Result: 329 passed, 58 skipped, 1 failed. The failure is test_candidate_schema_replay.py::test_candidate_replay_sqlite[rename] under xdist (maintenance.json not found). It fails the same way on unmodified master ed8902b and passes when run alone.
    • Installed-release upgrade acceptance (tests/release_upgrades) was not run locally.

)


def _scope_rowid_range(scope_id: str) -> tuple[int, int]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Scope 行区间这件事本身没有任何断言,退化成共享区间时测试全绿

三个新用例只断言「另一个 Scope 的结果不变」「替换后本 Scope 返回当前 revision」,因此无法区分「每个 Scope 一个 hashed 区间」和「所有 Scope 共用一个区间」这两种实现。

证据:在隔离镜像 D:\test\github\review\oceanbase-powercontext-pr-2532\probes\mutant_shared_band.py 里把 _scope_rowid_range 替换成常量 (2**32, 2**32 + 2**32 - 1)——即所有 Scope 落进同一个 band,scope_id 身份过滤全部保留、区间隔离完全消失——pytest tests/builtin/persistence/test_topic_memory.py -k sqlite_fts 仍然是 7 passed(WSL venv,Python 3.13,head b7dcaff)。也就是说本 PR 的核心目的被整体撤掉以后没有任何用例失败。

影响:这个改动只有性能语义,正文给出的 0 / 5 万 / 20 万行实测(replace_many 232.13 ms → 1.31 ms,search 1156.11 ms → 38.01 ms)不会在 CI 里复现,因此 CI 是这件事唯一的防线,而当前 CI 不检查分布。后续重构合并区间、把 _allocate_rowids 改回全局追加、或让 _insert_rebuilt_rows 用全局序号,都不会有任何测试变红。

建议补一条直接约束机制的用例(不冻结具体取值,只固定「每 Scope 一个区间」这个外部代价属性):

  • _scope_rowid_range 对两个固定 Scope id 返回不同的 first;
  • replace_many 之后回读 SELECT rowid, scope_id FROM pc_topic_memory_topic_fts,断言每个 Scope 的 rowid 都落在自己的 (first, last) 内,且两个 Scope 的 rowid 集合不相交。

附注:persistence_sha256 复核一致(f8abed92e6bff2a57b5416cf7b49f57ce1de10bd72c8809117210899409022df),正文与 rationale 对该 digest、对「bm25 统计仍为全表」、对降级不受支持的说明都与代码一致,此处不重复。

@Fengzdadi Fengzdadi Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, agreed. 18cd6cc adds _assert_scope_rowid_ranges. It reads rowid, scope_id from both FTS tables and asserts that each test Scope's _scope_rowid_range holds exactly that Scope's own rows: all of its rows are inside the range, and no other Scope's row is. It follows that the two Scopes' ranges differ, so the test doesn't check first values separately.

It runs on all three write paths:

  • incremental replacement (test_sqlite_fts_replacements_leave_other_scopes_results_unchanged);
  • the dense renumbering after a Scope's range fills (test_sqlite_fts_scope_keeps_replacing_topics_after_its_rowid_range_fills);
  • the version-1 rebuild in initialize, and a replacement after it (test_sqlite_fts_version_1_database_stays_searchable_before_and_after_upgrade).

Each regression you listed now fails a test; the previous tests passed all three:

  • One shared range (your probe): all three tests fail.
  • _allocate_rowids numbering like version 1 (table-wide max(rowid) + 1, starting at 1): the replacement and range-fill tests fail.
  • _insert_rebuilt_rows numbering globally from 1: the version-1 upgrade test fails.

Search results stay correct under all three: the scope_id filter still applies inside a shared range, and rows numbered from 1 switch the index to the version-1 fallback. Only an assertion on where the rows are placed can catch these regressions.

I also merged master (c4c95e4) in 04b4125; the commit you reviewed (b7dcaff) is unchanged. release/upgrade-support.json keeps master's rationale and appends this PR's paragraph. persistence_sha256 is recomputed for the merged tree (f0ffb8f5…), and scripts/upgrade_release_gate.py passes.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

在 head 18cd6cc 上复核:本条已修复。

新增的 _assert_scope_rowid_ranges(tests/builtin/persistence/test_topic_memory.py:1301)逐表断言「_scope_rowid_range(scope) 区间内的 rowid 集合 == 该 Scope 自己拥有的行」,并在替换后、v1 库升级前后、区间写满后四处调用。

实测(WSL Ubuntu / Python 3.13.11,镜像 D: est\github eview\oceanbase-powercontext-pr-2532\source�8cd6ccf,PYTHONPATH=<mirror>/src):

  • 未变异:-m pytest tests/builtin/persistence/test_topic_memory.py -k sqlite_fts -q ⇒ 7 passed / 7.15s;
  • 变异(用 pytest 插件把 _scope_rowid_range 换成所有 Scope 共用一个 band,脚本见 probes/degenerate_range_plugin.py)⇒ 3 failed / 4 passed,失败点就是 :1313 的断言,报出的多余 rowid 正是另一个 Scope 的行。

即该断言能检出「退化为共享区间」的实现,P2 关闭。

另一项缺口(不计入本 PR):该 head 的 tests (3.12, e2e) 红,7 个失败全部在 tests/e2e/test_atomic_memory_reconciliation_retry.py,断言 lineage 带 SourceSequenceLocator 而 receipt.source_ref.locator is None。成因是本分支基于 c4c95e46,早于 master 63f021d6 上的同名修复(git diff c4c95e46 refs/heads/master -- tests/e2e/test_atomic_memory_reconciliation_retry.py 有 19+/9-),与本 PR 的 SQLite FTS 改动无关。但它使 31 个 suite job 级联 skip,本 head 上该改动没有 e2e/OceanBase 验收证据。

@hireview001 hireview001 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Resolve merge conflicts with the target branch.

Copilot AI balanced review requested due to automatic review settings November 9, 2026 04:44

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@AlexStocks AlexStocks added the 1.5.2 v1.5.2 release tracking label Nov 9, 2026

@hireview001 hireview001 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 18cd6ccf. The merge conflict and persistence digest are fixed, and the new range assertions detect the shared-range regression. No new SQLite FTS correctness findings.

Merge remains blocked by CI. The seven e2e failures in test_atomic_memory_reconciliation_retry.py compare locator-bearing lineage with locator-free receipt references; I reproduced test_changed_workflow_revises_published_fact_and_preserves_history on both this head and unmodified base c4c95e46. Current master already corrects those expectations. Please incorporate that correction and rerun the required matrix: both unit jobs were cancelled and selected upgrade acceptance was skipped, leaving CI result and Upgrade release gate red.

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@hidb4ai
hidb4ai merged commit e64fc9d into oceanbase:master Nov 11, 2026
73 of 86 checks passed
jackie-cqz added a commit to jackie-cqz/powercontext that referenced this pull request Nov 12, 2026
Resolve the conflict with the SQLite Topic Memory per-Scope rowid ranges
(oceanbase#2532) and the 10 other commits that landed since the previous merge,
including the DSH plugin UI (oceanbase#2569), which also fixes the DSH runtime test
that failed on master.

- `release/upgrade-support.json`: keep the rationale sentence added upstream
  for the Topic Memory full-text helper, append the sentence about this
  branch's code-organization changes, and recompute the persistence digest
  after formatting. The generated table and index DDL for all 76 tables is
  identical to master on the SQLite and MySQL dialects.
- The new OpenCode service chain test passed the removed `scheduler_path`
  argument to `create_server_app`, so that argument is dropped.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

1.5.2 v1.5.2 release tracking

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants