From b7dcaffb321f36393d26405e3196928b1b451557 Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Sat, 7 Nov 2026 00:09:40 -0500 Subject: [PATCH 1/2] perf(topic-memory): scope SQLite FTS writes and searches to per-Scope 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. --- release/upgrade-support.json | 4 +- .../persistence/sqlite/topic_memory_index.py | 239 +++++++++++++----- .../builtin/persistence/test_topic_memory.py | 173 +++++++++++++ 3 files changed, 354 insertions(+), 62 deletions(-) diff --git a/release/upgrade-support.json b/release/upgrade-support.json index 68cdfbafd2..f8b50ca9e7 100644 --- a/release/upgrade-support.json +++ b/release/upgrade-support.json @@ -3,8 +3,8 @@ "target_version": "1.5.0", "mode": "upgrade-required", "schema_review": { - "persistence_sha256": "02dc8322b0f3440903e3831a41daf43307f2ec2cc77d6ec9cc3e63b3d4c98889", - "rationale": "Topic Memory processing failures attach bounded, content-free stage, reason and budget diagnostics to in-flight exceptions. Rejected reservations retain their existing durable charges; readback omits token-specific fields unless committed evidence establishes the limiting dimension, and repeated rejected calls cannot reinterpret prior evidence. Source structure and history-count guards do not imply context overflow. Missing FTS capability is configuration, and incomplete vector projections are business validation. No database schema, migration resource, registered table layout, frozen revision checksum, row encoding, persisted journal format or worker retry behavior is changed by these diagnostic annotations. The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. New Server revisions use software-version-plus-sequence names directly; software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum." + "persistence_sha256": "f8abed92e6bff2a57b5416cf7b49f57ce1de10bd72c8809117210899409022df", + "rationale": "Topic Memory processing failures attach bounded, content-free stage, reason and budget diagnostics to in-flight exceptions. Rejected reservations retain their existing durable charges; readback omits token-specific fields unless committed evidence establishes the limiting dimension, and repeated rejected calls cannot reinterpret prior evidence. Source structure and history-count guards do not imply context overflow. Missing FTS capability is configuration, and incomplete vector projections are business validation. No database schema, migration resource, registered table layout, frozen revision checksum, row encoding, persisted journal format or worker retry behavior is changed by these diagnostic annotations. The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. New Server revisions use software-version-plus-sequence names directly; software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum. SQLite Topic Memory full-text helper version 2 assigns each Scope's helper rows to a hashed 2^32-rowid range above every rowid that version 1 assigned, so Topic replacement and search bound their FTS5 cursors to one Scope's range. Virtual table definitions, registered schema fingerprints, migration resources and authoritative active Topic rows are unchanged. Unmanaged initialization and the existing s1400 domain step rebuild version-1 helper rows from the active tables with exact identities and revisions; a managed database that still holds version-1 helper rows keeps the previous identity filters until the helper is rebuilt. bm25 statistics remain table-wide, so search hits, ordering and scores are unchanged." }, "cases": [], "automatic_sources": { diff --git a/src/powercontext/builtin/persistence/sqlite/topic_memory_index.py b/src/powercontext/builtin/persistence/sqlite/topic_memory_index.py index 69f8e01fd7..a1a0028227 100644 --- a/src/powercontext/builtin/persistence/sqlite/topic_memory_index.py +++ b/src/powercontext/builtin/persistence/sqlite/topic_memory_index.py @@ -16,8 +16,9 @@ from __future__ import annotations +import hashlib import struct -from collections.abc import Mapping, Sequence +from collections.abc import Iterable, Mapping, Sequence from typing import Any from uuid import uuid4 @@ -28,15 +29,18 @@ String, Table, UniqueConstraint, + bindparam, column, delete, insert, select, table, text, + update, ) from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.ext.asyncio import AsyncConnection +from sqlalchemy.sql.elements import TextClause from powercontext.artifacts import ArtifactRef from powercontext.builtin.artifacts.memory import EmbeddingProfile @@ -121,37 +125,72 @@ searchable_text, tokenize='unicode61' ) """ -_DELETE_TOPIC_FTS_SQL = text( - "DELETE FROM pc_topic_memory_topic_fts WHERE scope_id = :scope_id AND artifact_id = :artifact_id" +# Version 2 places each Scope's rows in its own rowid range. FTS5 bounds MATCH +# cursors and scans by rowid, so writes and searches read one Scope's range +# instead of every Scope's matches; bm25 keeps its table-wide statistics. +# Version 1 numbered rows globally from 1. Ranges start at 2**32, so its rows +# stay recognizable until rebuilt or replaced; while any remain, writes and +# searches keep the version-1 identity filters. +_TOPIC_FTS_SCHEMA_VERSION = 2 +_REBUILD_BATCH_SIZE = 500 +_GLOBAL_ROWID_END = 1 << 32 +_SCOPE_ROWID_BITS = 32 +_MAX_ROWID = (1 << 63) - 1 +_TOPIC_FTS_COLUMNS = ("scope_id", "artifact_id", "revision", "title", "summary", "searchable_text") +_CHUNK_FTS_COLUMNS = ( + "scope_id", + "artifact_id", + "revision", + "chunk_ordinal", + "start_offset", + "title", + "summary", + "chunk_text", + "searchable_text", ) -_DELETE_CHUNK_FTS_SQL = text( - "DELETE FROM pc_topic_memory_chunk_fts WHERE scope_id = :scope_id AND artifact_id = :artifact_id" -) -_INSERT_TOPIC_FTS_SQL = text( - """ - INSERT INTO pc_topic_memory_topic_fts - (scope_id, artifact_id, revision, title, summary, searchable_text) - VALUES - (:scope_id, :artifact_id, :revision, :title, :summary, :searchable_text) - """ -) -_INSERT_CHUNK_FTS_SQL = text( - """ - INSERT INTO pc_topic_memory_chunk_fts - (scope_id, artifact_id, revision, chunk_ordinal, start_offset, - title, summary, chunk_text, searchable_text) - VALUES - (:scope_id, :artifact_id, :revision, :chunk_ordinal, :start_offset, - :title, :summary, :chunk_text, :searchable_text) - """ +_FTSTable = tuple[str, tuple[str, ...]] +_TOPIC_FTS_TABLE: _FTSTable = ("pc_topic_memory_topic_fts", _TOPIC_FTS_COLUMNS) +_CHUNK_FTS_TABLE: _FTSTable = ("pc_topic_memory_chunk_fts", _CHUNK_FTS_COLUMNS) +_FTS_TABLES = (_TOPIC_FTS_TABLE, _CHUNK_FTS_TABLE) +_HAS_GLOBAL_ROWS_SQL = text( + "SELECT EXISTS (SELECT 1 FROM pc_topic_memory_topic_fts WHERE rowid < :global_end) " + "OR EXISTS (SELECT 1 FROM pc_topic_memory_chunk_fts WHERE rowid < :global_end)" ) + + +def _scope_rowid_range(scope_id: str) -> tuple[int, int]: + """Return the inclusive rowid range shared by a Scope and its rare hash neighbours.""" + + size = 1 << _SCOPE_ROWID_BITS + digest = int.from_bytes(hashlib.sha256(scope_id.encode("utf-8")).digest()[:8], "big") + first = _GLOBAL_ROWID_END + digest % ((_MAX_ROWID + 1 - _GLOBAL_ROWID_END) // size) * size + return first, first + size - 1 + + +def _insert_fts_sql(table_name: str, columns: tuple[str, ...]) -> TextClause: + names = ", ".join(("rowid", *columns)) + values = ", ".join(f":{name}" for name in ("rowid", *columns)) + return text(f"INSERT INTO {table_name} ({names}) VALUES ({values})") # noqa: S608 + + +def _delete_fts_sql(table_name: str, *, scoped: bool) -> TextClause: + if not scoped: + return text(f"DELETE FROM {table_name} WHERE scope_id = :scope_id AND artifact_id = :artifact_id") # noqa: S608 + return text( + f"DELETE FROM {table_name} WHERE rowid BETWEEN :rowid_first AND :rowid_last " # noqa: S608 + "AND scope_id = :scope_id AND artifact_id IN :artifact_ids" + ).bindparams(bindparam("artifact_ids", expanding=True)) + + +_GLOBAL_SCOPE_FILTER = "scope_id = :scope_id" +_RANGE_SCOPE_FILTER = "rowid BETWEEN :rowid_first AND :rowid_last AND scope_id = :scope_id" _SEARCH_TOPIC_FTS_SQL = """ WITH scored AS MATERIALIZED ( SELECT rowid, artifact_id, revision, bm25(pc_topic_memory_topic_fts) AS raw_score, ({coverage}) AS coverage FROM pc_topic_memory_topic_fts - WHERE pc_topic_memory_topic_fts MATCH :query AND scope_id = :scope_id + WHERE pc_topic_memory_topic_fts MATCH :query AND {scope} ), candidates AS ( SELECT rowid, artifact_id, revision, raw_score FROM scored @@ -175,7 +214,7 @@ bm25(pc_topic_memory_chunk_fts) AS raw_score, ({coverage}) AS coverage FROM pc_topic_memory_chunk_fts - WHERE pc_topic_memory_chunk_fts MATCH :query AND scope_id = :scope_id + WHERE pc_topic_memory_chunk_fts MATCH :query AND {scope} ), ranked AS ( SELECT scored.*, row_number() OVER ( @@ -300,17 +339,17 @@ async def initialize(self, connection: AsyncConnection, /) -> None: ) ) marker = await connection.scalar(select(SQLITE_TOPIC_MEMORY_FTS_MARKER_TABLE.c.schema_version)) - if marker == 1 and existing == 2: + if marker == _TOPIC_FTS_SCHEMA_VERSION and existing == 2: return - if marker is not None and marker != 1: + if marker not in {None, 1, _TOPIC_FTS_SCHEMA_VERSION}: raise TopicMemoryCapabilityError("sqlite-fts", "unsupported Topic FTS schema version") await connection.exec_driver_sql(_CREATE_TOPIC_FTS_SQL) await connection.exec_driver_sql(_CREATE_CHUNK_FTS_SQL) + # Version 1 and missing helpers rebuild from the authoritative active rows. await connection.exec_driver_sql("DELETE FROM pc_topic_memory_topic_fts") await connection.exec_driver_sql("DELETE FROM pc_topic_memory_chunk_fts") topics = (await connection.execute(select(TOPIC_MEMORY_ACTIVE_TOPICS_TABLE))).mappings() - for row in topics: - await connection.execute(_INSERT_TOPIC_FTS_SQL, _topic_fts_values(row)) + await _insert_rebuilt_rows(connection, _TOPIC_FTS_TABLE, topics) chunks = ( await connection.execute( select( @@ -325,13 +364,20 @@ async def initialize(self, connection: AsyncConnection, /) -> None: ) ) ).mappings() - for row in chunks: - await connection.execute(_INSERT_CHUNK_FTS_SQL, _chunk_fts_values(row)) + await _insert_rebuilt_rows(connection, _CHUNK_FTS_TABLE, chunks) await connection.exec_driver_sql( "SELECT rowid FROM pc_topic_memory_topic_fts WHERE pc_topic_memory_topic_fts MATCH 'powercontext'" ) if marker is None: - await connection.execute(insert(SQLITE_TOPIC_MEMORY_FTS_MARKER_TABLE).values(singleton=1, schema_version=1)) + await connection.execute( + insert(SQLITE_TOPIC_MEMORY_FTS_MARKER_TABLE).values( + singleton=1, schema_version=_TOPIC_FTS_SCHEMA_VERSION + ) + ) + else: + await connection.execute( + update(SQLITE_TOPIC_MEMORY_FTS_MARKER_TABLE).values(schema_version=_TOPIC_FTS_SCHEMA_VERSION) + ) async def replace( self, @@ -352,14 +398,26 @@ async def replace_many( ) -> None: if not items: return - identities = [{"scope_id": scope_id, "artifact_id": ref.artifact_id} for ref, _ in items] - await connection.execute(_DELETE_TOPIC_FTS_SQL, identities) - await connection.execute(_DELETE_CHUNK_FTS_SQL, identities) + first, last = _scope_rowid_range(scope_id) + artifact_ids = [ref.artifact_id for ref, _ in items] + global_rows = await _has_global_rows(connection) + for table_name, _columns in _FTS_TABLES: + if global_rows: + await connection.execute( + _delete_fts_sql(table_name, scoped=False), + [{"scope_id": scope_id, "artifact_id": artifact_id} for artifact_id in artifact_ids], + ) + else: + await connection.execute( + _delete_fts_sql(table_name, scoped=True), + {"rowid_first": first, "rowid_last": last, "scope_id": scope_id, "artifact_ids": artifact_ids}, + ) topics = [] chunks = [] - for (ref, projection), identity in zip(items, identities, strict=True): + for ref, projection in items: values = { - **identity, + "scope_id": scope_id, + "artifact_id": ref.artifact_id, "revision": ref.revision, "title": projection.content.title, "summary": projection.content.summary, @@ -376,9 +434,14 @@ async def replace_many( } for chunk in projection.chunks ) - await connection.execute(_INSERT_TOPIC_FTS_SQL, topics) - if chunks: - await connection.execute(_INSERT_CHUNK_FTS_SQL, chunks) + for fts_table, rows in zip(_FTS_TABLES, (topics, chunks), strict=True): + if not rows: + continue + rowid = await _allocate_rowids(connection, fts_table, first, last, len(rows)) + await connection.execute( + _insert_fts_sql(*fts_table), + [{**row, "rowid": rowid + offset} for offset, row in enumerate(rows)], + ) async def search( self, @@ -399,18 +462,26 @@ async def search( f"CASE WHEN instr(' ' || searchable_text || ' ', :coverage_term_{position}) > 0 THEN 1 ELSE 0 END" for position, _term in enumerate(query_terms) ) + first, last = _scope_rowid_range(scope_id) + scope = _GLOBAL_SCOPE_FILTER if await _has_global_rows(connection) else _RANGE_SCOPE_FILTER parameters = { "query": query, "scope_id": scope_id, + "rowid_first": first, + "rowid_last": last, "candidate_limit": request.candidate_limit, "required_matches": required_matches, **{f"coverage_term_{position}": f" {term} " for position, term in enumerate(query_terms)}, } topic_rows = tuple( - (await connection.execute(text(_SEARCH_TOPIC_FTS_SQL.format(coverage=coverage)), parameters)).mappings() + ( + await connection.execute(text(_SEARCH_TOPIC_FTS_SQL.format(coverage=coverage, scope=scope)), parameters) + ).mappings() ) chunk_rows = tuple( - (await connection.execute(text(_SEARCH_CHUNK_FTS_SQL.format(coverage=coverage)), parameters)).mappings() + ( + await connection.execute(text(_SEARCH_CHUNK_FTS_SQL.format(coverage=coverage, scope=scope)), parameters) + ).mappings() ) topic_hits = tuple(_channel_hit(row, "topic_fts") for row in topic_rows if not row["is_rejected"]) chunk_hits = tuple(_channel_hit(row, "detail_fts") for row in chunk_rows if not row["is_rejected"]) @@ -668,25 +739,73 @@ async def _delete_existing(self, connection: AsyncConnection, scope_id: str, art ) -def _topic_fts_values(row: Mapping[Any, Any]) -> dict[str, object]: - return {key: row[key] for key in ("scope_id", "artifact_id", "revision", "title", "summary", "searchable_text")} - - -def _chunk_fts_values(row: Mapping[Any, Any]) -> dict[str, object]: - return { - key: row[key] - for key in ( - "scope_id", - "artifact_id", - "revision", - "chunk_ordinal", - "start_offset", - "title", - "summary", - "chunk_text", - "searchable_text", +async def _has_global_rows(connection: AsyncConnection) -> bool: + """Whether version-1 rows remain; only the identity filters find them outside Scope ranges.""" + + return bool(await connection.scalar(_HAS_GLOBAL_ROWS_SQL, {"global_end": _GLOBAL_ROWID_END})) + + +async def _insert_rebuilt_rows( + connection: AsyncConnection, fts_table: _FTSTable, rows: Iterable[Mapping[Any, Any]] +) -> None: + table_name, columns = fts_table + next_rowids: dict[int, int] = {} + batch: list[dict[str, object]] = [] + for row in rows: + # Hash neighbours share a range, so allocation is keyed by the range. + first, last = _scope_rowid_range(row["scope_id"]) + rowid = next_rowids.get(first, first) + if rowid > last: + raise TopicMemoryCapabilityError("sqlite-fts", "a Scope exceeds its Topic FTS rowid range") + next_rowids[first] = rowid + 1 + batch.append({"rowid": rowid, **{name: row[name] for name in columns}}) + if len(batch) == _REBUILD_BATCH_SIZE: + await connection.execute(_insert_fts_sql(table_name, columns), batch) + batch = [] + if batch: + await connection.execute(_insert_fts_sql(table_name, columns), batch) + + +async def _allocate_rowids(connection: AsyncConnection, fts_table: _FTSTable, first: int, last: int, count: int) -> int: + """Return the first of ``count`` free consecutive rowids in a Scope range.""" + + table_name, columns = fts_table + bounds = {"rowid_first": first, "rowid_last": last} + top = await connection.scalar( + text( + f"SELECT rowid FROM {table_name} WHERE rowid BETWEEN :rowid_first AND :rowid_last " # noqa: S608 + "ORDER BY rowid DESC LIMIT 1" + ), + bounds, + ) + start = first if top is None else int(top) + 1 + if start + count - 1 <= last: + return start + # Replacements always append, so a long-lived Scope can reach the end of + # its range while most earlier rowids are free. Renumber its rows densely. + names = ", ".join(columns) + rows = ( + await connection.execute( + text( + f"SELECT {names} FROM {table_name} WHERE rowid BETWEEN :rowid_first AND :rowid_last " # noqa: S608 + "ORDER BY rowid" + ), + bounds, + ) + ).mappings() + retained = [dict(row) for row in rows] + if len(retained) + count > last - first + 1: + raise TopicMemoryCapabilityError("sqlite-fts", "a Scope exceeds its Topic FTS rowid range") + await connection.execute( + text(f"DELETE FROM {table_name} WHERE rowid BETWEEN :rowid_first AND :rowid_last"), # noqa: S608 + bounds, + ) + if retained: + await connection.execute( + _insert_fts_sql(table_name, columns), + [{**row, "rowid": first + offset} for offset, row in enumerate(retained)], ) - } + return first + len(retained) def _channel_hit(row: Mapping[Any, Any], channel: TopicMemoryMatchedBy) -> TopicMemoryChannelHit: diff --git a/tests/builtin/persistence/test_topic_memory.py b/tests/builtin/persistence/test_topic_memory.py index c0f8373f30..96c02fb615 100644 --- a/tests/builtin/persistence/test_topic_memory.py +++ b/tests/builtin/persistence/test_topic_memory.py @@ -57,7 +57,9 @@ from powercontext.builtin.persistence.records import RelationalRecordService from powercontext.builtin.persistence.sources import SourceRepository from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.persistence.sqlite import topic_memory_index as sqlite_topic_memory_index from powercontext.builtin.persistence.sqlite.topic_memory_index import ( + SQLITE_TOPIC_MEMORY_FTS_MARKER_TABLE, SQLITE_TOPIC_MEMORY_VECTOR_CHUNKS_TABLE, SQLITE_TOPIC_MEMORY_VECTOR_TOPICS_TABLE, SQLiteTopicMemoryFTSIndex, @@ -1248,6 +1250,177 @@ async def scenario() -> None: asyncio.run(scenario()) +_SHARED_FTS_REQUEST = TopicMemorySearchRequest(query="shared amber", candidate_limit=20, mode="fts") + + +async def _publish_shared_topics( + repository: TopicMemoryRepository, connection: AsyncConnection, scope_ids: Sequence[str], count: int +) -> dict[tuple[str, str], TopicMemory]: + topics = {} + for scope_id in scope_ids: + for position in range(count): + content = _content(f"Shared {scope_id} {position}", "amber") + published = await repository.publish_create( + connection, scope_id, f"topic-{position}", _draft(content), prepare_topic_memory_projection(content) + ) + topics[scope_id, f"topic-{position}"] = published.topic + return topics + + +async def _revise_shared_topic( + repository: TopicMemoryRepository, connection: AsyncConnection, scope_id: str, current: TopicMemory +) -> TopicMemory: + content = _content(f"Shared {scope_id} {current.artifact_id} r{current.revision + 1}", "amber") + draft = _draft(content, artifacts=(current.as_ref(),)) + published = await repository.publish_revision( + connection, scope_id, current, draft, prepare_topic_memory_projection(content) + ) + return published.topic + + +def _fts_refs(channels: TopicMemorySearchChannels) -> tuple[list[tuple[str, int]], list[tuple[str, int]]]: + return ( + sorted((hit.artifact_ref.artifact_id, hit.artifact_ref.revision) for hit in channels.topic_fts), + sorted((hit.artifact_ref.artifact_id, hit.artifact_ref.revision) for hit in channels.detail_fts), + ) + + +def _ranked_fts(channels: TopicMemorySearchChannels) -> tuple[object, ...]: + # bm25 statistics span the whole table, so another Scope's writes may move + # raw scores; ranked identities and admission counts must not change. + return ( + tuple((hit.artifact_ref, hit.chunk_ordinal, hit.chunk_text) for hit in channels.topic_fts), + tuple((hit.artifact_ref, hit.chunk_ordinal, hit.chunk_text) for hit in channels.detail_fts), + channels.topic_fts_retrieved, + channels.detail_fts_retrieved, + channels.topic_fts_eligible, + channels.detail_fts_eligible, + ) + + +def test_sqlite_fts_replacements_leave_other_scopes_results_unchanged(tmp_path: Path) -> None: + async def scenario() -> None: + index = SQLiteTopicMemoryFTSIndex() + repository = TopicMemoryRepository(index=CompositeTopicMemoryIndex(index)) + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'fts-scopes.db'}") + async with SQLiteProfile.open(config, tables=BUILTIN_TABLES + index.tables) as profile: + async with profile.database.transaction() as connection: + await repository.initialize(connection) + topics = await _publish_shared_topics(repository, connection, ("scope-a", "scope-b"), 3) + other_before = await index.search(connection, "scope-b", _SHARED_FTS_REQUEST) + for _ in range(3): + for artifact_id in ("topic-0", "topic-2"): + async with profile.database.transaction() as connection: + topics["scope-a", artifact_id] = await _revise_shared_topic( + repository, connection, "scope-a", topics["scope-a", artifact_id] + ) + async with profile.database.transaction() as connection: + other_after = await index.search(connection, "scope-b", _SHARED_FTS_REQUEST) + revised = await index.search(connection, "scope-a", _SHARED_FTS_REQUEST) + + assert _ranked_fts(other_after) == _ranked_fts(other_before) + assert _fts_refs(revised) == ([("topic-0", 4), ("topic-1", 1), ("topic-2", 4)],) * 2 + assert revised.topic_fts_retrieved == revised.detail_fts_retrieved == 3 + + asyncio.run(scenario()) + + +def test_sqlite_fts_version_1_database_stays_searchable_before_and_after_upgrade(tmp_path: Path) -> None: + async def scenario() -> None: + index = SQLiteTopicMemoryFTSIndex() + repository = TopicMemoryRepository(index=CompositeTopicMemoryIndex(index)) + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'fts-v1.db'}") + async with SQLiteProfile.open(config, tables=BUILTIN_TABLES + index.tables) as profile: + async with profile.database.transaction() as connection: + await repository.initialize(connection) + topics = await _publish_shared_topics(repository, connection, ("scope-a", "scope-b"), 2) + expected = { + scope_id: await index.search(connection, scope_id, _SHARED_FTS_REQUEST) + for scope_id in ("scope-a", "scope-b") + } + # Version 1 numbered every Scope's rows from one global sequence. + for statement in ( + "CREATE TEMP TABLE v1_topics AS SELECT * FROM pc_topic_memory_topic_fts", + "CREATE TEMP TABLE v1_chunks AS SELECT * FROM pc_topic_memory_chunk_fts", + "DELETE FROM pc_topic_memory_topic_fts", + "DELETE FROM pc_topic_memory_chunk_fts", + "INSERT INTO pc_topic_memory_topic_fts SELECT * FROM v1_topics", + "INSERT INTO pc_topic_memory_chunk_fts SELECT * FROM v1_chunks", + ): + await connection.exec_driver_sql(statement) + await connection.execute(update(SQLITE_TOPIC_MEMORY_FTS_MARKER_TABLE).values(schema_version=1)) + async with profile.database.transaction() as connection: + # Managed startup validates only, so version-1 rows must stay usable unconverted. + for scope_id, channels in expected.items(): + assert await index.search(connection, scope_id, _SHARED_FTS_REQUEST) == channels + topics["scope-a", "topic-0"] = await _revise_shared_topic( + repository, connection, "scope-a", topics["scope-a", "topic-0"] + ) + assert ( + _fts_refs(await index.search(connection, "scope-a", _SHARED_FTS_REQUEST)) + == ([("topic-0", 2), ("topic-1", 1)],) * 2 + ) + assert _ranked_fts(await index.search(connection, "scope-b", _SHARED_FTS_REQUEST)) == _ranked_fts( + expected["scope-b"] + ) + async with ( + SQLiteProfile.open(config, tables=BUILTIN_TABLES + index.tables) as profile, + profile.database.transaction() as connection, + ): + await repository.initialize(connection) + upgraded = await index.search(connection, "scope-a", _SHARED_FTS_REQUEST) + assert _ranked_fts(await index.search(connection, "scope-b", _SHARED_FTS_REQUEST)) == _ranked_fts( + expected["scope-b"] + ) + topics["scope-a", "topic-1"] = await _revise_shared_topic( + repository, connection, "scope-a", topics["scope-a", "topic-1"] + ) + assert ( + _fts_refs(await index.search(connection, "scope-a", _SHARED_FTS_REQUEST)) + == ([("topic-0", 2), ("topic-1", 2)],) * 2 + ) + assert _ranked_fts(await index.search(connection, "scope-b", _SHARED_FTS_REQUEST)) == _ranked_fts( + expected["scope-b"] + ) + assert _fts_refs(upgraded) == ([("topic-0", 2), ("topic-1", 1)],) * 2 + + asyncio.run(scenario()) + + +def test_sqlite_fts_scope_keeps_replacing_topics_after_its_rowid_range_fills( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # Shrink each Scope's range so repeated appends exhaust it within the test. + monkeypatch.setattr(sqlite_topic_memory_index, "_SCOPE_ROWID_BITS", 2) + + async def scenario() -> None: + index = SQLiteTopicMemoryFTSIndex() + repository = TopicMemoryRepository(index=CompositeTopicMemoryIndex(index)) + async with ( + SQLiteProfile.open(SQLiteConfig(), tables=BUILTIN_TABLES + index.tables) as profile, + profile.database.transaction() as connection, + ): + await repository.initialize(connection) + topics = await _publish_shared_topics(repository, connection, ("scope-a", "scope-b"), 2) + other = await index.search(connection, "scope-b", _SHARED_FTS_REQUEST) + for _ in range(3): + for artifact_id in ("topic-0", "topic-1"): + topics["scope-a", artifact_id] = await _revise_shared_topic( + repository, connection, "scope-a", topics["scope-a", artifact_id] + ) + current = sorted( + (topic.artifact_id, topic.revision) + for (scope, _), topic in topics.items() + if scope == "scope-a" + ) + revised = await index.search(connection, "scope-a", _SHARED_FTS_REQUEST) + assert _fts_refs(revised) == (current, current) + assert _ranked_fts(await index.search(connection, "scope-b", _SHARED_FTS_REQUEST)) == _ranked_fts(other) + assert _fts_refs(revised) == ([("topic-0", 4), ("topic-1", 4)],) * 2 + + asyncio.run(scenario()) + + def test_retrieval_shape_is_persistent_and_rejects_bidirectional_downgrades(tmp_path: Path) -> None: async def scenario() -> None: embedding_profile = EmbeddingProfile( From 18cd6ccf49ff1920a012bc786ecfaf2a96d032b3 Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Sun, 8 Nov 2026 23:39:57 -0500 Subject: [PATCH 2/2] test(topic-memory): assert each Scope's FTS rows stay in its rowid range --- .../builtin/persistence/test_topic_memory.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tests/builtin/persistence/test_topic_memory.py b/tests/builtin/persistence/test_topic_memory.py index 96c02fb615..a13c3dda17 100644 --- a/tests/builtin/persistence/test_topic_memory.py +++ b/tests/builtin/persistence/test_topic_memory.py @@ -1298,6 +1298,21 @@ def _ranked_fts(channels: TopicMemorySearchChannels) -> tuple[object, ...]: ) +async def _assert_scope_rowid_ranges(connection: AsyncConnection, scope_ids: Sequence[str]) -> None: + # Range bounds, not the scope_id filter, are what keep FTS5 from reading + # other Scopes, so each test Scope's range must hold exactly its own rows. + for statement in ( + "SELECT rowid, scope_id FROM pc_topic_memory_topic_fts", + "SELECT rowid, scope_id FROM pc_topic_memory_chunk_fts", + ): + rows = (await connection.exec_driver_sql(statement)).all() + for scope_id in scope_ids: + first, last = sqlite_topic_memory_index._scope_rowid_range(scope_id) + own = {rowid for rowid, owner in rows if owner == scope_id} + assert own + assert own == {rowid for rowid, _ in rows if first <= rowid <= last} + + def test_sqlite_fts_replacements_leave_other_scopes_results_unchanged(tmp_path: Path) -> None: async def scenario() -> None: index = SQLiteTopicMemoryFTSIndex() @@ -1317,6 +1332,7 @@ async def scenario() -> None: async with profile.database.transaction() as connection: other_after = await index.search(connection, "scope-b", _SHARED_FTS_REQUEST) revised = await index.search(connection, "scope-a", _SHARED_FTS_REQUEST) + await _assert_scope_rowid_ranges(connection, ("scope-a", "scope-b")) assert _ranked_fts(other_after) == _ranked_fts(other_before) assert _fts_refs(revised) == ([("topic-0", 4), ("topic-1", 1), ("topic-2", 4)],) * 2 @@ -1368,6 +1384,7 @@ async def scenario() -> None: profile.database.transaction() as connection, ): await repository.initialize(connection) + await _assert_scope_rowid_ranges(connection, ("scope-a", "scope-b")) upgraded = await index.search(connection, "scope-a", _SHARED_FTS_REQUEST) assert _ranked_fts(await index.search(connection, "scope-b", _SHARED_FTS_REQUEST)) == _ranked_fts( expected["scope-b"] @@ -1379,6 +1396,7 @@ async def scenario() -> None: _fts_refs(await index.search(connection, "scope-a", _SHARED_FTS_REQUEST)) == ([("topic-0", 2), ("topic-1", 2)],) * 2 ) + await _assert_scope_rowid_ranges(connection, ("scope-a", "scope-b")) assert _ranked_fts(await index.search(connection, "scope-b", _SHARED_FTS_REQUEST)) == _ranked_fts( expected["scope-b"] ) @@ -1416,6 +1434,7 @@ async def scenario() -> None: revised = await index.search(connection, "scope-a", _SHARED_FTS_REQUEST) assert _fts_refs(revised) == (current, current) assert _ranked_fts(await index.search(connection, "scope-b", _SHARED_FTS_REQUEST)) == _ranked_fts(other) + await _assert_scope_rowid_ranges(connection, ("scope-a", "scope-b")) assert _fts_refs(revised) == ([("topic-0", 4), ("topic-1", 4)],) * 2 asyncio.run(scenario())