From 93495aecd781f6fc36b70b0a9eac4b64c9642272 Mon Sep 17 00:00:00 2001 From: Rongfeng Fu Date: Tue, 8 Sep 2026 18:32:57 +0800 Subject: [PATCH 1/5] fix(topic-memory): guard stale runtimes and reuse worker indexes Co-authored-by: multica-agent --- docs/en/docs/reference/configuration.md | 6 + ...0_topic_memory.md => 1417_topic_memory.md} | 1 + docs/en/rfcs/1485_profile_artifact.md | 4 +- ...-artifact-processing-persistence-design.md | 6 +- docs/zh/docs/reference/configuration.md | 5 + ...0_topic_memory.md => 1417_topic_memory.md} | 1 + docs/zh/rfcs/1485_profile_artifact.md | 4 +- .../oceanbase/topic_memory_index.py | 3 + .../persistence/sqlite/topic_memory_index.py | 9 + .../builtin/persistence/topic_memory.py | 88 ++++++-- .../builtin/runtime/composition.py | 15 +- .../runtime/topic_memory_processing.py | 4 +- .../builtin/persistence/test_topic_memory.py | 211 +++++++++++++++++- .../test_topic_memory_oceanbase.py | 10 +- .../runtime/test_composition_embedding.py | 124 ++++++++++ .../runtime/test_topic_memory_processing.py | 22 +- 16 files changed, 471 insertions(+), 42 deletions(-) rename docs/en/rfcs/{0000_topic_memory.md => 1417_topic_memory.md} (99%) rename docs/zh/rfcs/{0000_topic_memory.md => 1417_topic_memory.md} (99%) diff --git a/docs/en/docs/reference/configuration.md b/docs/en/docs/reference/configuration.md index e832049f85..8643e1b7e4 100644 --- a/docs/en/docs/reference/configuration.md +++ b/docs/en/docs/reference/configuration.md @@ -236,6 +236,12 @@ Memory, Experience, and Profile APScheduler jobs belong exclusively to `all`: co `POWERCONTEXT_SERVER_RUNTIME_PROFILE_SCHEDULE_ENABLED` with either split role is rejected at startup. Keep `all` when those jobs are required; assigning them to a separate process is outside the current split-role contract. +Normal Runtime startup initializes and recovers the configured search indexes. Topic Workers reuse that database +without rebuilding the unrelated Memory/Experience search projections for each Window; Topic index validation and +publication guards still apply. If an empty database is reconfigured to another Topic retrieval shape or embedding +profile, reopen existing Runtimes with the same configuration: stale Runtimes reject Topic search, exact get, and +current-head browsing with a retrieval-shape error instead of reading another vector space. + Provider credentials, such as `OPENAI_API_KEY`, are read by the configured inference provider. Do not place secrets in command-line arguments, documentation, or Memory. Replace `provider:model-name` with a model identifier supported by Pydantic AI. Scheduled extraction requires both a generation model and diff --git a/docs/en/rfcs/0000_topic_memory.md b/docs/en/rfcs/1417_topic_memory.md similarity index 99% rename from docs/en/rfcs/0000_topic_memory.md rename to docs/en/rfcs/1417_topic_memory.md index a8f680f14b..20e328bd11 100644 --- a/docs/en/rfcs/0000_topic_memory.md +++ b/docs/en/rfcs/1417_topic_memory.md @@ -1,3 +1,4 @@ +- RFC ID: 1417 - Proposal Name: `topic_memory` - Start Date: 2026-09-01 - RFC PR: [oceanbase/powercontext#1417](https://github.com/oceanbase/powercontext/pull/1417) diff --git a/docs/en/rfcs/1485_profile_artifact.md b/docs/en/rfcs/1485_profile_artifact.md index 6f98437f36..847926c1d6 100644 --- a/docs/en/rfcs/1485_profile_artifact.md +++ b/docs/en/rfcs/1485_profile_artifact.md @@ -3,7 +3,7 @@ - RFC PR: [oceanbase/powercontext#1485](https://github.com/oceanbase/powercontext/pull/1485) - Related RFCs: [Scope organization](1345_scope_organization_and_agent_integration.md), [Access control](1396_handoff_access_control.md), [Source and Artifact REST API](1437_source_artifact_rest_api.md), - [Candidate review](0050_artifact_candidate_review_inbox.md), [Topic Memory](0000_topic_memory.md) + [Candidate review](0050_artifact_candidate_review_inbox.md), [Topic Memory](1417_topic_memory.md) # Summary @@ -854,7 +854,7 @@ general batch operations. - PowerContext [base REST API](1437_source_artifact_rest_api.md) supplies Source/Artifact identity, atomic commits, ETags, and lineage_only; the [Scope RFC](1345_scope_organization_and_agent_integration.md) supplies ordinary Scopes and Bindings. - The [Candidate Review RFC](0050_artifact_candidate_review_inbox.md) supplies candidate versions and review lifecycle; - [Topic Memory](0000_topic_memory.md) provides independent Source-window consumer references. This design does not depend on its proposed task tables. + [Topic Memory](1417_topic_memory.md) provides independent Source-window consumer references. This design does not depend on its proposed task tables. - [TencentDB Agent Memory](https://github.com/TencentCloud/TencentDB-Agent-Memory#technical-implementation) uses layered asynchronous processing, and [OpenViking Session](https://github.com/volcengine/OpenViking/tree/main/openviking/session) provides session-processing references for accumulating evidence into long-term memory. This RFC uses PowerContext's own Scope, Cursor, and transaction contracts. diff --git a/docs/superpowers/specs/2026-09-04-artifact-processing-persistence-design.md b/docs/superpowers/specs/2026-09-04-artifact-processing-persistence-design.md index 0b5c0c926e..22bcc8ad18 100644 --- a/docs/superpowers/specs/2026-09-04-artifact-processing-persistence-design.md +++ b/docs/superpowers/specs/2026-09-04-artifact-processing-persistence-design.md @@ -2,7 +2,7 @@ ## Scope -Implement only the persistent primitives required by RFC 0000 before the Artifact Processing Supervisor exists. +Implement only the persistent primitives required by RFC 1417 before the Artifact Processing Supervisor exists. Topic Memory is the first binding, named `topic-memory-source-window`. This milestone reuses the existing scoped Source Journal (`pc_sources` and `pc_source_journal_heads`) and the existing @@ -14,7 +14,7 @@ workers, automatic waves, retries, scheduling state, Topic generation, projectio ## Storage -Add `pc_artifact_processing_pending` exactly as specified by RFC 0000: +Add `pc_artifact_processing_pending` exactly as specified by RFC 1417: - primary key: `(binding_name, scope_id)`; - `source_through >= 1`; @@ -71,5 +71,5 @@ Tests cover only RFC-visible behavior: ## Boundary escalation rule During review, any proposed persistence field, lock, retry, security check, validation rule, or failure state absent from -RFC 0000 must be rejected when the RFC explicitly excludes it. If the RFC is silent and the mechanism would change the +RFC 1417 must be rejected when the RFC explicitly excludes it. If the RFC is silent and the mechanism would change the contract or operational trade-off, implementation pauses for human confirmation. diff --git a/docs/zh/docs/reference/configuration.md b/docs/zh/docs/reference/configuration.md index 31b6937d05..4ce5025557 100644 --- a/docs/zh/docs/reference/configuration.md +++ b/docs/zh/docs/reference/configuration.md @@ -212,6 +212,11 @@ model 的配置会在声明处理能力之前被拒绝。请通过 `POWERCONTEXT `POWERCONTEXT_SERVER_RUNTIME_PROFILE_SCHEDULE_ENABLED` 同时配置时,进程会在启动阶段明确拒绝。需要这些旧作业时应继续 使用 `all`;把旧作业分配到独立进程不属于当前 split-role 合同。 +普通 Runtime 启动会初始化并恢复所配置的检索索引。Topic Worker 复用该数据库,不再为每个 Window 重建无关的 +Memory/Experience 检索投影;Topic 索引校验与发布守卫仍然执行。如果空库切换了 Topic 检索形态或 Embedding +profile,应使用相同配置重新打开已有 Runtime;旧 Runtime 会以 retrieval-shape 错误拒绝 Topic 搜索、精确读取和 +当前 Head 浏览,而不是读取另一个向量空间。 + 指定 SQLite 路径并启用定时提取的示例: ```bash diff --git a/docs/zh/rfcs/0000_topic_memory.md b/docs/zh/rfcs/1417_topic_memory.md similarity index 99% rename from docs/zh/rfcs/0000_topic_memory.md rename to docs/zh/rfcs/1417_topic_memory.md index 1f5f62d2b0..1236f70094 100644 --- a/docs/zh/rfcs/0000_topic_memory.md +++ b/docs/zh/rfcs/1417_topic_memory.md @@ -1,3 +1,4 @@ +- RFC ID: 1417 - Proposal Name: `topic_memory` - Start Date: 2026-09-01 - RFC PR: [oceanbase/powercontext#1417](https://github.com/oceanbase/powercontext/pull/1417) diff --git a/docs/zh/rfcs/1485_profile_artifact.md b/docs/zh/rfcs/1485_profile_artifact.md index 8115487ce0..f1ee7fdeec 100644 --- a/docs/zh/rfcs/1485_profile_artifact.md +++ b/docs/zh/rfcs/1485_profile_artifact.md @@ -3,7 +3,7 @@ - RFC PR: [oceanbase/powercontext#1485](https://github.com/oceanbase/powercontext/pull/1485) - Related RFCs: [Scope organization](1345_scope_organization_and_agent_integration.md), [Access control](1396_handoff_access_control.md), [Source and Artifact REST API](1437_source_artifact_rest_api.md), - [Candidate review](0050_artifact_candidate_review_inbox.md), [Topic Memory](0000_topic_memory.md) + [Candidate review](0050_artifact_candidate_review_inbox.md), [Topic Memory](1417_topic_memory.md) # Summary @@ -782,7 +782,7 @@ Source journal 和 Candidate 重建,因此不新增 pending、lease、projecti - PowerContext [基础 REST API](1437_source_artifact_rest_api.md)提供 Source/Artifact 身份、原子提交、ETag 和 lineage_only; [Scope RFC](1345_scope_organization_and_agent_integration.md)提供普通 Scope 与 Binding。 - [Candidate Review RFC](0050_artifact_candidate_review_inbox.md)提供候选版本与审核生命周期; - [Topic Memory RFC](0000_topic_memory.md)提供独立 Source-window consumer 的参考。本设计不依赖其拟新增的任务表。 + [Topic Memory RFC](1417_topic_memory.md)提供独立 Source-window consumer 的参考。本设计不依赖其拟新增的任务表。 - [TencentDB Agent Memory](https://github.com/TencentCloud/TencentDB-Agent-Memory#technical-implementation)的分层异步处理, 以及 [OpenViking Session](https://github.com/volcengine/OpenViking/tree/main/openviking/session)的会话处理, 为证据累积后更新长期记忆提供参考;本设计采用 PowerContext 自己的 Scope、Cursor 和事务契约。 diff --git a/src/powercontext/builtin/persistence/oceanbase/topic_memory_index.py b/src/powercontext/builtin/persistence/oceanbase/topic_memory_index.py index f3a4f76bf4..6e525ad436 100644 --- a/src/powercontext/builtin/persistence/oceanbase/topic_memory_index.py +++ b/src/powercontext/builtin/persistence/oceanbase/topic_memory_index.py @@ -89,6 +89,7 @@ l2_distance(v.embedding, :query_vector) AS distance FROM pc_topic_memory_vector_topics AS v WHERE v.scope_id = :scope_id + AND v.profile_fingerprint = :profile_fingerprint ORDER BY l2_distance(v.embedding, :query_vector) APPROXIMATE LIMIT :candidate_limit ) @@ -104,6 +105,7 @@ l2_distance(v.embedding, :query_vector) AS distance FROM pc_topic_memory_vector_chunks AS v WHERE v.scope_id = :scope_id + AND v.profile_fingerprint = :profile_fingerprint ORDER BY l2_distance(v.embedding, :query_vector) APPROXIMATE LIMIT :neighbor_limit ), ranked AS ( @@ -417,6 +419,7 @@ async def search( raise TopicMemoryCapabilityError("embedding-profile") parameters = { "scope_id": scope_id, + "profile_fingerprint": self._fingerprint, "query_vector": canonical_embedding( request.query_vector, dimension=self.profile.dimension, diff --git a/src/powercontext/builtin/persistence/sqlite/topic_memory_index.py b/src/powercontext/builtin/persistence/sqlite/topic_memory_index.py index 9db3ef976b..34d3fc08fd 100644 --- a/src/powercontext/builtin/persistence/sqlite/topic_memory_index.py +++ b/src/powercontext/builtin/persistence/sqlite/topic_memory_index.py @@ -189,6 +189,10 @@ WITH nearest AS ( SELECT rowid, distance FROM pc_topic_memory_topic_vec WHERE scope_id = :scope_id AND embedding MATCH :query_vector AND k = :neighbor_limit + AND rowid IN ( + SELECT vector_id FROM pc_topic_memory_vector_topics + WHERE scope_id = :scope_id AND profile_fingerprint = :profile_fingerprint + ) ) SELECT a.artifact_id, a.revision, a.title, a.summary, nearest.distance FROM nearest @@ -205,6 +209,10 @@ WITH nearest AS ( SELECT rowid, distance FROM pc_topic_memory_chunk_vec WHERE scope_id = :scope_id AND embedding MATCH :query_vector AND k = :neighbor_limit + AND rowid IN ( + SELECT vector_id FROM pc_topic_memory_vector_chunks + WHERE scope_id = :scope_id AND profile_fingerprint = :profile_fingerprint + ) ), ranked AS ( SELECT a.artifact_id, a.revision, a.title, a.summary, c.chunk_ordinal, c.start_offset, c.chunk_text, nearest.distance, @@ -508,6 +516,7 @@ async def search( parameters = { "query_vector": query_vector, "scope_id": scope_id, + "profile_fingerprint": self._fingerprint, "candidate_limit": request.candidate_limit, } topic_rows = ( diff --git a/src/powercontext/builtin/persistence/topic_memory.py b/src/powercontext/builtin/persistence/topic_memory.py index 8b4c361f1c..9d308e67ee 100644 --- a/src/powercontext/builtin/persistence/topic_memory.py +++ b/src/powercontext/builtin/persistence/topic_memory.py @@ -104,7 +104,7 @@ async def initialize(self, connection: AsyncConnection, /) -> None: if missing_publication is not None: raise TopicMemoryStorageInvariantError("missing-publication", tuple(missing_publication)) - await self._ensure_retrieval_shape(connection) + await self._ensure_retrieval_shape(connection, allow_empty_change=True) await self.index.initialize(connection) orphan_active = ( @@ -257,6 +257,7 @@ async def get_exact( if ref.family != TopicMemory.family: raise InvalidRepositoryArgumentError("artifact_ref", "must reference topic-memory") + await self._check_retrieval_shape(connection) topic = await self.artifacts.get(connection, scope_id, ref) if not isinstance(topic, TopicMemory): raise TopicMemoryStorageInvariantError("artifact-type", ref) @@ -280,6 +281,7 @@ async def get_exact( if active_revision is None: raise TopicMemoryStorageInvariantError("missing-active-head", (scope_id, ref.artifact_id)) current = ArtifactRef(family=TopicMemory.family, artifact_id=ref.artifact_id, revision=int(active_revision)) + await self._check_retrieval_shape(connection) return PublishedTopicMemory( topic=topic, published_at=_aware_utc(published_at), @@ -300,6 +302,7 @@ async def browse_current( if not 1 <= limit <= 100: raise InvalidRepositoryArgumentError("limit", "must be between 1 and 100") + await self._check_retrieval_shape(connection) statement = ( select( TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.artifact_id, @@ -356,6 +359,7 @@ async def browse_current( ).limit(limit) ) ).mappings() + await self._check_retrieval_shape(connection) return tuple( TopicMemoryCurrentItem( artifact_ref=ArtifactRef( @@ -406,6 +410,7 @@ async def search( f"must contain at most {MAX_TOPIC_MEMORY_QUERY_TERMS} distinct Analyzer terms", ) query_vector = self._canonical_query_vector(used_mode, query_vector) + await self._check_retrieval_shape(connection) if not analyzed and used_mode == "fts": return TopicMemorySearchResult(mode=used_mode, hits=()) request = TopicMemorySearchRequest( @@ -417,6 +422,7 @@ async def search( embedding_profile=embedding_profile, ) channels = await self.index.search(connection, scope_id, request) + await self._check_retrieval_shape(connection) return TopicMemorySearchResult( mode=used_mode, hits=fuse_topic_memory_rankings(query, channels, limit, mode=used_mode), @@ -538,13 +544,55 @@ def _canonical_vector_projection(self, projection: TopicMemoryProjection) -> Top } ) - async def _ensure_retrieval_shape(self, connection: AsyncConnection) -> None: + def _configured_retrieval_shape(self) -> tuple[str, str | None]: capabilities = self.index.capabilities - if not capabilities.fts: - return shape = "hybrid" if capabilities.vector else "fts" profile = capabilities.embedding_profile fingerprint = None if profile is None else topic_memory_embedding_profile_fingerprint(profile) + return shape, fingerprint + + def _require_retrieval_shape(self, stored_shape: str, stored_fingerprint: str | None) -> None: + shape, fingerprint = self._configured_retrieval_shape() + if (stored_shape, stored_fingerprint) != (shape, fingerprint): + stored_label = stored_shape if stored_fingerprint is None else f"{stored_shape}:{stored_fingerprint[:12]}" + configured_label = shape if fingerprint is None else f"{shape}:{fingerprint[:12]}" + raise TopicMemoryCapabilityError( + "retrieval-shape", + f"database requires {stored_label}; runtime configured {configured_label}", + ) + + async def _check_retrieval_shape(self, connection: AsyncConnection) -> None: + # Reads must neither initialize/reconfigure the store nor take its write + # lock. Check before and after hydration: SQLite's legacy SELECT mode + # need not hold a read snapshot across statements. A newly published + # Topic freezes the shape, so a racing switch cannot silently label + # another profile's results with this runtime's startup capabilities. + if not self.index.capabilities.fts: + return + stored = ( + await connection.execute( + select( + TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE.c.shape, + TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE.c.profile_fingerprint, + ).where(TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE.c.singleton == 1) + ) + ).one_or_none() + if stored is None: + raise TopicMemoryStorageInvariantError("missing-retrieval-shape", 1) + self._require_retrieval_shape(str(stored[0]), None if stored[1] is None else str(stored[1])) + + async def _ensure_retrieval_shape(self, connection: AsyncConnection, *, allow_empty_change: bool = False) -> None: + if not self.index.capabilities.fts: + return + shape, fingerprint = self._configured_retrieval_shape() + # Serialize empty-store reconfiguration with publication. An already + # open runtime must not publish its old shape after another one changes + # it. SQLite needs a write lock; SELECT FOR UPDATE is a no-op there. + await connection.execute( + update(TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE) + .where(TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE.c.singleton == 1) + .values(shape=TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE.c.shape) + ) stored = ( await connection.execute( select( @@ -591,25 +639,23 @@ async def _ensure_retrieval_shape(self, connection: AsyncConnection) -> None: stored_shape = str(stored[0]) stored_fingerprint = None if stored[1] is None else str(stored[1]) if (stored_shape, stored_fingerprint) != (shape, fingerprint): - # A configuration becomes binding only once Topic evidence has been published. - changed = await connection.execute( - update(TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE) - .where( - TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE.c.singleton == 1, - ~select(ARTIFACTS_TABLE.c.artifact_id) + if allow_empty_change: + # A locking read sees publications committed before we obtained + # the shape lock even on MySQL REPEATABLE READ connections. + existing = await connection.scalar( + select(ARTIFACTS_TABLE.c.artifact_id) .where(ARTIFACTS_TABLE.c.family == TopicMemory.family) - .exists(), + .limit(1) + .with_for_update() ) - .values(shape=shape, profile_fingerprint=fingerprint) - ) - if changed.rowcount == 1: - return - stored_label = stored_shape if stored_fingerprint is None else f"{stored_shape}:{stored_fingerprint[:12]}" - configured_label = shape if fingerprint is None else f"{shape}:{fingerprint[:12]}" - raise TopicMemoryCapabilityError( - "retrieval-shape", - f"database requires {stored_label}; runtime configured {configured_label}", - ) + if existing is None: + await connection.execute( + update(TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE) + .where(TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE.c.singleton == 1) + .values(shape=shape, profile_fingerprint=fingerprint) + ) + return + self._require_retrieval_shape(stored_shape, stored_fingerprint) def _select_mode( self, diff --git a/src/powercontext/builtin/runtime/composition.py b/src/powercontext/builtin/runtime/composition.py index a22ecafdc7..a499d2ffa4 100644 --- a/src/powercontext/builtin/runtime/composition.py +++ b/src/powercontext/builtin/runtime/composition.py @@ -574,6 +574,7 @@ async def open_builtin_contexts( prompt_registry: PromptRegistry | None = None, prompt_demonstrators: dict[str, DemonstrationGenerator] | None = None, handoff_verification_keys: tuple[bytes, ...] = (), + _topic_memory_worker: bool = False, ) -> AsyncIterator[RelationalContexts]: """Open the selected database and expose scope-bound PowerContext providers.""" @@ -596,8 +597,13 @@ async def open_builtin_contexts( ) as profile: async with profile.database.transaction() as connection: await ensure_skill_distribution_schema(connection) - await index.initialize(connection) - await experience_index.initialize(connection) + # A Topic child reuses its parent's schema. It never reads or + # writes Memory/Experience projections; rebuilding their FTS + # indexes here would take the shared SQLite write lock once + # per Window. Normal runtime startup retains index recovery. + if not _topic_memory_worker: + await index.initialize(connection) + await experience_index.initialize(connection) await TopicMemoryRepository(index=topic_index).initialize(connection) contexts = RelationalContexts( database=profile.database, @@ -642,8 +648,9 @@ async def open_builtin_contexts( async with profile_context as profile: async with profile.database.transaction() as connection: await ensure_skill_distribution_schema(connection) - await index.initialize(connection) - await experience_index.initialize(connection) + if not _topic_memory_worker: + await index.initialize(connection) + await experience_index.initialize(connection) await TopicMemoryRepository(index=topic_index).initialize(connection) contexts = RelationalContexts( database=profile.database, diff --git a/src/powercontext/builtin/runtime/topic_memory_processing.py b/src/powercontext/builtin/runtime/topic_memory_processing.py index 62049da1e7..0948238234 100644 --- a/src/powercontext/builtin/runtime/topic_memory_processing.py +++ b/src/powercontext/builtin/runtime/topic_memory_processing.py @@ -1209,7 +1209,9 @@ async def _open_topic_memory_processor(spec: TopicMemoryWorkerSpec, scope_id: st ) raw_embedding, _ = await _embedding_models(inference, resources, None) embedding = None if raw_embedding is None else UsageReportingEmbeddingModel(raw_embedding) - contexts = await resources.enter_async_context(open_builtin_contexts(config, embedding_model=embedding)) + contexts = await resources.enter_async_context( + open_builtin_contexts(config, embedding_model=embedding, _topic_memory_worker=True) + ) fixed_prompts: dict[str, str] = {} diff --git a/tests/builtin/persistence/test_topic_memory.py b/tests/builtin/persistence/test_topic_memory.py index 369edb8744..48b5157fa2 100644 --- a/tests/builtin/persistence/test_topic_memory.py +++ b/tests/builtin/persistence/test_topic_memory.py @@ -49,6 +49,7 @@ from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile from powercontext.builtin.persistence.sqlite.topic_memory_index import ( SQLITE_TOPIC_MEMORY_VECTOR_CHUNKS_TABLE, + SQLITE_TOPIC_MEMORY_VECTOR_TOPICS_TABLE, SQLiteTopicMemoryFTSIndex, SQLiteTopicMemoryVectorIndex, ) @@ -60,7 +61,11 @@ TOPIC_MEMORY_REVISION_PUBLICATIONS_TABLE, ) from powercontext.builtin.persistence.topic_memory import TopicMemoryRepository -from powercontext.builtin.persistence.topic_memory_index import CompositeTopicMemoryIndex, TopicMemoryIndex +from powercontext.builtin.persistence.topic_memory_index import ( + CompositeTopicMemoryIndex, + TopicMemoryIndex, + topic_memory_embedding_profile_fingerprint, +) from powercontext.sources import SourceMaterialization, SourceRef from tests.builtin.persistence.contract import SOURCE_ADAPTERS, NoteSource @@ -673,10 +678,13 @@ async def scenario() -> None: SQLiteProfile.open(config, tables=BUILTIN_TABLES + index.tables) as profile, profile.database.transaction() as connection, ): + # Test index idempotency separately from the repository's shape + # fence, which deliberately obtains a write lock during startup. before = await connection.scalar(text("SELECT total_changes()")) - await repository.initialize(connection) + await index.initialize(connection) if missing_table is None: assert await connection.scalar(text("SELECT total_changes()")) == before + await repository.initialize(connection) result = await repository.search(connection, "scope-b", "survives", limit=10) assert [hit.artifact_ref.artifact_id for hit in result.hits] == ["peer-topic"] @@ -744,13 +752,14 @@ async def scenario() -> None: SQLiteProfile.open(fts_config, tables=BUILTIN_TABLES + fts_index.tables) as profile, profile.database.transaction() as connection, ): - await TopicMemoryRepository(index=fts_index).initialize(connection) + repository = TopicMemoryRepository(index=fts_index) + await repository.initialize(connection) + content = _content("FTS", "lexical") + await repository.publish_create( + connection, "scope-a", "topic-1", _draft(content), prepare_topic_memory_projection(content) + ) shape = await connection.scalar(select(TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE.c.shape)) assert shape == "fts" - content = _content("Lexical", "durable") - await TopicMemoryRepository(index=fts_index).publish_create( - connection, "scope-a", "fts-topic", _draft(content), prepare_topic_memory_projection(content) - ) async with SQLiteProfile.open( fts_config, @@ -770,6 +779,60 @@ async def scenario() -> None: asyncio.run(scenario()) +def test_empty_shape_change_rejects_publication_from_an_already_open_runtime(tmp_path: Path) -> None: + async def scenario() -> None: + embedding_profile = EmbeddingProfile( + profile_id="topic-test", model="test", dimension=2, distance="l2", normalization="unit" + ) + hybrid_index = CompositeTopicMemoryIndex( + SQLiteTopicMemoryFTSIndex(), SQLiteTopicMemoryVectorIndex(embedding_profile) + ) + old_repository = TopicMemoryRepository(index=_fts_index()) + new_repository = TopicMemoryRepository(index=hybrid_index) + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'shape-change.db'}") + async with SQLiteProfile.open( + config, tables=BUILTIN_TABLES + hybrid_index.tables, load_vector_extension=True + ) as profile: + async with profile.database.transaction() as connection: + await old_repository.initialize(connection) + async with profile.database.transaction() as connection: + await new_repository.initialize(connection) + + content = _content("New", "shape") + projection = prepare_topic_memory_projection(content) + with pytest.raises(TopicMemoryCapabilityError, match="retrieval-shape"): + async with profile.database.transaction() as connection: + await old_repository.publish_create(connection, "scope-a", "stale", _draft(content), projection) + async with profile.database.transaction() as connection: + assert await connection.scalar(select(func.count()).select_from(ARTIFACTS_TABLE)) == 0 + assert ( + await connection.scalar(select(func.count()).select_from(TOPIC_MEMORY_REVISION_PUBLICATIONS_TABLE)) + == 0 + ) + published = await new_repository.publish_create( + connection, + "scope-a", + "current", + _draft(content), + projection.model_copy( + update={ + "topic_embedding": (1.0, 0.0), + "chunk_embeddings": tuple((1.0, 0.0) for _ in projection.chunks), + "embedding_profile": embedding_profile, + } + ), + ) + with pytest.raises(TopicMemoryCapabilityError, match="retrieval-shape"): + async with profile.database.transaction() as connection: + await old_repository.initialize(connection) + async with profile.database.transaction() as connection: + assert ( + await new_repository.get_exact(connection, "scope-a", published.topic.as_ref()) + ).topic == published.topic + + asyncio.run(scenario()) + + def test_startup_rejects_a_topic_revision_without_publication_metadata() -> None: async def scenario() -> None: index = _fts_index() @@ -787,6 +850,140 @@ async def scenario() -> None: asyncio.run(scenario()) +def test_search_rechecks_shape_after_a_concurrent_empty_store_switch(tmp_path: Path) -> None: + async def scenario() -> None: + embedding_profile = EmbeddingProfile( + profile_id="old", model="test", dimension=2, distance="l2", normalization="unit" + ) + hybrid = CompositeTopicMemoryIndex(SQLiteTopicMemoryFTSIndex(), SQLiteTopicMemoryVectorIndex(embedding_profile)) + current = TopicMemoryRepository(index=_fts_index()) + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'read-race.db'}") + async with SQLiteProfile.open( + config, tables=BUILTIN_TABLES + hybrid.tables, load_vector_extension=True + ) as profile: + + class SwitchDuringSearch(_SwitchableIndex): + async def search(self, connection, scope_id, request, /): + # Reconfigure/first-publish on a second connection after + # search starts but before its index has returned results. + async with profile.database.transaction() as writer: + await current.initialize(writer) + content = _content("Current", "evidence") + await current.publish_create( + writer, scope_id, "new", _draft(content), prepare_topic_memory_projection(content) + ) + return await super().search(connection, scope_id, request) + + old = TopicMemoryRepository(index=SwitchDuringSearch(hybrid)) + async with profile.database.transaction() as connection: + await old.initialize(connection) + with pytest.raises(TopicMemoryCapabilityError, match="retrieval-shape"): + async with profile.database.transaction() as reader: + await old.search( + reader, + "scope-a", + "evidence", + limit=2, + mode="hybrid", + query_vector=(1.0, 0.0), + embedding_profile=embedding_profile, + ) + async with profile.database.transaction() as reader: + result = await current.search(reader, "scope-a", "evidence", limit=2) + assert result.mode == "fts" + assert [hit.artifact_ref.artifact_id for hit in result.hits] == ["new"] + + asyncio.run(scenario()) + + +def test_sqlite_vector_candidates_filter_profiles_before_the_neighbor_budget() -> None: + async def scenario() -> None: + embedding_profile = EmbeddingProfile( + profile_id="current", model="test", dimension=2, distance="l2", normalization="unit" + ) + wrong_profile = embedding_profile.model_copy(update={"profile_id": "other-space"}) + vectors = SQLiteTopicMemoryVectorIndex(embedding_profile) + index = CompositeTopicMemoryIndex(SQLiteTopicMemoryFTSIndex(), vectors) + repository = TopicMemoryRepository(index=index) + async with SQLiteProfile.open( + SQLiteConfig(), tables=BUILTIN_TABLES + index.tables, load_vector_extension=True + ) as profile: + async with profile.database.transaction() as connection: + await repository.initialize(connection) + for label, vector in (("wrong", (1.0, 0.0)), ("valid", (0.96, 0.28))): + content = _content(label, "evidence") + projection = prepare_topic_memory_projection(content) + await repository.publish_create( + connection, + "scope-a", + label, + _draft(content), + prepare_topic_memory_projection( + content, + topic_embedding=vector, + chunk_embeddings=(vector,) * len(projection.chunks), + embedding_profile=embedding_profile, + ), + ) + for table in (SQLITE_TOPIC_MEMORY_VECTOR_TOPICS_TABLE, SQLITE_TOPIC_MEMORY_VECTOR_CHUNKS_TABLE): + await connection.execute( + update(table) + .where(table.c.artifact_id == "wrong") + .values(profile_fingerprint=topic_memory_embedding_profile_fingerprint(wrong_profile)) + ) + + async with profile.database.transaction() as connection: + # A closer vector in another space must not consume the sole + # candidate slot. The read guard itself must not write/lock. + await connection.exec_driver_sql("PRAGMA query_only = ON") + try: + for mode in ("vector", "hybrid"): + channels = await vectors.search( + connection, + "scope-a", + TopicMemorySearchRequest( + query="evidence", + mode=mode, + candidate_limit=1, + query_vector=(1.0, 0.0), + embedding_profile=embedding_profile, + ), + ) + for hits in (channels.topic_vector, channels.detail_vector): + assert [hit.artifact_ref.artifact_id for hit in hits] == ["valid"] + result = await repository.search( + connection, + "scope-a", + "evidence", + limit=1, + mode="vector", + query_vector=(1.0, 0.0), + embedding_profile=embedding_profile, + ) + assert [hit.artifact_ref.artifact_id for hit in result.hits] == ["valid"] + assert (await repository.get_exact(connection, "scope-a", result.hits[0].artifact_ref)).is_current + assert len(await repository.browse_current(connection, "scope-a", limit=2)) == 2 + # Direct use of an old adapter also fails closed even if + # callers bypass the repository's persistent shape check. + stale = SQLiteTopicMemoryVectorIndex(embedding_profile.model_copy(update={"profile_id": "stale"})) + stale_channels = await stale.search( + connection, + "scope-a", + TopicMemorySearchRequest( + query="evidence", + mode="vector", + candidate_limit=1, + query_vector=(1.0, 0.0), + embedding_profile=stale.profile, + ), + ) + assert stale_channels.topic_vector == stale_channels.detail_vector == () + finally: + await connection.exec_driver_sql("PRAGMA query_only = OFF") + + asyncio.run(scenario()) + + def test_startup_rejects_a_chunk_that_is_not_part_of_the_current_head() -> None: async def scenario() -> None: index = _fts_index() diff --git a/tests/builtin/persistence/test_topic_memory_oceanbase.py b/tests/builtin/persistence/test_topic_memory_oceanbase.py index f95b094149..224f0d1d38 100644 --- a/tests/builtin/persistence/test_topic_memory_oceanbase.py +++ b/tests/builtin/persistence/test_topic_memory_oceanbase.py @@ -49,7 +49,10 @@ TOPIC_MEMORY_REVISION_PUBLICATIONS_TABLE, ) from powercontext.builtin.persistence.topic_memory import TopicMemoryRepository -from powercontext.builtin.persistence.topic_memory_index import CompositeTopicMemoryIndex +from powercontext.builtin.persistence.topic_memory_index import ( + CompositeTopicMemoryIndex, + topic_memory_embedding_profile_fingerprint, +) def _embedding_profile() -> EmbeddingProfile: @@ -254,6 +257,7 @@ async def scenario() -> None: ann_selection = statement[: statement.index("APPROXIMATE")] assert "JOIN" not in ann_selection assert "WHERE v.scope_id = :scope_id" in ann_selection + assert "v.profile_fingerprint = :profile_fingerprint" in ann_selection assert statement.index("JOIN pc_topic_memory_active_topics") > statement.index("APPROXIMATE") assert statement.rfind("ORDER BY distance, artifact_id, revision DESC") > statement.index("APPROXIMATE") assert statements[0].index("LIMIT :candidate_limit") < statements[0].rfind("ORDER BY distance") @@ -262,6 +266,10 @@ async def scenario() -> None: assert statements[1].find("LIMIT :neighbor_limit") < statements[1].find("row_number() OVER") assert statements[1].rfind("LIMIT :candidate_limit") > statements[1].rfind("WHERE topic_rank = 1") assert connection.execute.await_args_list[1].args[1]["neighbor_limit"] == 400 + for call in connection.execute.await_args_list: + assert call.args[1]["profile_fingerprint"] == topic_memory_embedding_profile_fingerprint( + _embedding_profile() + ) assert result.topic_vector == () assert result.detail_vector == () diff --git a/tests/builtin/runtime/test_composition_embedding.py b/tests/builtin/runtime/test_composition_embedding.py index b463495ecc..ccaedbe154 100644 --- a/tests/builtin/runtime/test_composition_embedding.py +++ b/tests/builtin/runtime/test_composition_embedding.py @@ -16,10 +16,22 @@ import asyncio from contextlib import AsyncExitStack +from pathlib import Path from typing import ClassVar +import pytest from pydantic_ai import Embedder +from powercontext.builtin.artifacts.memory import EmbeddingProfile, MemoryEntryInput +from powercontext.builtin.artifacts.topic_memory import ( + TopicMemoryCapabilityError, + TopicMemoryContent, + TopicMemoryDraft, + prepare_topic_memory_projection, +) +from powercontext.builtin.inference import EmbeddingResult +from powercontext.builtin.persistence.sqlite import SQLiteConfig +from powercontext.builtin.runtime import BuiltinConfig, open_builtin_contexts from powercontext.builtin.runtime.composition import _embedding_models from powercontext.builtin.runtime.config import InferenceConfig @@ -62,3 +74,115 @@ async def scenario() -> None: assert readiness is None asyncio.run(scenario()) + + +@pytest.mark.parametrize("existing_memory", [False, True]) +def test_empty_topic_database_allows_embedding_configuration_changes(tmp_path: Path, existing_memory: bool) -> None: + class Embedding: + def __init__(self, profile_id: str) -> None: + self.profile = EmbeddingProfile( + profile_id=profile_id, model="test", dimension=2, distance="l2", normalization="unit" + ) + + async def embed(self, texts: tuple[str, ...], /) -> EmbeddingResult: + return EmbeddingResult(vectors=tuple((1.0, 0.0) for _ in texts)) + + async def scenario() -> None: + config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'configuration.db'}")) + memory = None + async with open_builtin_contexts(config) as contexts: + if existing_memory: + context = await contexts.get("project") + memory = await context.artifacts.memory.remember( + memory=None, + entries=(MemoryEntryInput(kind="decision", text="Preserve ordinary Memory."),), + mode="append", + ) + + # Reopening an unused Topic store must not lock out ordinary Memory + # embeddings, disabling embeddings, or changing a compatible profile. + for embedding in (Embedding("first"), Embedding("second"), None, Embedding("third")): + async with open_builtin_contexts(config, embedding_model=embedding) as contexts: + assert contexts.index.capabilities.vector is (embedding is not None) + assert contexts.topic_memory_index.capabilities.vector is (embedding is not None) + if existing_memory: + assert memory is not None + context = await contexts.get("project") + result = await context.artifacts.memory.search("ordinary", memories=(memory,), mode="fts") + assert [hit.text for hit in result.hits] == ["Preserve ordinary Memory."] + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("transition", ["profile-change", "hybrid-to-fts", "fts-to-hybrid"]) +def test_stale_topic_runtime_rejects_reads_after_empty_store_reconfiguration(tmp_path: Path, transition: str) -> None: + class Embedding: + def __init__(self, profile_id: str) -> None: + self.profile = EmbeddingProfile( + profile_id=profile_id, model="test", dimension=2, distance="l2", normalization="unit" + ) + + async def embed(self, texts: tuple[str, ...], /) -> EmbeddingResult: + return EmbeddingResult(vectors=tuple((1.0, 0.0) for _ in texts)) + + async def scenario() -> None: + config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'stale-runtime.db'}")) + old_embedding = None if transition == "fts-to-hybrid" else Embedding("old") + new_embedding = None if transition == "hybrid-to-fts" else Embedding("new") + vector = (1.0, 0.0) + # Keep both independently composed runtimes/engines open. Matching + # dimensions alone must not allow queries across embedding spaces. + async with ( + open_builtin_contexts(config, embedding_model=old_embedding) as old, + open_builtin_contexts(config, embedding_model=new_embedding) as current, + ): + with pytest.raises(TopicMemoryCapabilityError, match="retrieval-shape"): + await old.search_topic_memories("scope-a", "evidence", limit=2) + content = TopicMemoryContent( + title="Evidence", summary="Current profile", detail="Evidence from a new space." + ) + chunks = prepare_topic_memory_projection(content).chunks + projection = prepare_topic_memory_projection( + content, + topic_embedding=None if new_embedding is None else vector, + chunk_embeddings=() if new_embedding is None else (vector,) * len(chunks), + embedding_profile=None if new_embedding is None else new_embedding.profile, + ) + async with current.database.transaction() as connection: + published = await current.repositories.topic_memories.publish_create( + connection, "scope-a", "current", TopicMemoryDraft(content=content), projection + ) + modes = ("fts", "auto") if old_embedding is None else ("fts", "auto", "vector", "hybrid") + for mode in modes: + with pytest.raises(TopicMemoryCapabilityError, match="retrieval-shape"): + await old.search_topic_memories( + "scope-a", + "evidence", + limit=2, + mode=mode, + query_vector=None if old_embedding is None else vector, + embedding_profile=None if old_embedding is None else old_embedding.profile, + ) + # Even the zero-Analyzer-term fast path must not silently succeed. + with pytest.raises(TopicMemoryCapabilityError, match="retrieval-shape"): + await old.search_topic_memories("scope-a", "!!!", limit=2, mode="fts") + with pytest.raises(TopicMemoryCapabilityError, match="retrieval-shape"): + await old.get_topic_memory("scope-a", published.topic.as_ref()) + with pytest.raises(TopicMemoryCapabilityError, match="retrieval-shape"): + await old.browse_topic_memories("scope-a", limit=2) + + result = await current.search_topic_memories( + "scope-a", + "evidence", + limit=2, + query_vector=None if new_embedding is None else vector, + embedding_profile=None if new_embedding is None else new_embedding.profile, + ) + assert result.mode == ("fts" if new_embedding is None else "hybrid") + assert [hit.artifact_ref for hit in result.hits] == [published.topic.as_ref()] + assert (await current.get_topic_memory("scope-a", published.topic.as_ref())).topic == published.topic + assert [item.artifact_ref for item in await current.browse_topic_memories("scope-a", limit=2)] == [ + published.topic.as_ref() + ] + + asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_topic_memory_processing.py b/tests/builtin/runtime/test_topic_memory_processing.py index 50e98dd1f8..d9c51a2577 100644 --- a/tests/builtin/runtime/test_topic_memory_processing.py +++ b/tests/builtin/runtime/test_topic_memory_processing.py @@ -26,6 +26,8 @@ import pytest from pydantic import BaseModel, SecretStr +from sqlalchemy import event +from sqlalchemy.engine import Engine from powercontext.artifacts import ArtifactRef from powercontext.builtin.artifacts.search import analyze_text @@ -2139,6 +2141,24 @@ def test_worker_spec_pickle_and_repr_do_not_expose_secret() -> None: assert secret not in repr(restored) +def _run_worker_without_general_fts_writes(spec, assignment): + # Install inside the real spawned child: an event hook in the parent would + # not observe the independent engine. This protects a per-Window I/O budget, + # not a particular sequence of private bootstrap calls. + def reject_general_fts_writes(_connection, _cursor, statement, _parameters, _context, _executemany): + sql = statement.lstrip().lower() + if sql.startswith(("insert", "delete", "update", "replace", "create virtual")) and any( + table in sql for table in ("pc_memory_entry_fts", "pc_memory_entry_vec", "pc_artifact_fts") + ): + raise AssertionError("Topic Worker must not rebuild unrelated search indexes") # noqa: TRY003 + + event.listen(Engine, "before_cursor_execute", reject_general_fts_writes) + try: + return run_topic_memory_worker(spec, assignment) + finally: + event.remove(Engine, "before_cursor_execute", reject_general_fts_writes) + + def test_topic_worker_entrypoint_runs_and_sanitizes_failure_in_real_spawn_child(tmp_path) -> None: async def scenario() -> None: config = BuiltinConfig( @@ -2153,7 +2173,7 @@ async def scenario() -> None: term = await contexts.repositories.processing_leases.start_single_process_term(connection, "holder") assignment = _assignment(term.fence("single-process"), through=1) launcher = SpawnArtifactProcessingWorkerLauncher( - partial(run_topic_memory_worker, TopicMemoryWorkerSpec(config=config)) + partial(_run_worker_without_general_fts_writes, TopicMemoryWorkerSpec(config=config)) ) handle = await launcher.start(assignment) From be68e31bd73e9a7afcd48223d2d28b683fe51de0 Mon Sep 17 00:00:00 2001 From: Rongfeng Fu Date: Tue, 8 Sep 2026 19:01:34 +0800 Subject: [PATCH 2/5] fix(topic-memory): forbid worker retrieval shape reconfiguration Co-authored-by: multica-agent --- .../builtin/persistence/topic_memory.py | 16 +++- .../builtin/runtime/composition.py | 8 +- .../builtin/persistence/test_topic_memory.py | 26 ++++++ .../runtime/test_topic_memory_processing.py | 88 ++++++++++++++++++- 4 files changed, 130 insertions(+), 8 deletions(-) diff --git a/src/powercontext/builtin/persistence/topic_memory.py b/src/powercontext/builtin/persistence/topic_memory.py index 9d308e67ee..7d43e66eb7 100644 --- a/src/powercontext/builtin/persistence/topic_memory.py +++ b/src/powercontext/builtin/persistence/topic_memory.py @@ -77,8 +77,12 @@ def __init__( self.artifacts = ArtifactRepository((TopicMemory,)) if artifacts is None else artifacts self.index = NoTopicMemoryIndex() if index is None else index - async def initialize(self, connection: AsyncConnection, /) -> None: - """Initialize indexes and reject incomplete historical Topic projections.""" + async def initialize(self, connection: AsyncConnection, /, *, configure_retrieval_shape: bool = True) -> None: + """Initialize indexes and reject incomplete historical Topic projections. + + Only deployment startup may configure an empty store. Workers must + reuse an existing shape and fail closed if it is absent or mismatched. + """ missing_publication = ( await connection.execute( @@ -104,7 +108,10 @@ async def initialize(self, connection: AsyncConnection, /) -> None: if missing_publication is not None: raise TopicMemoryStorageInvariantError("missing-publication", tuple(missing_publication)) - await self._ensure_retrieval_shape(connection, allow_empty_change=True) + if configure_retrieval_shape: + await self._ensure_retrieval_shape(connection, allow_empty_change=True) + else: + await self._check_retrieval_shape(connection) await self.index.initialize(connection) orphan_active = ( @@ -195,6 +202,9 @@ async def initialize(self, connection: AsyncConnection, /) -> None: ): raise TopicMemoryStorageInvariantError("incomplete-vector", (str(row["scope_id"]), ref)) + if not configure_retrieval_shape: + await self._check_retrieval_shape(connection) + async def publish_create( self, connection: AsyncConnection, diff --git a/src/powercontext/builtin/runtime/composition.py b/src/powercontext/builtin/runtime/composition.py index a499d2ffa4..7cc85c51ea 100644 --- a/src/powercontext/builtin/runtime/composition.py +++ b/src/powercontext/builtin/runtime/composition.py @@ -604,7 +604,9 @@ async def open_builtin_contexts( if not _topic_memory_worker: await index.initialize(connection) await experience_index.initialize(connection) - await TopicMemoryRepository(index=topic_index).initialize(connection) + await TopicMemoryRepository(index=topic_index).initialize( + connection, configure_retrieval_shape=not _topic_memory_worker + ) contexts = RelationalContexts( database=profile.database, index=index, @@ -651,7 +653,9 @@ async def open_builtin_contexts( if not _topic_memory_worker: await index.initialize(connection) await experience_index.initialize(connection) - await TopicMemoryRepository(index=topic_index).initialize(connection) + await TopicMemoryRepository(index=topic_index).initialize( + connection, configure_retrieval_shape=not _topic_memory_worker + ) contexts = RelationalContexts( database=profile.database, index=index, diff --git a/tests/builtin/persistence/test_topic_memory.py b/tests/builtin/persistence/test_topic_memory.py index 48b5157fa2..ab1736acfb 100644 --- a/tests/builtin/persistence/test_topic_memory.py +++ b/tests/builtin/persistence/test_topic_memory.py @@ -779,6 +779,32 @@ async def scenario() -> None: asyncio.run(scenario()) +@pytest.mark.parametrize("initialized", [False, True]) +def test_worker_initialization_requires_an_existing_shape_without_writing_it(initialized: bool) -> None: + async def scenario() -> None: + index = _fts_index() + repository = TopicMemoryRepository(index=index) + async with SQLiteProfile.open(SQLiteConfig(), tables=BUILTIN_TABLES + index.tables) as profile: + if initialized: + async with profile.database.transaction() as connection: + await repository.initialize(connection) + async with profile.database.transaction() as connection: + await connection.exec_driver_sql("PRAGMA query_only = ON") + try: + if initialized: + await repository.initialize(connection, configure_retrieval_shape=False) + else: + with pytest.raises(TopicMemoryStorageInvariantError, match="missing-retrieval-shape"): + await repository.initialize(connection, configure_retrieval_shape=False) + assert ( + await connection.scalar(select(func.count()).select_from(TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE)) + ) == int(initialized) + finally: + await connection.exec_driver_sql("PRAGMA query_only = OFF") + + asyncio.run(scenario()) + + def test_empty_shape_change_rejects_publication_from_an_already_open_runtime(tmp_path: Path) -> None: async def scenario() -> None: embedding_profile = EmbeddingProfile( diff --git a/tests/builtin/runtime/test_topic_memory_processing.py b/tests/builtin/runtime/test_topic_memory_processing.py index d9c51a2577..a6153b80aa 100644 --- a/tests/builtin/runtime/test_topic_memory_processing.py +++ b/tests/builtin/runtime/test_topic_memory_processing.py @@ -26,10 +26,11 @@ import pytest from pydantic import BaseModel, SecretStr -from sqlalchemy import event +from sqlalchemy import event, select from sqlalchemy.engine import Engine from powercontext.artifacts import ArtifactRef +from powercontext.builtin.artifacts.memory import EmbeddingProfile from powercontext.builtin.artifacts.search import analyze_text from powercontext.builtin.artifacts.skill import ExternalSkillRegistration, ExternalSkillSnapshot, SkillPackageRef from powercontext.builtin.artifacts.topic_memory import ( @@ -80,9 +81,12 @@ from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile from powercontext.builtin.persistence.sqlite.topic_memory_index import SQLiteTopicMemoryFTSIndex from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository -from powercontext.builtin.persistence.tables import BUILTIN_TABLES +from powercontext.builtin.persistence.tables import BUILTIN_TABLES, TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE from powercontext.builtin.persistence.topic_memory import TopicMemoryRepository -from powercontext.builtin.persistence.topic_memory_index import CompositeTopicMemoryIndex +from powercontext.builtin.persistence.topic_memory_index import ( + CompositeTopicMemoryIndex, + topic_memory_embedding_profile_fingerprint, +) from powercontext.builtin.runtime.artifact_processing import ( ArtifactProcessingBinding, ArtifactProcessingSupervisor, @@ -2199,6 +2203,84 @@ async def scenario() -> None: asyncio.run(scenario()) +def test_stale_spawn_worker_cannot_reconfigure_the_current_runtime(tmp_path) -> None: + class Embedding: + profile = EmbeddingProfile(profile_id="current", model="test", dimension=2, distance="l2", normalization="unit") + + async def embed(self, texts: tuple[str, ...], /) -> EmbeddingResult: + return EmbeddingResult(vectors=tuple((1.0, 0.0) for _ in texts)) + + async def scenario() -> None: + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'stale-worker.db'}"), + inference=InferenceConfig(generation_model="test"), + ) + async with open_builtin_contexts(config) as old: + spec = TopicMemoryWorkerSpec(config=config) + scope = await old.get("scope-a") + await scope.sources.capture(ContentCapture(source_id="source", content="Durable evidence")) + async with old.database.transaction() as connection: + term = await old.repositories.processing_leases.start_single_process_term(connection, "holder") + # Keep the old deployment/spec alive while a normal Runtime + # explicitly changes the empty Topic store from FTS to hybrid. + embedding = Embedding() + async with open_builtin_contexts(config, embedding_model=embedding) as current: + expected_shape = ("hybrid", topic_memory_embedding_profile_fingerprint(embedding.profile)) + shape_query = select( + TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE.c.shape, + TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE.c.profile_fingerprint, + ) + async with current.database.transaction() as connection: + assert tuple((await connection.execute(shape_query)).one()) == expected_shape + launcher = SpawnArtifactProcessingWorkerLauncher(partial(run_topic_memory_worker, spec)) + handle = await launcher.start(_assignment(term.fence("single-process"), through=1)) + try: + with pytest.raises(RuntimeError) as error: + await asyncio.wait_for(handle.wait(), timeout=30) + finally: + await handle.terminate() + + async with current.database.transaction() as connection: + assert tuple((await connection.execute(shape_query)).one()) == expected_shape + assert ( + await current.repositories.cursors.load( + connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING + ) + ) is None + # Reject during bootstrap, not later at model-output validation. + assert cast(Any, error.value).failure.exception_type == "TopicMemoryCapabilityError" + assert (await current.search_topic_memories("scope-a", "evidence", mode="fts", limit=2)).hits == () + assert await current.browse_topic_memories("scope-a", limit=2) == () + + content = TopicMemoryContent(title="Current", summary="Evidence", detail="Durable evidence") + chunks = prepare_topic_memory_projection(content).chunks + projection = prepare_topic_memory_projection( + content, + topic_embedding=(1.0, 0.0), + chunk_embeddings=((1.0, 0.0),) * len(chunks), + embedding_profile=embedding.profile, + ) + async with current.database.transaction() as connection: + published = await current.repositories.topic_memories.publish_create( + connection, "scope-a", "current", TopicMemoryDraft(content=content), projection + ) + result = await current.search_topic_memories( + "scope-a", + "evidence", + limit=2, + query_vector=(1.0, 0.0), + embedding_profile=embedding.profile, + ) + assert result.mode == "hybrid" + assert [hit.artifact_ref for hit in result.hits] == [published.topic.as_ref()] + assert (await current.get_topic_memory("scope-a", published.topic.as_ref())).topic == published.topic + assert [item.artifact_ref for item in await current.browse_topic_memories("scope-a", limit=2)] == [ + published.topic.as_ref() + ] + + asyncio.run(scenario()) + + def test_topic_usage_purposes_are_fail_open_and_secret_safe(caplog: pytest.LogCaptureFixture) -> None: async def scenario() -> None: observed: list[ModelUsagePurpose] = [] From b6162e0b6f48a1c532c0b74b134a5d355c3069a3 Mon Sep 17 00:00:00 2001 From: Rongfeng Fu Date: Tue, 8 Sep 2026 22:59:01 +0800 Subject: [PATCH 3/5] fix(topic-memory): bound intermediate fragment accumulation Co-authored-by: multica-agent --- docs/en/rfcs/1417_topic_memory.md | 27 +- docs/zh/rfcs/1417_topic_memory.md | 19 +- .../artifacts/topic_memory/generation.py | 39 +++ .../runtime/topic_memory_processing.py | 98 ++++++- .../test_topic_memory_fragment_reduction.py | 271 ++++++++++++++++++ 5 files changed, 436 insertions(+), 18 deletions(-) create mode 100644 tests/builtin/runtime/test_topic_memory_fragment_reduction.py diff --git a/docs/en/rfcs/1417_topic_memory.md b/docs/en/rfcs/1417_topic_memory.md index 20e328bd11..1c8a341b07 100644 --- a/docs/en/rfcs/1417_topic_memory.md +++ b/docs/en/rfcs/1417_topic_memory.md @@ -213,6 +213,14 @@ original evidence ID and its character offsets; it does not become a new Source fragments must complete before the Window publishes and advances its Cursor. A failed fragment leaves the original Source and Cursor unchanged for retry. +Fragment results use a streaming accumulator bounded by both 20 live items and the stage input token budget, not a +20-item limit over the entire Source. Exact duplicate Probes are coalesced. Before the accumulator overflows, a private +reduction stage consolidates a fitting prefix into one intermediate result. It must account for every input position, +retain the exact union of evidence IDs, and cannot select a historical identity or return NOOP. The result is limited +to one eighth of the stage input budget. A singleton reduction must decrease estimated size; other reductions must +decrease item count. Each compaction has a fixed attempt bound of twice its input item count plus one, so a model cannot +create an unbounded compression loop. All model calls use the existing stage request/output limits and Worker timeout. + ## Probe and historical Topic selection The Worker first reads the current Source Window. Server-owned `lineage_only` Sources are excluded before token @@ -291,7 +299,8 @@ Item uses the temporary Topic path: Work Item Sources -> split into bounded Source Batches, fragmenting an oversized Source when necessary -> generate temporary Topics for each Batch without loading the historical Topic - -> all relevant temporary Topics + one historical Topic or an empty target + -> bounded intermediate reduction of all contributed temporary Topics + -> reduced temporary Topics + one historical Topic or an empty target -> final CREATE / UPDATE / NOOP ~~~ @@ -300,10 +309,12 @@ its evidence IDs. Final lineage is the union of SourceRefs referenced by the tem to the result. A temporary Topic has no identity, is not written to the database, does not participate in retrieval, and is discarded when the Worker ends. -If all temporary Topics plus one historical Topic still exceed the model context, the first release does not perform -recursive compression, split the historical Topic, or split the topic automatically. This is a known but explicitly -excluded extreme input. Source fragmentation does not remove the separate bounds on temporary Topic count, -provider requests, or final historical context. +Temporary results are reduced incrementally before count or token overflow, and again if needed before adding the +historical Topic. Reduction never publishes intermediate state. Missing input coverage, invented evidence or targets, +an oversized result, or failure to make progress aborts the Window with its Cursor unchanged. If even a reduced result +plus the historical Topic cannot fit, the Worker fails closed; it does not split or truncate historical content or +start an unlimited reduction loop. This does not guarantee semantic summary quality or successful processing of +arbitrarily large input within the Worker timeout. ## Second retrieval and related-group reconciliation @@ -823,8 +834,8 @@ should use consistent settings and record effective values in startup logs. whole Window and the progress of an individual task cannot be queried. - The `global` Supervisor centralizes resource control, but it may become a bottleneck if several heavyweight Families share the Worker pool in the future. -- Source fragmentation adds generation calls. Temporary Topics plus a historical Topic may still exceed context; - recursive compression of that material remains outside the first release. +- Source fragmentation and intermediate reduction add generation calls. Reduction coverage is checked structurally, + but information-preserving wording still depends on the model. Oversized historical context can still fail closed. # Rationale and alternatives @@ -890,7 +901,7 @@ The current scope has no unresolved design questions that block acceptance of th The following boundaries are explicitly excluded rather than left as open choices for implementers: -- recursive compression or splitting when temporary Topic content plus one historical Topic still exceeds context; +- unbounded recursive compression or splitting of historical Topic content; - automatic merging of two existing Topic identities; - cross-Scope Topic retrieval; - user-facing APIs to create, update, delete, or retire Topics manually; diff --git a/docs/zh/rfcs/1417_topic_memory.md b/docs/zh/rfcs/1417_topic_memory.md index 1236f70094..02e07fce0e 100644 --- a/docs/zh/rfcs/1417_topic_memory.md +++ b/docs/zh/rfcs/1417_topic_memory.md @@ -192,6 +192,12 @@ tokens。一次实际 generation 请求仍必须满足: 新 Source,也不占用新的 Journal 位置。全部片段处理成功后,Window 才统一发布并推进 Cursor;任一片段失败时, 原 Source 与 Cursor 保持不变,供后续重试。 +分片结果使用同时受 20 个驻留项和阶段输入 token 预算约束的流式累加器,20 不是整条 Source 的结果总上限。 +完全相同的 Probe 先去重;累加器将溢出前,私有归并阶段把预算内的前缀合成一个中间结果。归并必须覆盖每个 +输入位置、保留 evidence IDs 的精确并集,不能选择历史身份或返回 NOOP。结果最多占阶段输入预算的八分之一。 +单项归并必须缩小估算体积,多项归并必须减少项数;每次压缩最多尝试“输入项数的两倍加一”次,防止模型造成 +无限压缩循环。所有调用继续使用现有阶段请求/输出限制与 Worker timeout。 + ## Probe 与历史 Topic 选择 Worker 首先读取当前 Source Window。服务端标记为 `lineage_only` 的 Source 在 token 估算与生成之前排除,其 @@ -262,7 +268,8 @@ Evolver 直接生成最终 Topic 内容。 Work Item Source -> 拆成有界 Source Batch,必要时将单个超长 Source 分段 -> 每个 Batch 在不加载历史 Topic 的情况下生成临时 Topics - -> 全部相关临时 Topics + 一个历史 Topic或空白目标 + -> 对全部贡献的临时 Topics 做有界中间归并 + -> 归并后的临时 Topics + 一个历史 Topic或空白目标 -> 最终 CREATE / UPDATE / NOOP ~~~ @@ -270,8 +277,10 @@ Work Item Source 结果的临时 Topics 所引用 SourceRef 的并集。临时 Topic 没有 identity,不写数据库,不参与检索,Worker 结束 后即丢弃。 -如果“全部临时 Topic + 单个历史 Topic”仍超过模型上下文,首版不做递归压缩、历史 Topic 分片或自动拆分。这是 -已知但明确排除的极端输入。Source 分段不取消临时 Topic 数量、模型请求次数和最终历史上下文的独立上限。 +临时结果在数量或 token 溢出前增量归并,加入历史 Topic 前必要时再归并。归并不发布中间状态;遗漏输入覆盖、 +虚构证据或目标、结果超预算、无法缩小结果都会使 Window 失败并保留 Cursor。如果归并结果加单个历史 Topic +仍不能适配上下文,则失败关闭,不拆分或截断历史内容,也不进入无限归并循环。这不保证模型摘要的语义质量, +也不保证任意大的输入都能在 Worker timeout 内处理成功。 ## 二次检索与相关组协调 @@ -738,7 +747,7 @@ configuration error 失败;Runtime 不创建或回填这些历史向量,也 - Pending dirty set 增加 Source 写事务的写放大。 - 不持久化 Job、checkpoint 和 retry state 简化了系统,但失败后需要重算整个 Window,且无法查询单次任务进度。 - `global` Supervisor 统一资源控制,但未来多个重型 Family 共用 Worker pool 时可能成为瓶颈。 -- Source 分段增加模型调用次数;“临时 Topic + 历史 Topic”仍可能超过上下文,对这部分材料的递归压缩不在首版范围。 +- Source 分段和中间归并增加模型调用次数;结构校验保护输入覆盖,但信息保真的措辞仍依赖模型,超长历史上下文仍可能失败关闭。 # Rationale and alternatives @@ -793,7 +802,7 @@ Revision 拥有不同通道数,融合排名不可比较,因此保留旧 acti 以下边界已明确排除,不作为实现者自行选择的开放问题: -- 临时 Topic 总内容加单个历史 Topic 仍超过上下文时的递归压缩或拆分策略; +- 对历史 Topic 内容无限递归压缩或拆分的策略; - 两个已有 Topic identities 的自动合并; - 跨 Scope Topic 检索; - 用户手动管理 Topic 的 create/update/delete/retire API; diff --git a/src/powercontext/builtin/artifacts/topic_memory/generation.py b/src/powercontext/builtin/artifacts/topic_memory/generation.py index e602ae49ba..f89ddbe8a0 100644 --- a/src/powercontext/builtin/artifacts/topic_memory/generation.py +++ b/src/powercontext/builtin/artifacts/topic_memory/generation.py @@ -283,6 +283,28 @@ class TopicMemoryTemporaryOutput(_TopicMemoryStageModel): proposals: tuple[TopicMemoryProposal, ...] = Field(min_length=1, max_length=MAX_TOPIC_MEMORY_STAGE_ITEMS) +class TopicMemoryReductionInput(_TopicMemoryStageModel): + """A bounded batch of intermediate results, never raw Source identities.""" + + probes: tuple[TopicMemoryProbe, ...] = Field(default=(), max_length=MAX_TOPIC_MEMORY_STAGE_ITEMS) + temporary: tuple[TopicMemoryProposal, ...] = Field(default=(), max_length=MAX_TOPIC_MEMORY_STAGE_ITEMS) + max_result_tokens: StrictInt = Field(ge=1) + + @model_validator(mode="after") + def require_one_kind(self): + if bool(self.probes) == bool(self.temporary): + raise ValueError("reduction requires exactly one kind of intermediate material") # noqa: TRY003 + return self + + +class TopicMemoryReductionOutput(_TopicMemoryStageModel): + """One summary accounting for every input position; no CREATE/UPDATE decision.""" + + covered_indices: tuple[StrictInt, ...] = Field(min_length=1, max_length=MAX_TOPIC_MEMORY_STAGE_ITEMS) + probe: TopicMemoryProbe | None = None + temporary: TopicMemoryProposal | None = None + + class TopicMemoryReconcileInput(_TopicMemoryStageModel): component_id: str = Field(min_length=1, max_length=64) proposals: tuple[TopicMemoryProposal, ...] = Field(min_length=1, max_length=MAX_TOPIC_MEMORY_STAGE_ITEMS) @@ -299,6 +321,14 @@ class TopicMemoryReconcileOutput(_TopicMemoryStageModel): Use only a candidate_id listed by every probe in its work item, and group every probe that lists a chosen candidate.""" TOPIC_MEMORY_EVOLVE_INSTRUCTIONS = """Create or revise one topic. Return content and cited opaque evidence only.""" TOPIC_MEMORY_TEMPORARY_INSTRUCTIONS = """Summarize an oversized work item into at most 20 temporary topics.""" +TOPIC_MEMORY_REDUCTION_INSTRUCTIONS = """Consolidate ALL supplied intermediate material into one bounded summary. +For probes, return one semantic retrieval probe retaining the distinct concepts and keywords of every input. +For temporary topics of one work item, return one temporary topic retaining all contributed facts, corrections, +qualifications and evidence; do not load or choose a historical target. This is not a final publication or a NOOP. +Return only the matching output kind. Cite the exact union of the supplied evidence_ids and include every zero-based +input position exactly once in covered_indices. Never invent a candidate_id or proposal_id. Deduplicate repeated +information, but never omit an input. The complete result must fit max_result_tokens; compress wording, not evidence. +""" TOPIC_MEMORY_RECONCILE_INSTRUCTIONS = """Coordinate related proposals without merging two historical identities.""" @@ -345,6 +375,12 @@ def _topic_memory_minimum_stage_requests() -> tuple[str, ...]: TopicMemoryTemporaryOutput, TopicMemoryTemporaryInput(work_id="w", evidence=(evidence,)), ), + ( + TOPIC_MEMORY_REDUCTION_INSTRUCTIONS, + TopicMemoryReductionInput, + TopicMemoryReductionOutput, + TopicMemoryReductionInput(temporary=(proposal, proposal), max_result_tokens=128), + ), ( TOPIC_MEMORY_RECONCILE_INSTRUCTIONS, TopicMemoryReconcileInput, @@ -378,6 +414,7 @@ def validate_topic_memory_stage_capacity( "TOPIC_MEMORY_PLANNER_INSTRUCTIONS", "TOPIC_MEMORY_PROBE_INSTRUCTIONS", "TOPIC_MEMORY_RECONCILE_INSTRUCTIONS", + "TOPIC_MEMORY_REDUCTION_INSTRUCTIONS", "TOPIC_MEMORY_TEMPORARY_INSTRUCTIONS", "BudgetedTopicMemoryGenerator", "TopicMemoryEvidence", @@ -398,6 +435,8 @@ def validate_topic_memory_stage_capacity( "TopicMemoryProposal", "TopicMemoryReconcileInput", "TopicMemoryReconcileOutput", + "TopicMemoryReductionInput", + "TopicMemoryReductionOutput", "TopicMemoryStageBudget", "TopicMemoryTemporaryInput", "TopicMemoryTemporaryOutput", diff --git a/src/powercontext/builtin/runtime/topic_memory_processing.py b/src/powercontext/builtin/runtime/topic_memory_processing.py index 0948238234..508a2f3c0f 100644 --- a/src/powercontext/builtin/runtime/topic_memory_processing.py +++ b/src/powercontext/builtin/runtime/topic_memory_processing.py @@ -67,6 +67,8 @@ TopicMemoryProposal, TopicMemoryReconcileInput, TopicMemoryReconcileOutput, + TopicMemoryReductionInput, + TopicMemoryReductionOutput, TopicMemoryTemporaryInput, TopicMemoryTemporaryOutput, topic_memory_stage_fixed_prompt, @@ -131,6 +133,7 @@ class TopicMemoryStageSet: estimator: TokenEstimator input_tokens_limit: int fixed_prompts: Mapping[str, str] = field(default_factory=dict) + reducer: StructuredGenerator[TopicMemoryReductionInput, TopicMemoryReductionOutput] | None = None def __post_init__(self) -> None: if self.input_tokens_limit < 1: @@ -427,13 +430,80 @@ async def _probe(self, evidence: tuple[TopicMemoryEvidence, ...]) -> tuple[Topic for batch in batches: with self._usage(ModelUsagePurpose.TOPIC_MEMORY_GENERATION): output = (await self._stages.probe.generate(TopicMemoryProbeInput(evidence=batch))).output - probes.extend(output.probes) - if len(probes) > MAX_TOPIC_MEMORY_STAGE_ITEMS: - raise TopicMemoryGenerationError("probe_limit") + self._validate_probes(output.probes, batch) + for probe in output.probes: + if probe in probes: + continue + probes = list(cast(tuple[TopicMemoryProbe, ...], await self._compact_intermediates((*probes, probe)))) result = tuple(probes) self._validate_probes(result, evidence) return result + def _reduction_input( + self, items: Sequence[TopicMemoryProbe | TopicMemoryProposal], *, temporary: bool + ) -> TopicMemoryReductionInput: + return TopicMemoryReductionInput( + probes=() if temporary else cast(tuple[TopicMemoryProbe, ...], tuple(items)), + temporary=cast(tuple[TopicMemoryProposal, ...], tuple(items)) if temporary else (), + max_result_tokens=max(1, self._stages.input_tokens_limit // 8), + ) + + async def _compact_intermediates( + self, + values: Sequence[TopicMemoryProbe | TopicMemoryProposal], + *, + temporary: bool = False, + historical: TopicMemoryHistoricalSlot | None = None, + ) -> tuple[TopicMemoryProbe | TopicMemoryProposal, ...]: + """Bound live results by count AND tokens without dropping an input. + + Each reduction consumes a prefix and returns one summary. A singleton + must shrink; every other reduction decreases cardinality. The fixed + attempt bound prevents model output from causing a compression loop. + """ + + items = list(values) + for _ in range(2 * len(items) + 1): + if len(items) <= MAX_TOPIC_MEMORY_STAGE_ITEMS: + fits = self._stages.fits(self._reduction_input(items, temporary=temporary), "reduce") + if temporary: + fits = fits and self._stages.fits( + TopicMemoryEvolveInput( + work_id="work-0001", + temporary=cast(tuple[TopicMemoryProposal, ...], tuple(items)), + historical=historical, + ), + "evolve", + ) + if fits: + return tuple(items) + size = min(len(items), MAX_TOPIC_MEMORY_STAGE_ITEMS) + while size and not self._stages.fits(self._reduction_input(items[:size], temporary=temporary), "reduce"): + size -= 1 + if not size or self._stages.reducer is None: + raise TopicMemoryGenerationError("reduction_input_budget_exceeded") + request = self._reduction_input(items[:size], temporary=temporary) + with self._usage(ModelUsagePurpose.TOPIC_MEMORY_GENERATION): + output = (await self._stages.reducer.generate(request)).output + result = output.temporary if temporary else output.probe + other = output.probe if temporary else output.temporary + expected_evidence = {eid for item in items[:size] for eid in item.evidence_ids} + if ( + result is None + or other is not None + or sorted(output.covered_indices) != list(range(size)) + or set(result.evidence_ids) != expected_evidence + or (isinstance(result, TopicMemoryProposal) and (result.candidate_id or result.proposal_id)) + ): + raise TopicMemoryGenerationError("invalid_reduction") + result_tokens = self._stages.estimator.estimate(result.model_dump_json()) + if result_tokens > request.max_result_tokens: + raise TopicMemoryGenerationError("reduction_output_budget_exceeded") + if size == 1 and result_tokens >= self._stages.estimator.estimate(items[0].model_dump_json()): + raise TopicMemoryGenerationError("reduction_did_not_progress") + items[:size] = [result] + raise TopicMemoryGenerationError("reduction_did_not_progress") + def _evidence_batches( self, evidence: tuple[TopicMemoryEvidence, ...], @@ -669,8 +739,18 @@ async def _plan( # noqa: C901 update={"proposal_id": (f"temp-{index:04d}-{batch_index:04d}-{len(temporary):04d}")} ) ) - if len(temporary) > MAX_TOPIC_MEMORY_STAGE_ITEMS: - raise TopicMemoryGenerationError("temporary_limit") + temporary = list( + cast( + tuple[TopicMemoryProposal, ...], + await self._compact_intermediates(temporary, temporary=True), + ) + ) + temporary = list( + cast( + tuple[TopicMemoryProposal, ...], + await self._compact_intermediates(temporary, temporary=True, historical=historical), + ) + ) flattened = TopicMemoryEvolveInput( work_id=evolve_input.work_id, temporary=tuple(temporary), @@ -1167,6 +1247,7 @@ async def _open_topic_memory_processor(spec: TopicMemoryWorkerSpec, scope_id: st TOPIC_MEMORY_PLANNER_INSTRUCTIONS, TOPIC_MEMORY_PROBE_INSTRUCTIONS, TOPIC_MEMORY_RECONCILE_INSTRUCTIONS, + TOPIC_MEMORY_REDUCTION_INSTRUCTIONS, TOPIC_MEMORY_TEMPORARY_INSTRUCTIONS, BudgetedTopicMemoryGenerator, topic_memory_stage_budget, @@ -1284,6 +1365,13 @@ def stage( "topic_reconciler", "reconcile", ), + reducer=stage( + TopicMemoryReductionInput, + TopicMemoryReductionOutput, + TOPIC_MEMORY_REDUCTION_INSTRUCTIONS, + "topic_reducer", + "reduce", + ), estimator=contexts.token_estimator, input_tokens_limit=budget.input_tokens_limit, fixed_prompts=fixed_prompts, diff --git a/tests/builtin/runtime/test_topic_memory_fragment_reduction.py b/tests/builtin/runtime/test_topic_memory_fragment_reduction.py new file mode 100644 index 0000000000..826ddb9846 --- /dev/null +++ b/tests/builtin/runtime/test_topic_memory_fragment_reduction.py @@ -0,0 +1,271 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import asyncio +import json +from dataclasses import replace + +import pytest + +from powercontext.builtin.artifacts.topic_memory import TOPIC_MEMORY_SOURCE_WINDOW_BINDING, TopicMemoryContent +from powercontext.builtin.artifacts.topic_memory.generation import ( + MAX_TOPIC_MEMORY_STAGE_ITEMS, + TOPIC_MEMORY_EVOLVE_INSTRUCTIONS, + TOPIC_MEMORY_PROBE_INSTRUCTIONS, + TOPIC_MEMORY_REDUCTION_INSTRUCTIONS, + TOPIC_MEMORY_TEMPORARY_INSTRUCTIONS, + TopicMemoryEvolveInput, + TopicMemoryEvolveOutput, + TopicMemoryGenerationError, + TopicMemoryPlanItem, + TopicMemoryPlannerOutput, + TopicMemoryProbe, + TopicMemoryProbeInput, + TopicMemoryProbeOutput, + TopicMemoryProposal, + TopicMemoryReductionInput, + TopicMemoryReductionOutput, + TopicMemoryTemporaryInput, + TopicMemoryTemporaryOutput, + topic_memory_stage_fixed_prompt, +) +from powercontext.builtin.inference import GenerationResult, character_token_estimator +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.sources import SourceRepository +from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository +from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingWorkerOutcome +from powercontext.builtin.runtime.topic_memory_processing import ( + TopicMemoryAtomicPublisher, + TopicMemoryProcessor, + TopicMemoryStageSet, + TopicMemoryWindowSelector, +) +from powercontext.builtin.sources import CONTENT_SOURCE_ADAPTER, ContentCapture +from tests.builtin.persistence.contract import SOURCE_ADAPTERS +from tests.builtin.runtime.test_topic_memory_processing import _assignment, _QueueGenerator, _repositories + + +def _proposal(detail: str) -> TopicMemoryProposal: + return TopicMemoryProposal( + content=TopicMemoryContent(title="Fragmented evidence", summary="Complete observations", detail=detail), + evidence_ids=("evidence-0001",), + ) + + +class _FragmentStages: + """Deterministic model outputs retaining a distinct marker for every fragment.""" + + def __init__(self, *, repeated: bool = False, failure: str | None = None, padded: bool = False) -> None: + self.repeated = repeated + self.failure = failure + self.padding = "shared-context " * 2_800 if padded else "" + self.probes: list[TopicMemoryProbeInput] = [] + self.temporaries: list[TopicMemoryTemporaryInput] = [] + self.reductions: list[TopicMemoryReductionInput] = [] + + async def generate(self, value, /): # noqa: C901 + if isinstance(value, TopicMemoryProbeInput): + self.probes.append(value) + fragment = value.evidence[0].metadata + # The ordinary tail remains independently processable as a NOOP. + if "fragment_start" not in fragment: + return GenerationResult(output=TopicMemoryProbeOutput()) + query = "repeated observation" if self.repeated else f"observation-{fragment['fragment_start']}" + return GenerationResult( + output=TopicMemoryProbeOutput(probes=(TopicMemoryProbe(query=query, evidence_ids=("evidence-0001",)),)) + ) + if isinstance(value, TopicMemoryTemporaryInput): + self.temporaries.append(value) + return GenerationResult( + output=TopicMemoryTemporaryOutput( + proposals=( + _proposal(f"fact-{value.evidence[0].metadata['fragment_start']}\n{self.padding}".strip()), + ) + ) + ) + if isinstance(value, TopicMemoryReductionInput): + self.reductions.append(value) + inputs = value.probes or value.temporary + indices = tuple(range(len(inputs))) + probe = ( + TopicMemoryProbe(query=" ".join(item.query for item in value.probes), evidence_ids=("evidence-0001",)) + if value.probes + else None + ) + proposal = _proposal(_combined_detail(value.temporary)) if value.temporary else None + # Fail in the temporary path, after successful Probe accumulation. + if value.temporary: + if self.failure == "unavailable": + raise RuntimeError("reduction unavailable") # noqa: TRY003 + if self.failure == "coverage": + indices = indices[:-1] + if self.failure == "evidence": + proposal = _proposal("bad").model_copy(update={"evidence_ids": ("unissued-evidence",)}) + if self.failure == "target": + proposal = _proposal("bad").model_copy(update={"candidate_id": "unissued-target"}) + if self.failure == "budget": + proposal = _proposal("界" * value.max_result_tokens) + return GenerationResult( + output=TopicMemoryReductionOutput(covered_indices=indices, probe=probe, temporary=proposal) + ) + if isinstance(value, TopicMemoryEvolveInput): + return GenerationResult( + output=TopicMemoryEvolveOutput(proposal=_proposal(_combined_detail(value.temporary))) + ) + return GenerationResult( + output=TopicMemoryPlannerOutput( + items=(TopicMemoryPlanItem(probe_ids=tuple(p.probe_id for p in value.probes)),) + ) + ) + + +def _combined_detail(items: tuple[TopicMemoryProposal, ...]) -> str: + return "\n".join(dict.fromkeys(line for item in items for line in item.content.detail.splitlines())) + + +@pytest.mark.parametrize( + "repeated,input_limit,characters", + [(True, 100_000, 2_100_000), (False, 100_000, 2_100_000), (False, 20_000, 500_000)], +) +def test_fragment_reduction_publishes_all_material_then_processes_scope_tail(repeated, input_limit, characters) -> None: + asyncio.run(_scenario(repeated=repeated, input_limit=input_limit, characters=characters)) + + +@pytest.mark.parametrize("failure", ["coverage", "evidence", "target", "budget", "unavailable"]) +def test_fragment_reduction_failure_preserves_cursor_and_can_retry(failure) -> None: + asyncio.run(_scenario(failure=failure)) + + +def test_fragment_reduction_enforces_token_budget_before_item_count_limit() -> None: + asyncio.run(_scenario(padded=True)) + + +async def _scenario(*, repeated=False, input_limit=100_000, characters=2_100_000, failure=None, padded=False) -> None: + manager, profile, _, topics = await _repositories() + sources = SourceRepository((*SOURCE_ADAPTERS, CONTENT_SOURCE_ADAPTER)) + fake = _FragmentStages(repeated=repeated, failure=failure, padded=padded) + try: + original = "界" * characters + "TAIL-OF-LARGE-SOURCE" + async with profile.database.transaction() as connection: + source = await sources.add( + connection, + "scope-a", + await CONTENT_SOURCE_ADAPTER.resolve( + ContentCapture(source_id="large", content="body", metadata={"context": original}) + ), + ) + tail = await sources.add( + connection, + "scope-a", + await CONTENT_SOURCE_ADAPTER.resolve(ContentCapture(source_id="tail", content="ordinary tail")), + ) + term = await ArtifactProcessingLeaseRepository().start_single_process_term(connection, "holder") + estimator = character_token_estimator() + stages = TopicMemoryStageSet( + probe=fake, + planner=fake, + temporary=fake, + evolver=fake, + reducer=fake, + global_evolver=_QueueGenerator(), + reconciler=_QueueGenerator(), + estimator=estimator, + input_tokens_limit=input_limit, + fixed_prompts={ + name: topic_memory_stage_fixed_prompt(instructions, inputs, outputs) + for name, instructions, inputs, outputs in ( + ("probe", TOPIC_MEMORY_PROBE_INSTRUCTIONS, TopicMemoryProbeInput, TopicMemoryProbeOutput), + ( + "temporary", + TOPIC_MEMORY_TEMPORARY_INSTRUCTIONS, + TopicMemoryTemporaryInput, + TopicMemoryTemporaryOutput, + ), + ("evolve", TOPIC_MEMORY_EVOLVE_INSTRUCTIONS, TopicMemoryEvolveInput, TopicMemoryEvolveOutput), + ( + "reduce", + TOPIC_MEMORY_REDUCTION_INSTRUCTIONS, + TopicMemoryReductionInput, + TopicMemoryReductionOutput, + ), + ) + }, + ) + selector = TopicMemoryWindowSelector( + profile.database, sources, estimator, context_window_tokens=input_limit * 5 // 4 + ) + selected = await selector.select("scope-a", 0, tail.journal_position) + assert selected == source.journal_position + processor = TopicMemoryProcessor( + database=profile.database, + sources=sources, + topics=topics, + stages=stages, + publisher=TopicMemoryAtomicPublisher(profile.database, sources, topics), + ) + assignment = _assignment(term.fence("single-process"), through=selected) + if failure: + with pytest.raises((TopicMemoryGenerationError, RuntimeError), match="reduction"): + await processor.process(assignment) + async with profile.database.transaction() as connection: + assert ( + await SourceCursorRepository().load(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + is None + ) + assert await topics.browse_current(connection, "scope-a", limit=10) == () + fake.failure = None + fake.probes.clear() + fake.temporaries.clear() + fake.reductions.clear() + assert (await processor.process(assignment)).outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + for requests, stage in ((fake.probes, "probe"), (fake.temporaries, "temporary")): + assert len(requests) > 20 + assert all(stages.fits(request, stage) for request in requests) + canonical = "".join(request.evidence[0].content for request in requests) + assert json.loads(canonical) == {"content": "body", "metadata": {"context": original}} + assert fake.reductions + assert all(stages.fits(request, "reduce") for request in fake.reductions) + assert all( + len(request.probes or request.temporary) <= MAX_TOPIC_MEMORY_STAGE_ITEMS for request in fake.reductions + ) + if padded: + assert any(1 < len(request.temporary) < MAX_TOPIC_MEMORY_STAGE_ITEMS for request in fake.reductions) + # Intermediate reductions must terminate; no model-controlled retry loop. + assert len(fake.reductions) <= 2 * (len(fake.probes) + len(fake.temporaries)) + async with profile.database.transaction() as connection: + hits = await topics.browse_current(connection, "scope-a", limit=10) + assert len(hits) == 1 + published = await topics.get_exact(connection, "scope-a", hits[0].artifact_ref) + assert published.topic.lineage.sources == (source.ref,) + expected = {f"fact-{value.evidence[0].metadata['fragment_start']}" for value in fake.temporaries} + if fake.padding: + expected.add(fake.padding.strip()) + assert set(published.topic.content.detail.splitlines()) == expected + cursor = await SourceCursorRepository().load(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + assert cursor is not None and cursor.cursor.sequence == selected + tail_assignment = replace( + assignment, + source_after=selected, + source_through=tail.journal_position, + wave_target=tail.journal_position, + cursor_generation=cursor.generation, + ) + assert (await processor.process(tail_assignment)).outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + assert cursor is not None and cursor.cursor.sequence == tail.journal_position + finally: + await manager.__aexit__(None, None, None) From f0e6e0bbb8767d506af3e05c2efef2a0a348404b Mon Sep 17 00:00:00 2001 From: "rongfeng.frf" Date: Wed, 9 Sep 2026 00:15:56 +0800 Subject: [PATCH 4/5] fix(topic-memory): persist cumulative work budgets Co-authored-by: multica-agent --- docs/en/docs/how-to/troubleshoot.md | 6 +- docs/en/docs/reference/configuration.md | 17 +- docs/en/rfcs/1417_topic_memory.md | 67 +- docs/zh/docs/how-to/troubleshoot.md | 5 +- docs/zh/docs/reference/configuration.md | 15 +- docs/zh/rfcs/1417_topic_memory.md | 48 +- .../builtin/inference/pydantic_ai.py | 23 +- .../builtin/persistence/tables.py | 17 + .../persistence/topic_memory_budget.py | 209 +++++++ .../builtin/runtime/composition.py | 54 +- .../runtime/topic_memory_processing.py | 244 +++++++- .../test_topic_memory_fragment_reduction.py | 15 + .../runtime/test_topic_memory_processing.py | 10 +- .../runtime/test_topic_memory_work_budget.py | 589 ++++++++++++++++++ 14 files changed, 1274 insertions(+), 45 deletions(-) create mode 100644 src/powercontext/builtin/persistence/topic_memory_budget.py create mode 100644 tests/builtin/runtime/test_topic_memory_work_budget.py diff --git a/docs/en/docs/how-to/troubleshoot.md b/docs/en/docs/how-to/troubleshoot.md index e3255396ba..6ff8be299e 100644 --- a/docs/en/docs/how-to/troubleshoot.md +++ b/docs/en/docs/how-to/troubleshoot.md @@ -184,13 +184,15 @@ so the previous database remains available for recovery: Because `pc_scopes.parent_scope_id` is self-referential, keep ancestor Scope rows before their descendants in the exported `pc_scopes` data. If the source predates the three Skill lifecycle tables (`pc_skill_packages`, `pc_agent_skill_targets`, and - `pc_skill_publications`) or the Profile tables, remove the absent tables from their respective layers. + `pc_skill_publications`), the Profile tables, or `pc_topic_memory_work_budgets`, remove the absent tables from their + respective layers. + When a work-budget table exists, restore it together with Cursors so failure allowances survive the migration. Layer 1 contains parents and tables without foreign keys: ```bash obloader -D --csv \ - --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_artifacts,pc_source_cursors,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily' \ + --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_artifacts,pc_source_cursors,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_topic_memory_work_budgets,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily' \ -f ``` diff --git a/docs/en/docs/reference/configuration.md b/docs/en/docs/reference/configuration.md index 8643e1b7e4..c765dca47f 100644 --- a/docs/en/docs/reference/configuration.md +++ b/docs/en/docs/reference/configuration.md @@ -73,7 +73,7 @@ Server settings use the `POWERCONTEXT_SERVER_` prefix. | `POWERCONTEXT_SERVER_RUNTIME_MEMORY_RERANK_CANDIDATE_LIMIT` | `30` | Coarse candidate pool supplied to the reranker | | `POWERCONTEXT_SERVER_RUNTIME_SCHEDULE_SECONDS` | unset | Scheduler interval; unset disables scheduling | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SCHEDULE_SECONDS` | unset | Per-binding Topic Memory automatic-wave interval; unset disables automatic waves | -| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SOURCE_WINDOW_LIMIT` | `10` | Maximum Sources assigned to one Topic Memory Worker | +| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SOURCE_WINDOW_LIMIT` | `10` | Maximum Sources assigned to one Topic Memory Worker, capped at 100 | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_MAX_CANDIDATES` | `20` | Maximum historical Topic candidates considered while processing | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_RRF_THRESHOLD` | `70` | RRF acceptance threshold normalized to `0..100` | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_MIN_CANDIDATES` | `5` | Minimum historical recall count when the threshold returns too few candidates | @@ -105,6 +105,21 @@ Server settings use the `POWERCONTEXT_SERVER_` prefix. | `POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_SCHEDULE_SECONDS` | unset | Experience incubation interval; unset disables that job | | `POWERCONTEXT_SERVER_EXTERNAL_SKILLS` | automatic local project targets | JSON override containing the host identity and explicit Agent Skill targets | +Topic Workers enforce a durable allowance per unadvanced Scope Cursor: 3 attempts, 512 reserved provider requests, +and 64,000,000 estimated token-capacity units across all retries. A Window admits at most 4,194,304 canonical evidence +characters including metadata; nested input is also bounded. Exhaustion preserves Sources, Cursor, Pending, and the +same-Scope tail, and stops further provider calls. Flush and restart do not reset it; inspect +`pc_topic_memory_work_budgets` and structured errors for operator remediation. + +Topic generation accepts `max_tokens`, `temperature`, `top_p`, `top_k`, `seed`, `presence_penalty`, `frequency_penalty`, +`timeout`, `openai_reasoning_effort`, `openai_text_verbosity`, `service_tier`, `openai_service_tier`, +`anthropic_service_tier`, and `anthropic_effort` as bounded scalar settings. Topic Embedding accepts only `dimensions` +and `truncate`. Background/hidden-history/native-tool settings and `extra_body` disable Topic processing while ordinary +inference continues; explicitly configured automatic Topic scheduling fails startup instead. Supported +provider prefixes are `openai`, `openai-chat`, `openai-responses`, `anthropic`, `azure`, `azure-responses`, `deepseek`, +and `openrouter`, plus the local `test` model; Embedding must also be supported by its SDK adapter. Topic SDK transport +retries and automatic continuations are disabled. Non-Topic inference keeps its existing settings behavior. + When the cursor signing secret is unset, a file-backed SQLite Server creates a private key beside its database; other persistent backends create one in the PowerContext user data directory. In-memory SQLite uses a process-local key. Configure the same `POWERCONTEXT_SERVER_CURSOR_SIGNING_SECRET` on every replica so a cursor remains valid after diff --git a/docs/en/rfcs/1417_topic_memory.md b/docs/en/rfcs/1417_topic_memory.md index 1c8a341b07..7e85a8317b 100644 --- a/docs/en/rfcs/1417_topic_memory.md +++ b/docs/en/rfcs/1417_topic_memory.md @@ -189,7 +189,7 @@ Topic Memory is the first consumer. This RFC does not migrate the existing Memor In Journal order, the Topic Window Policy selects the largest contiguous prefix after the Cursor that satisfies both limits: -- no more than `runtime.topic_memory_source_window_limit` Sources, with a default of 10; +- no more than `runtime.topic_memory_source_window_limit` Sources, with a default of 10 and a server ceiling of 100; - estimated Source tokens no greater than 80% of the generation model's context window. `inference.generation_model_context_window_tokens` defaults to 125,000, so the default Source Window limit is 100,000 @@ -219,7 +219,37 @@ reduction stage consolidates a fitting prefix into one intermediate result. It m retain the exact union of evidence IDs, and cannot select a historical identity or return NOOP. The result is limited to one eighth of the stage input budget. A singleton reduction must decrease estimated size; other reductions must decrease item count. Each compaction has a fixed attempt bound of twice its input item count plus one, so a model cannot -create an unbounded compression loop. All model calls use the existing stage request/output limits and Worker timeout. +create an unbounded compression loop. All model calls use the stage request/output limits, durable cumulative budget, +and Worker timeout. + +### Cumulative work and evidence ceilings + +A Topic Window admits at most 4,194,304 canonical evidence characters in total. Each eligible Source is checked before +canonical JSON serialization for at most 65,536 visited values/keys, depth 32, and 4,194,304 text characters; the final +serialized content must also fit the character ceiling. These are Topic processing limits, including metadata, not a +new capture API limit. Oversized or excessively nested captured content remains stored, but Topic processing stops +with `source_complexity_limit`. The selector isolates the earliest Source when projection cannot fit; the Worker +persists rejection instead of repeatedly serializing it on every discovery pass. + +All generation stages (including temporary Topics and reduction), structured retries, and Embedding share a durable +allowance at `(scope_id, binding_name, source_after)`: at most **3 processing attempts**, **512 reserved provider +requests**, and **64,000,000 reserved token-capacity units** across all attempts. Before a generation delegate is +called, a short fenced transaction reserves `generation_max_requests` requests and that many complete stage context +windows. This includes input, schemas, retry transcript, and output capacity, even for fast empty outputs. Embedding +reserves one request per input text and its estimated input tokens; provider batching may use fewer requests. The token +figure is conservative estimated capacity, not exact provider billing. Neither successful underuse, missing usage, +exceptions, cancellation, timeout, nor process death refunds a reservation. + +The Worker uses OpenAI/Anthropic SDK-backed providers with SDK transport retries disabled, including compatible +endpoints. Binding assembly and Worker bootstrap validate the same policy. Topic model settings admit only bounded +scalar sampling, output, timeout, and service-tier settings; Embedding admits only `dimensions` and `truncate`. +`extra_body`, hidden response/conversation history, background generation, native tools, and unsupported providers are +rejected before provider I/O. A suspended response is rejected at the raw model boundary, preventing the inference +library from folding separately billed continuation segments into one logical request. Ordinary non-Topic inference +retains its existing provider behavior. An incompatible configuration does not register a Topic Worker and reports +Topic processing unavailable, including on API-only replicas. If automatic Topic scheduling was explicitly configured, +startup fails with a configuration error instead. These ceilings cannot be raised by model settings, Source metadata, a new Worker, flush generation, +window end, leadership term, or process restart. ## Probe and historical Topic selection @@ -577,7 +607,7 @@ immediately. Whether ordinary Pending immediately forms an automatic recovery wa `last_auto_wave_completed_at` and automatic processing interval. If the old Leader exits before an automatic wave completes, it does not advance that time, so the new Leader immediately resumes a wave that is due but unfinished. A recently completed automatic wave waits only its remaining interval and does not run early merely because leadership -changed. In-memory backoff resets on takeover, so a failed Scope may receive one immediate extra retry. Even if an old +changed. In-memory backoff resets on takeover, but a Topic Scope receives an extra attempt only if its durable work allowance remains available. Even if an old Leader or orphan Worker keeps running, its final transaction rolls back on holder, generation, or Lease validation and cannot change Artifacts, projections, Cursors, Pending, or binding scheduling state. @@ -686,12 +716,29 @@ retry_states[(binding_name, scope_id)] = { ~~~ Retries use jittered exponential backoff at approximately 30 seconds, 1 minute, and 2 minutes, up to a cap of about 30 -minutes. There is no maximum retry count, and the system never skips a Source automatically. Leader failover or process -restart loses the backoff state and permits one immediate extra retry. +minutes. The Supervisor may continue checking a failed key, but Topic Worker's durable allowance caps recomputation. +The attempt counter is committed before Source projection; each provider reservation is committed before I/O. The +third attempt may finish using the remaining provider budget; a subsequent attempt is refused. An exhausted request +or token allowance records `window_provider_budget_exceeded`, and an exhausted attempt count is reported as +`window_attempt_limit`. The selector reads terminal frontiers before materializing Sources or spawning another Worker. + +A terminal frontier retains its Sources, Cursor, Pending, and later same-Scope Sources. It is not a NOOP, success, or +permission to skip evidence. Other Scope keys remain processable. A retry that succeeds within the remaining allowance +publishes normally and can process the tail. There is no automatic allowance reset, retry/reset API, or quarantine +skip operation; terminal input or repeated failures require deliberate operator remediation. Repeated flushes and +restarts cannot authorize additional model cost. + +`pc_topic_memory_work_budgets` stores the frontier, furthest attempted end, opaque attempt ID, attempt count, reserved +requests/tokens, and a bounded failure code; it stores no prompts, Source text, or model outputs. Inspect these columns +together with the Cursor and structured error logs to distinguish terminal work from transient backoff. A new attempt +supersedes publication authority from an earlier attempt in the same leadership term. The row is removed only in the +successful atomic publication transaction alongside Cursor CAS and Topic/index writes; rollback restores it. No +fragment checkpoint or persistent job history is created. The table is additive and is created when an existing +supported database opens. Actual errors—including model calls, output validation, retrieval, enabled Embedding, database commit, Worker crash, and timeout—use the same backoff strategy but must produce structured logs by `stage` and `error_code`. Cursor/Head CAS -conflicts and leadership loss are control signals and do not increase the ordinary failure count. +conflicts and leadership loss are control signals and do not increase the ordinary in-memory failure count. Any already committed Topic attempt or provider reservation remains consumed. Cursor and Head conflicts use a fixed short retry deadline rather than immediate redispatch. The conflicting target releases its current page while delayed, so frozen suffix targets continue to make progress without a hot loop. @@ -794,7 +841,7 @@ The first release adds or uses these deployment-level settings: | `runtime.artifact_processing_role` | `all` | `all / api / background` | | `inference.generation_model_context_window_tokens` | `125000` | Total context window for one generation-model request, including input and output reservation | -The Source Window token limit is fixed at 80% of the generation context window; the total Topic request budget is +The Source Window token limit is fixed at 80% of the generation context window; the per-request Topic context budget is 100%. Neither ratio is public configuration in the first release. Topic Memory reuses the existing generation model, generation timeout, and generation max requests. A vector-enabled @@ -830,8 +877,8 @@ should use consistent settings and record effective values in startup logs. but cannot guarantee semantic quality automatically. - Requiring complete indexes before activating a Revision increases write latency. - The Pending dirty set adds write amplification to Source write transactions. -- Avoiding persistent Jobs, checkpoints, and retry state simplifies the system, but a failure requires recomputing the - whole Window and the progress of an individual task cannot be queried. +- No fragment checkpoints or persistent Jobs are kept. A failure may require whole-Window recomputation within the + durable allowance; terminal exhaustion requires remediation and leaves the same-Scope tail pending. - The `global` Supervisor centralizes resource control, but it may become a bottleneck if several heavyweight Families share the Worker pool in the future. - Source fragmentation and intermediate reduction add generation calls. Reduction coverage is checked structurally, @@ -905,7 +952,7 @@ The following boundaries are explicitly excluded rather than left as open choice - automatic merging of two existing Topic identities; - cross-Scope Topic retrieval; - user-facing APIs to create, update, delete, or retire Topics manually; -- queryable background tasks, cancellation, checkpoints, or persistent retry state; +- queryable background tasks, cancellation, fragment checkpoints, or persistent retry scheduling beyond the work allowance; - in-place conversion of existing FTS-only Topic Heads to a vector-enabled deployment and offline backfill of their vector projections; - an independent Topic Supervisor group and online routing migration. diff --git a/docs/zh/docs/how-to/troubleshoot.md b/docs/zh/docs/how-to/troubleshoot.md index e88d4117c4..ddc072dc79 100644 --- a/docs/zh/docs/how-to/troubleshoot.md +++ b/docs/zh/docs/how-to/troubleshoot.md @@ -179,11 +179,14 @@ collation,但不会包含数据库 URL 或凭据。 源数据库早于三张 Skill 生命周期表(`pc_skill_packages`、`pc_agent_skill_targets` 和 `pc_skill_publications`)或 Profile 表时,应从对应层删除缺失的表。 + 旧版本没有 `pc_topic_memory_work_budgets` 时可从清单移除该表;若该表存在,必须与 Cursor 一起恢复, + 保留已消耗的失败额度,避免迁移后重置累计成本。 + 第 1 层包含父表和无外键的表: ```bash obloader -D --csv \ - --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_artifacts,pc_source_cursors,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily' \ + --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_artifacts,pc_source_cursors,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_topic_memory_work_budgets,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily' \ -f ``` diff --git a/docs/zh/docs/reference/configuration.md b/docs/zh/docs/reference/configuration.md index 4ce5025557..520f028456 100644 --- a/docs/zh/docs/reference/configuration.md +++ b/docs/zh/docs/reference/configuration.md @@ -69,7 +69,7 @@ Server 配置使用 `POWERCONTEXT_SERVER_` 前缀。 | `POWERCONTEXT_SERVER_RUNTIME_MEMORY_RERANK_CANDIDATE_LIMIT` | `30` | 交给 reranker 的粗排候选池大小 | | `POWERCONTEXT_SERVER_RUNTIME_SCHEDULE_SECONDS` | 未设置 | Scheduler 间隔;未设置即不启用 | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SCHEDULE_SECONDS` | 未设置 | Topic Memory 按 binding 的自动波次间隔;未设置即关闭自动波次 | -| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SOURCE_WINDOW_LIMIT` | `10` | 单个 Topic Memory Worker 最多处理的 Source 数量 | +| `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_SOURCE_WINDOW_LIMIT` | `10` | 单个 Topic Memory Worker 最多处理的 Source 数量,硬上限为 100 | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_MAX_CANDIDATES` | `20` | 处理时考虑的历史 Topic 候选上限 | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_RRF_THRESHOLD` | `70` | 归一化到 `0..100` 的 RRF 接受阈值 | | `POWERCONTEXT_SERVER_RUNTIME_TOPIC_MEMORY_HISTORY_MIN_CANDIDATES` | `5` | 达到阈值的候选过少时保证的最小历史召回数 | @@ -101,6 +101,19 @@ Server 配置使用 `POWERCONTEXT_SERVER_` 前缀。 | `POWERCONTEXT_SERVER_RUNTIME_EXPERIENCE_SCHEDULE_SECONDS` | 未设置 | Experience 孵化间隔;未设置即不启用该 job | | `POWERCONTEXT_SERVER_EXTERNAL_SKILLS` | 自动生成本机项目 target | 覆盖默认值的 host identity 和显式 Agent Skill targets JSON object | +Topic Worker 对尚未推进的 Scope Cursor 强制使用持久额度:跨全部重试最多 3 次尝试、512 次预留 provider 请求和 +64,000,000 个估算 token 容量单位。Window 的 canonical evidence(包含 metadata)最多 4,194,304 个字符,并限制 +嵌套复杂度。耗尽后保留 Source、Cursor、Pending 和同 Scope 尾部,停止后续 provider 调用;flush 和重启均不重置。 +运维可检查 `pc_topic_memory_work_budgets` 与结构化错误以明确修复。 + +Topic generation 只允许有界标量设置:`max_tokens`、`temperature`、`top_p`、`top_k`、`seed`、`presence_penalty`、 +`frequency_penalty`、`timeout`、`openai_reasoning_effort`、`openai_text_verbosity`、`service_tier`、 +`openai_service_tier`、`anthropic_service_tier`、`anthropic_effort`;Topic Embedding 只允许 `dimensions` 和 `truncate`。 +background、隐藏历史、native tools 和 `extra_body` 会使 Topic 处理不可用,普通推理仍可继续;显式配置自动 Topic 调度时 +则启动失败。支持的 provider 前缀为 `openai`、`openai-chat`、 +`openai-responses`、`anthropic`、`azure`、`azure-responses`、`deepseek`、`openrouter`,以及本地 `test` 模型;Embedding +还必须受其 SDK adapter 支持。Topic 禁用 SDK transport 重试和自动 continuation,非 Topic 推理保留既有设置行为。 + 未设置 cursor 签名密钥时,使用文件 SQLite 的 Server 会在数据库旁创建权限受限的密钥文件;其他持久化后端会在 PowerContext 用户数据目录创建密钥。内存 SQLite 使用进程内密钥。多副本部署必须为所有副本配置相同的 `POWERCONTEXT_SERVER_CURSOR_SIGNING_SECRET`,这样重启或下一请求落到其他副本后,已签发 cursor 仍然有效。 diff --git a/docs/zh/rfcs/1417_topic_memory.md b/docs/zh/rfcs/1417_topic_memory.md index 02e07fce0e..b4ef806e7c 100644 --- a/docs/zh/rfcs/1417_topic_memory.md +++ b/docs/zh/rfcs/1417_topic_memory.md @@ -198,6 +198,29 @@ tokens。一次实际 generation 请求仍必须满足: 单项归并必须缩小估算体积,多项归并必须减少项数;每次压缩最多尝试“输入项数的两倍加一”次,防止模型造成 无限压缩循环。所有调用继续使用现有阶段请求/输出限制与 Worker timeout。 +### 累计工作量与证据上限 + +一个 Topic Window 最多接纳 100 条 Source(配置默认值仍为 10),canonical evidence 合计最多 4,194,304 个字符。 +每条 eligible Source 在 canonical JSON 序列化前限制访问的值/键总数不超过 65,536、深度不超过 32、文本字符总数 +不超过 4,194,304;最终序列化内容也必须满足字符上限。这是包含 metadata 的 Topic 处理边界,不是新的 capture +API 限制。过大或过深的捕获内容仍保留,但 Topic 处理持久记录 `source_complexity_limit`。Selector 无法投影整个 +候选 Window 时先隔离最早的单条 Source,由 Worker 记录拒绝,避免每次发现任务都重复序列化失败内容。 + +所有生成阶段(包括 temporary、reduction)、结构化重试和 Embedding 共用 `(scope_id, binding_name, source_after)` +上的持久额度:跨全部重试最多 **3 次处理尝试、512 次预留 provider 请求、64,000,000 个预留 token 容量单位**。 +每次调用生成 delegate 前,先在短 fenced 事务中预留 `generation_max_requests` 次请求及同样数量的完整阶段 context +容量,涵盖输入、schema、重试 transcript 与输出;快速空响应也不能绕过。Embedding 按每条输入文本预留一次请求及 +其估算输入 token,provider 批处理可以实际使用更少请求。token 数是保守估算容量,不是精确账单。未使用的额度、 +缺失 usage、异常、取消、timeout 和进程死亡都不退还已预留额度。 + +Worker 使用由 OpenAI/Anthropic SDK 支持的 provider(含兼容端点),并禁用 SDK 内部 transport 重试。 +binding 装配及 Worker 启动时执行相同校验,拒绝不支持的 provider。Topic 生成设置只允许有界标量形式的采样、输出、timeout 和 +service-tier 参数;Embedding 只允许 `dimensions` 与 `truncate`。拒绝 `extra_body`、隐藏 response/conversation 历史、 +background 生成和 native tools,避免未计量工作。底层模型响应边界会拒绝 suspended response,阻止推理库把分别收费 +的 continuation 合并计为一次请求。普通非 Topic 推理保留既有行为;不兼容配置不注册 Topic Worker,并明确声明 Topic +处理不可用(含 API-only 副本)。若显式配置了自动 Topic 调度,则启动时返回配置错误。模型设置、Source metadata、新 Worker、flush +generation、Window 终点、换主和重启均不能提高或重置这些硬上限。 + ## Probe 与历史 Topic 选择 Worker 首先读取当前 Source Window。服务端标记为 `lineage_only` 的 Source 在 token 估算与生成之前排除,其 @@ -522,7 +545,7 @@ Lease 过期后,成功通过原子更新接管的候选者递增 `supervisor_g binding 调度状态重新发现工作。未完成的显式 flush 立即恢复;普通 Pending 是否立即形成自动恢复波次,由对应 binding 的 `last_auto_wave_completed_at` 与自动处理间隔决定。旧 Leader 在自动波次完成前退出时不会推进该时间,因此新 Leader 会立即恢复已经到期但未完成的波次;最近已经完成的自动波次则只等待剩余间隔,不因换主提前执行。内存退避在接管后清空, -因此失败 Scope 允许立即额外重试一次。旧 Leader 或孤儿 Worker 即使继续运行,其最终事务也会因 holder、generation 或 +但失败 Topic Scope 只有在持久工作额度仍可用时才能获得额外尝试。旧 Leader 或孤儿 Worker 即使继续运行,其最终事务也会因 holder、generation 或 Lease 校验失败而整体回滚,不能写入 Artifact、projection、Cursor、Pending 或 binding 调度状态。 SQLite 不提供多副本自动接管;进程重启就是它的恢复路径。新 Supervisor 启动时递增 generation,使旧孤儿 Worker @@ -613,12 +636,23 @@ retry_states[(binding_name, scope_id)] = { } ~~~ -采用带抖动的指数退避:约 30 秒、1 分钟、2 分钟,直至约 30 分钟上限;不设置最大重试次数,也不自动跳过 -Source。主备切换或进程重启会丢失退避状态,并允许立即额外重试一次。 +采用带抖动的指数退避:约 30 秒、1 分钟、2 分钟,直至约 30 分钟上限。Supervisor 可继续检查失败键,但 Topic +Worker 的持久额度限制整窗重算次数。尝试计数在 Source 投影前提交,provider 额度在调用前提交。第三次尝试可用剩余 +provider 额度完成工作,但不能再开始第四次。请求或 token 额度耗尽记录 `window_provider_budget_exceeded`,尝试次数 +耗尽报告 `window_attempt_limit`。Selector 在 materialize Source 或启动 Worker 前检查终止状态。 + +终止的 frontier 保留 Source、Cursor、Pending 以及同 Scope 尾部;不会视为 NOOP、成功或跳过证据的授权。其他 Scope +仍可处理。剩余额度内重试成功后仍按原合同发布,并继续处理尾部。不提供自动额度重置、retry/reset API 或 quarantine +跳过操作;终止输入或重复失败需要运维明确修复,反复 flush 或重启不能重新授权模型成本。 + +`pc_topic_memory_work_budgets` 保存 frontier、尝试过的最远终点、不透明 attempt ID、尝试次数、预留请求/token 与有界 +failure code,不保存 prompt、Source 原文或模型输出。可结合 Cursor 和结构化错误日志检查这些列,区分持久终止与暂时 +退避。同一任期内新尝试也会使旧尝试失去发布权。只有成功原子发布事务才能与 Cursor CAS、Topic/index 写入一起删除 +该记录;回滚会恢复额度记录。不创建分片 checkpoint 或持久 Job history。该新增表会在现有受支持数据库打开时创建。 模型调用、输出校验、检索、启用后的 Embedding、数据库提交、Worker crash 和 timeout 等实际错误采用同一退避策略, 但必须按 `stage` 和 `error_code` 写结构化日志。Cursor/Head CAS 冲突与 leadership lost 是控制信号,不增加 -普通失败次数。 +普通内存失败次数;已提交的 Topic 尝试及 provider 预留额度仍然消耗。 Cursor 与 Head conflict 使用固定的短 retry deadline,而不是立即重新派发;冲突目标在延后期间释放当前页,使冻结 尾页继续推进且不会形成热循环。 @@ -718,7 +752,7 @@ score,并交错填充结果。请求的 `max_bytes` 是最终输出的统一 | `runtime.artifact_processing_role` | `all` | `all / api / background` | | `inference.generation_model_context_window_tokens` | `125000` | 生成模型单次请求的总上下文窗口,包含输入和输出预留 | -Source Window token 上限固定派生为 generation context window 的 80%;Topic 总请求预算为 100%。两个比例首版 +Source Window token 上限固定派生为 generation context window 的 80%;Topic 单请求 context 预算为 100%。两个比例首版 不是公共配置。 Topic Memory 复用现有 generation model、generation timeout 和 generation max requests。向量部署还复用现有 @@ -745,7 +779,7 @@ configuration error 失败;Runtime 不创建或回填这些历史向量,也 - 自动演进可能错误新建或错误更新主题;不可变 Revision 与 lineage 提供审计能力,但不能自动保证语义质量。 - 只有完整索引才能激活 Revision,会增加写入延迟。 - Pending dirty set 增加 Source 写事务的写放大。 -- 不持久化 Job、checkpoint 和 retry state 简化了系统,但失败后需要重算整个 Window,且无法查询单次任务进度。 +- 不保留分片 checkpoint 或持久 Job;失败可在持久额度内整窗重算,额度耗尽需要明确修复,同 Scope 尾部保留待处理。 - `global` Supervisor 统一资源控制,但未来多个重型 Family 共用 Worker pool 时可能成为瓶颈。 - Source 分段和中间归并增加模型调用次数;结构校验保护输入覆盖,但信息保真的措辞仍依赖模型,超长历史上下文仍可能失败关闭。 @@ -806,7 +840,7 @@ Revision 拥有不同通道数,融合排名不可比较,因此保留旧 acti - 两个已有 Topic identities 的自动合并; - 跨 Scope Topic 检索; - 用户手动管理 Topic 的 create/update/delete/retire API; -- 可查询的后台任务、取消、checkpoint 或持久化 retry state; +- 可查询的后台任务、取消、分片 checkpoint 或工作额度之外的持久 retry 调度; - 将已有 FTS-only Topic Heads 原地升级为向量部署,以及历史向量投影的离线回填; - 独立 Topic Supervisor group 与在线路由迁移。 diff --git a/src/powercontext/builtin/inference/pydantic_ai.py b/src/powercontext/builtin/inference/pydantic_ai.py index 8ebfab64b3..d1653ccdb4 100644 --- a/src/powercontext/builtin/inference/pydantic_ai.py +++ b/src/powercontext/builtin/inference/pydantic_ai.py @@ -23,6 +23,7 @@ from typing import Generic, Self, TypeVar, cast from pydantic import BaseModel, Field +from typing_extensions import override from powercontext.builtin.artifacts.memory.canonical import canonical_embedding from powercontext.builtin.artifacts.memory.models import EmbeddingProfile @@ -81,8 +82,9 @@ def __init__(self, code: str, detail: object | None = None) -> None: UsageLimitExceeded, UserError, ) - from pydantic_ai.messages import ModelRequest, UserPromptPart + from pydantic_ai.messages import ModelMessage, ModelRequest, ModelResponse, UserPromptPart from pydantic_ai.models import Model, ModelRequestParameters + from pydantic_ai.models.wrapper import WrapperModel from pydantic_ai.settings import ModelSettings, merge_model_settings from pydantic_ai.usage import RunUsage, UsageLimits from pydantic_core import PydanticSerializationError @@ -102,6 +104,23 @@ class InferenceLimits(BaseModel): max_requests: int = Field(default=2, ge=1) max_output_tokens_per_request: int | None = Field(default=None, ge=1) output_tokens_limit: int | None = Field(default=None, ge=1) + allow_continuations: bool = True + + +class _CompleteResponseModel(WrapperModel): + """Do not let Agent fold separately billed continuations into one request.""" + + @override + async def request( + self, + messages: list[ModelMessage], + model_settings: ModelSettings | None, + model_request_parameters: ModelRequestParameters, + ) -> ModelResponse: + response = await self.wrapped.request(messages, model_settings, model_request_parameters) + if response.state != "complete": + raise InvalidInferenceOutputError("generate", "provider continuation is not allowed") + return response class PydanticAIStructuredGenerator(Generic[InputT, OutputT]): @@ -135,7 +154,7 @@ def __init__( ModelSettings(max_tokens=self._limits.max_output_tokens_per_request), ) self._agent = Agent( - model, + model if self._limits.allow_continuations else _CompleteResponseModel(model), output_type=PromptedOutput(output_type), instructions=instructions, model_settings=bounded_settings, diff --git a/src/powercontext/builtin/persistence/tables.py b/src/powercontext/builtin/persistence/tables.py index 61ecf6f0e6..9a6ebcd38a 100644 --- a/src/powercontext/builtin/persistence/tables.py +++ b/src/powercontext/builtin/persistence/tables.py @@ -488,6 +488,22 @@ def _entry_text_type(): Column("last_auto_wave_completed_at", DateTime(timezone=False)), ) +TOPIC_MEMORY_WORK_BUDGETS_TABLE = Table( + "pc_topic_memory_work_budgets", + SHARED_METADATA, + Column("scope_id", identity_string(MAX_SCOPE_ID_LENGTH), primary_key=True), + Column("binding_name", identity_string(MAX_BINDING_NAME_LENGTH), primary_key=True), + Column("source_after", BigInteger, primary_key=True), + Column("source_through", BigInteger, nullable=False), + Column("attempt_id", identity_string(36), nullable=False), + Column("attempts", Integer, nullable=False), + Column("requests", BigInteger, nullable=False), + Column("tokens", BigInteger, nullable=False), + Column("failure_code", String(64), nullable=False), + CheckConstraint("source_after >= 0 AND source_through > source_after", name="ck_pc_topic_budget_window"), + CheckConstraint("attempts > 0 AND requests >= 0 AND tokens >= 0", name="ck_pc_topic_budget_usage"), +) + TOPIC_MEMORY_REVISION_PUBLICATIONS_TABLE = Table( "pc_topic_memory_revision_publications", @@ -807,6 +823,7 @@ def _entry_text_type(): SOURCE_CURSORS_TABLE, ARTIFACT_PROCESSING_LEASES_TABLE, ARTIFACT_PROCESSING_BINDING_STATES_TABLE, + TOPIC_MEMORY_WORK_BUDGETS_TABLE, ARTIFACT_PROCESSING_PENDING_TABLE, ARTIFACT_PROCESSING_AUTO_WAVE_TARGETS_TABLE, CONNECTOR_CHECKPOINTS_TABLE, diff --git a/src/powercontext/builtin/persistence/topic_memory_budget.py b/src/powercontext/builtin/persistence/topic_memory_budget.py new file mode 100644 index 0000000000..fed293117f --- /dev/null +++ b/src/powercontext/builtin/persistence/topic_memory_budget.py @@ -0,0 +1,209 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Durable, pre-I/O reservations for one unadvanced Topic Memory frontier.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any +from uuid import uuid4 + +from sqlalchemy import delete, insert, select, update +from sqlalchemy.ext.asyncio import AsyncConnection + +from powercontext.builtin.artifacts.topic_memory.generation import TopicMemoryGenerationError +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.database import AsyncDatabase +from powercontext.builtin.persistence.errors import GenerationConflictError +from powercontext.builtin.persistence.supervision import ArtifactProcessingFence, ArtifactProcessingLeaseRepository +from powercontext.builtin.persistence.tables import SOURCE_JOURNAL_HEADS_TABLE, TOPIC_MEMORY_WORK_BUDGETS_TABLE + +# Server-owned ceilings, shared by ALL attempts and stages at the same Cursor. +MAX_TOPIC_MEMORY_WORK_ATTEMPTS = 3 +MAX_TOPIC_MEMORY_WORK_REQUESTS = 512 +MAX_TOPIC_MEMORY_WORK_TOKENS = 64_000_000 + + +def exhausted_reason(row: Mapping[Any, Any]) -> str: + if row["failure_code"]: + return str(row["failure_code"]) + if row["attempts"] >= MAX_TOPIC_MEMORY_WORK_ATTEMPTS: + return "window_attempt_limit" + if row["requests"] >= MAX_TOPIC_MEMORY_WORK_REQUESTS or row["tokens"] >= MAX_TOPIC_MEMORY_WORK_TOKENS: + return "window_provider_budget_exceeded" + return "" + + +async def require_topic_memory_work_available( + connection: AsyncConnection, scope_id: str, binding_name: str, source_after: int +) -> None: + """Cheap selector guard: terminal frontiers never spawn or reproject Sources.""" + table = TOPIC_MEMORY_WORK_BUDGETS_TABLE + row = ( + ( + await connection.execute( + select(table).where( + table.c.scope_id == scope_id, + table.c.binding_name == binding_name, + table.c.source_after == source_after, + ) + ) + ) + .mappings() + .one_or_none() + ) + if row is not None and (reason := exhausted_reason(row)): + raise TopicMemoryGenerationError(reason) + + +class TopicMemoryWorkBudget: + """Commit worst-case charges before I/O; never refund ambiguous/failed work. + + Identity excludes Worker, lease term, flush generation and window end: none + of those can reset the allowance before the authoritative Cursor advances. + A fresh attempt supersedes old same-term work, including its publication. + """ + + def __init__( + self, + database: AsyncDatabase, + *, + scope_id: str, + binding_name: str, + source_after: int, + source_through: int, + cursor_generation: int | None, + fence: ArtifactProcessingFence, + ) -> None: + self.database = database + self.scope_id = scope_id + self.binding_name = binding_name + self.source_after = source_after + self.source_through = source_through + self.cursor_generation = cursor_generation + self.fence = fence + self.attempt_id = str(uuid4()) + + def _key(self): + table = TOPIC_MEMORY_WORK_BUDGETS_TABLE + return ( + table.c.scope_id == self.scope_id, + table.c.binding_name == self.binding_name, + table.c.source_after == self.source_after, + ) + + async def _lock(self, connection: AsyncConnection) -> None: + await ArtifactProcessingLeaseRepository().require_fence(connection, self.fence) + # Same lock order as publication. This also starts SQLite's write txn. + await connection.execute( + update(SOURCE_JOURNAL_HEADS_TABLE) + .where(SOURCE_JOURNAL_HEADS_TABLE.c.scope_id == self.scope_id) + .values(position=SOURCE_JOURNAL_HEADS_TABLE.c.position) + ) + cursor = await SourceCursorRepository().load(connection, self.scope_id, self.binding_name, for_update=True) + if (0 if cursor is None else cursor.cursor.sequence) != self.source_after or ( + None if cursor is None else cursor.generation + ) != self.cursor_generation: + raise GenerationConflictError( + self.binding_name, self.cursor_generation, None if cursor is None else cursor.generation + ) + + async def begin(self) -> None: + table = TOPIC_MEMORY_WORK_BUDGETS_TABLE + reason = "" + async with self.database.transaction() as connection: + await self._lock(connection) + row = ( + (await connection.execute(select(table).where(*self._key()).with_for_update())).mappings().one_or_none() + ) + if row is None: + await connection.execute( + insert(table).values( + scope_id=self.scope_id, + binding_name=self.binding_name, + source_after=self.source_after, + source_through=self.source_through, + attempt_id=self.attempt_id, + attempts=1, + requests=0, + tokens=0, + failure_code="", + ) + ) + elif reason := exhausted_reason(row): + await connection.execute(update(table).where(*self._key()).values(failure_code=reason)) + else: + await connection.execute( + update(table) + .where(*self._key()) + .values( + attempts=row["attempts"] + 1, + attempt_id=self.attempt_id, + source_through=max(self.source_through, row["source_through"]), + ) + ) + if reason: + raise TopicMemoryGenerationError(reason) + + async def _current(self, connection: AsyncConnection): + table = TOPIC_MEMORY_WORK_BUDGETS_TABLE + row = (await connection.execute(select(table).where(*self._key()).with_for_update())).mappings().one_or_none() + if row is None or row["attempt_id"] != self.attempt_id: + raise TopicMemoryGenerationError("window_attempt_superseded") + return row + + async def reserve(self, *, requests: int, tokens: int) -> None: + if requests < 1 or tokens < 1: + raise TopicMemoryGenerationError("invalid_work_reservation") + table = TOPIC_MEMORY_WORK_BUDGETS_TABLE + reason = "" + async with self.database.transaction() as connection: + await self._lock(connection) + row = await self._current(connection) + reason = str(row["failure_code"]) + if not reason and ( + row["requests"] + requests > MAX_TOPIC_MEMORY_WORK_REQUESTS + or row["tokens"] + tokens > MAX_TOPIC_MEMORY_WORK_TOKENS + ): + reason = "window_provider_budget_exceeded" + values = ( + {"failure_code": reason} + if reason + else {"requests": row["requests"] + requests, "tokens": row["tokens"] + tokens} + ) + await connection.execute(update(table).where(*self._key()).values(**values)) + # Raise AFTER committing the terminal marker, never roll it back. + if reason: + raise TopicMemoryGenerationError(reason) + + async def fail(self, reason: str) -> None: + """Persist a deterministic input rejection without storing source text.""" + async with self.database.transaction() as connection: + await self._lock(connection) + await self._current(connection) + await connection.execute( + update(TOPIC_MEMORY_WORK_BUDGETS_TABLE) + .where(*self._key()) + .values( + failure_code=reason, + ) + ) + + async def complete(self, connection: AsyncConnection) -> None: + """Called only inside the atomic publisher, before its Cursor CAS.""" + row = await self._current(connection) + if row["failure_code"]: + raise TopicMemoryGenerationError(str(row["failure_code"])) + await connection.execute(delete(TOPIC_MEMORY_WORK_BUDGETS_TABLE).where(*self._key())) diff --git a/src/powercontext/builtin/runtime/composition.py b/src/powercontext/builtin/runtime/composition.py index 7cc85c51ea..7b8d48d15d 100644 --- a/src/powercontext/builtin/runtime/composition.py +++ b/src/powercontext/builtin/runtime/composition.py @@ -111,6 +111,7 @@ TopicMemoryWindowSelector, TopicMemoryWorkerSpec, run_topic_memory_worker, + validate_topic_memory_provider_settings, ) from powercontext.builtin.sources import ( BUILTIN_SOURCE_REGISTRY, @@ -147,6 +148,7 @@ def __init__(self, issue: str) -> None: "Topic Memory processing requires child-reconstructible inference resources" ), "topic-memory-generation-budget": "Topic Memory generation budget is not executable", + "topic-memory-provider-budget": "Topic Memory workers require OpenAI/Anthropic SDK providers with transport retries disabled and bounded stateless model settings", "topic-memory-generation": "Topic Memory processing requires a configured generation model", "topic-memory-database": "Topic Memory workers require file-backed SQLite; an in-memory database cannot be shared with spawned workers", "database": "unsupported built-in database", @@ -492,6 +494,12 @@ def _topic_memory_processing_bindings( raise BuiltinConfigurationError("topic-memory-child-resources") if isinstance(config.database, SQLiteConfig) and config.database.is_in_memory: raise BuiltinConfigurationError("topic-memory-database") + if not _topic_memory_provider_available(config): + # Generic inference settings may be valid for other operations. Do not + # register an unusable Topic worker or reject those unrelated features. + if config.runtime.topic_memory_schedule_seconds is not None: + validate_topic_memory_provider_settings(config.inference) + return configured try: budget = topic_memory_stage_budget( context_window_tokens=config.inference.generation_model_context_window_tokens, @@ -529,10 +537,20 @@ def _topic_memory_processing_available( """Report declared cross-role processing ability without probing worker liveness.""" return any(binding.binding_name == TOPIC_MEMORY_SOURCE_WINDOW_BINDING for binding in bindings) or ( - config.runtime.artifact_processing_role == "api" and config.inference.generation_model is not None + config.runtime.artifact_processing_role == "api" + and config.inference.generation_model is not None + and _topic_memory_provider_available(config) ) +def _topic_memory_provider_available(config: BuiltinConfig) -> bool: + try: + validate_topic_memory_provider_settings(config.inference) + except BuiltinConfigurationError: + return False + return True + + @asynccontextmanager async def _open_artifact_processing_supervisor( config: BuiltinConfig, @@ -996,6 +1014,7 @@ async def _open_pydantic_ai_model( headers: Mapping[str, SecretStr], resources: AsyncExitStack, instrumentation: InstrumentationSettings | None, + disable_provider_retries: bool = False, ) -> tuple[Model, Model]: from pydantic_ai.models import infer_model from pydantic_ai.models.instrumented import InstrumentedModel @@ -1004,7 +1023,7 @@ async def _open_pydantic_ai_model( raise BuiltinConfigurationError("inference-endpoint-provider") inferred_model = ( infer_model(model_name) - if base_url is None and not headers + if base_url is None and not headers and not disable_provider_retries else infer_model( model_name, provider_factory=_provider_factory( @@ -1012,6 +1031,7 @@ async def _open_pydantic_ai_model( headers, workload="generation", resources=resources, + disable_retries=disable_provider_retries, ), ) ) @@ -1026,6 +1046,33 @@ def _provider_factory( *, workload: Literal["generation", "embedding"], resources: AsyncExitStack, + disable_retries: bool = False, +) -> Callable[[str], Provider[Any]]: + create = _unbounded_provider_factory(base_url, headers, workload=workload, resources=resources) + if not disable_retries: + return create + + def bounded(provider_name: str) -> Provider[Any]: + from anthropic import AsyncAnthropic + from openai import AsyncOpenAI + + provider = create(provider_name) + client = provider.client + if not isinstance(client, (AsyncOpenAI, AsyncAnthropic)): + # No unmetered provider-specific retry policy in a Topic Worker. + raise BuiltinConfigurationError("topic-memory-provider-budget") + client.max_retries = 0 + return provider + + return bounded + + +def _unbounded_provider_factory( + base_url: AnyHttpUrl | None, + headers: Mapping[str, SecretStr], + *, + workload: Literal["generation", "embedding"], + resources: AsyncExitStack, ) -> Callable[[str], Provider[Any]]: from pydantic_ai.providers import infer_provider @@ -1099,6 +1146,8 @@ async def _embedding_models( settings: InferenceConfig, resources: AsyncExitStack, instrumentation: InstrumentationSettings | None, + *, + disable_provider_retries: bool = False, ) -> tuple[EmbeddingModel | None, EmbeddingModel | None]: if settings.embedding_model is None: return None, None @@ -1115,6 +1164,7 @@ async def _embedding_models( settings.embedding_headers, workload="embedding", resources=resources, + disable_retries=disable_provider_retries, ) def provider_factory(provider_name: str) -> Provider[Any]: diff --git a/src/powercontext/builtin/runtime/topic_memory_processing.py b/src/powercontext/builtin/runtime/topic_memory_processing.py index 508a2f3c0f..af81fcc2d3 100644 --- a/src/powercontext/builtin/runtime/topic_memory_processing.py +++ b/src/powercontext/builtin/runtime/topic_memory_processing.py @@ -21,9 +21,10 @@ import logging from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence from contextlib import AsyncExitStack, asynccontextmanager, nullcontext -from dataclasses import dataclass, field +from contextvars import ContextVar +from dataclasses import dataclass, field, replace from datetime import UTC, datetime -from typing import Any, cast +from typing import Any, Generic, TypeVar, cast from uuid import uuid4 from pydantic import BaseModel, Field @@ -80,6 +81,7 @@ ) from powercontext.builtin.inference import ( EmbeddingModel, + GenerationResult, StructuredGenerator, TokenEstimator, character_token_estimator, @@ -92,12 +94,18 @@ from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository from powercontext.builtin.persistence.tables import SOURCE_JOURNAL_HEADS_TABLE from powercontext.builtin.persistence.topic_memory import TopicMemoryRepository +from powercontext.builtin.persistence.topic_memory_budget import ( + MAX_TOPIC_MEMORY_WORK_REQUESTS, + MAX_TOPIC_MEMORY_WORK_TOKENS, + TopicMemoryWorkBudget, + require_topic_memory_work_available, +) from powercontext.builtin.runtime.artifact_processing import ( ArtifactProcessingWorkAssignment, ArtifactProcessingWorkerCompletion, ArtifactProcessingWorkerOutcome, ) -from powercontext.builtin.runtime.config import BuiltinConfig +from powercontext.builtin.runtime.config import BuiltinConfig, InferenceConfig from powercontext.builtin.source_eligibility import is_generation_eligible from powercontext.builtin.sources import ( CONTENT_SOURCE_NAME, @@ -116,6 +124,30 @@ logger = logging.getLogger(__name__) _PLANNER_TEXT_PREVIEW_LENGTH = 512 +MAX_TOPIC_MEMORY_SOURCE_CHARACTERS = 4 * 1024 * 1024 +MAX_TOPIC_MEMORY_SOURCE_NODES = 65_536 +MAX_TOPIC_MEMORY_SOURCE_DEPTH = 32 +MAX_TOPIC_MEMORY_WINDOW_SOURCES = 100 + +InputT = TypeVar("InputT", bound=BaseModel) +OutputT = TypeVar("OutputT") + + +class _ReservedTopicMemoryGenerator(Generic[InputT, OutputT]): + def __init__( + self, + delegate: StructuredGenerator[InputT, OutputT], + reserve: Callable[[BaseModel, str], Awaitable[None]], + stage: str, + ) -> None: + self.delegate = delegate + self.reserve = reserve + self.stage = stage + + async def generate(self, value: InputT, /) -> GenerationResult[OutputT]: + await self.reserve(value, self.stage) + return await self.delegate.generate(value) + UsageReporter = Callable[[ModelUsagePurpose, ModelUsageOperation, Any], Awaitable[None]] @@ -134,9 +166,15 @@ class TopicMemoryStageSet: input_tokens_limit: int fixed_prompts: Mapping[str, str] = field(default_factory=dict) reducer: StructuredGenerator[TopicMemoryReductionInput, TopicMemoryReductionOutput] | None = None + max_requests: int = 2 + transcript_reserve: int | None = None def __post_init__(self) -> None: - if self.input_tokens_limit < 1: + if ( + self.input_tokens_limit < 1 + or self.max_requests < 1 + or (self.transcript_reserve is not None and self.transcript_reserve < 1) + ): raise ValueError("Topic Memory input token limit must be positive") # noqa: TRY003 def fits(self, value: BaseModel, stage: str = "") -> bool: @@ -194,14 +232,23 @@ def __init__( ) async def select(self, scope_id: str, source_after: int, source_ceiling: int, /) -> int: + source_ceiling = min(source_ceiling, source_after + MAX_TOPIC_MEMORY_WINDOW_SOURCES) limit = source_ceiling - source_after async with self._database.transaction() as connection: + await require_topic_memory_work_available( + connection, scope_id, TOPIC_MEMORY_SOURCE_WINDOW_BINDING, source_after + ) stored = await self._sources.list(connection, scope_id, after=source_after, limit=limit) if len(stored) != limit or tuple(item.journal_position for item in stored) != tuple( range(source_after + 1, source_ceiling + 1) ): raise TopicMemoryGenerationError("source_window_changed") - evidence = await _project_window(stored, self._sources) + try: + evidence = await _project_window(stored, self._sources) + except TopicMemoryGenerationError: + # Let a singleton Worker persist rejection at the current frontier. + # Earlier healthy Sources still make progress before a bad suffix. + return source_after + 1 return await asyncio.to_thread(self._largest_prefix, evidence, source_after, source_ceiling) def _largest_prefix(self, evidence: tuple[TopicMemoryEvidence, ...], source_after: int, source_ceiling: int) -> int: @@ -232,12 +279,14 @@ def __init__( self._cursors = SourceCursorRepository() if cursors is None else cursors self._leases = ArtifactProcessingLeaseRepository() if leases is None else leases - async def publish( + async def publish( # noqa: C901 self, assignment: ArtifactProcessingWorkAssignment, evidence: Mapping[str, StoredSource], operations: Sequence[PreparedTopicMemoryOperation], /, + *, + work_budget: TopicMemoryWorkBudget | None = None, ) -> None: if ( assignment.binding_name != TOPIC_MEMORY_SOURCE_WINDOW_BINDING @@ -308,6 +357,8 @@ async def publish( cited_sources = {(item.source_type, item.source_id) for item in operation.draft.sources} if not cited_sources or not cited_sources <= allowed_sources: raise TopicMemoryGenerationError("invalid_evidence") + if work_budget is not None: + await work_budget.complete(connection) await self._cursors.save( connection, assignment.scope_id, @@ -356,7 +407,23 @@ def __init__( self._database = database self._sources = sources self._topics = topics - self._stages = stages + self._work_budget: ContextVar[TopicMemoryWorkBudget | None] = ContextVar( + "topic_memory_work_budget", default=None + ) + self._local_requests = 0 + self._local_tokens = 0 + self._stages = replace( + stages, + probe=_ReservedTopicMemoryGenerator(stages.probe, self._reserve_stage, "probe"), + global_evolver=_ReservedTopicMemoryGenerator(stages.global_evolver, self._reserve_stage, "global"), + planner=_ReservedTopicMemoryGenerator(stages.planner, self._reserve_stage, "planner"), + evolver=_ReservedTopicMemoryGenerator(stages.evolver, self._reserve_stage, "evolve"), + temporary=_ReservedTopicMemoryGenerator(stages.temporary, self._reserve_stage, "temporary"), + reconciler=_ReservedTopicMemoryGenerator(stages.reconciler, self._reserve_stage, "reconcile"), + reducer=None + if stages.reducer is None + else _ReservedTopicMemoryGenerator(stages.reducer, self._reserve_stage, "reduce"), + ) self._publisher = publisher self._embedding_model = embedding_model self._usage_reporter = usage_reporter @@ -371,22 +438,77 @@ async def process(self, assignment: ArtifactProcessingWorkAssignment, /) -> Arti or not 0 <= assignment.source_after < assignment.source_through <= assignment.wave_target ): raise TopicMemoryGenerationError("invalid_window") + budget = TopicMemoryWorkBudget( + self._database, + scope_id=assignment.scope_id, + binding_name=assignment.binding_name, + source_after=assignment.source_after, + source_through=assignment.source_through, + cursor_generation=assignment.cursor_generation, + fence=assignment.fence, + ) + token = self._work_budget.set(budget) try: - stored = await self._read_window(assignment) - evidence = {_evidence_id(index): item for index, item in enumerate(stored, start=1)} - projected = await _project_window(stored, self._sources) - proposals, candidates = await self._generate(assignment.scope_id, projected) if projected else ((), {}) - operations = await self._prepare_operations(assignment.scope_id, proposals, candidates, evidence) - await self._publisher.publish(assignment, evidence, operations) + await budget.begin() + try: + stored = await self._read_window(assignment) + evidence = {_evidence_id(index): item for index, item in enumerate(stored, start=1)} + projected = await _project_window(stored, self._sources) + proposals, candidates = await self._generate(assignment.scope_id, projected) if projected else ((), {}) + operations = await self._prepare_operations(assignment.scope_id, proposals, candidates, evidence) + await self._publisher.publish(assignment, evidence, operations, work_budget=budget) + except TopicMemoryGenerationError as error: + if error.code == "source_complexity_limit": + await budget.fail(error.code) + raise except ArtifactProcessingLeadershipLostError: return ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.LEADERSHIP_LOST) except GenerationConflictError: return ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.CURSOR_CONFLICT) except RevisionConflictError: return ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.HEAD_CONFLICT) + finally: + self._work_budget.reset(token) return ArtifactProcessingWorkerCompletion() + async def _reserve_stage(self, value: BaseModel, stage: str) -> None: + if not self._stages.fits(value, stage): + raise TopicMemoryGenerationError("input_budget_exceeded") + # Reserve every structured retry's entire input + output/transcript + # capacity, even if the provider returns no usage or fails mid-call. + reserve = self._stages.transcript_reserve + capacity = self._stages.input_tokens_limit + ( + max(1, self._stages.input_tokens_limit // 4) if reserve is None else reserve + ) + await self._reserve(requests=self._stages.max_requests, tokens=self._stages.max_requests * capacity) + + async def _reserve(self, *, requests: int, tokens: int) -> None: + budget = self._work_budget.get() + if budget is not None: + await budget.reserve(requests=requests, tokens=tokens) + return + # Private stage helpers also have a finite allowance when used alone. + # The public process entrypoint ALWAYS uses the durable reservation. + if ( + self._local_requests + requests > MAX_TOPIC_MEMORY_WORK_REQUESTS + or self._local_tokens + tokens > MAX_TOPIC_MEMORY_WORK_TOKENS + ): + raise TopicMemoryGenerationError("window_provider_budget_exceeded") + self._local_requests += requests + self._local_tokens += tokens + + async def _embed(self, texts: tuple[str, ...]): + if self._embedding_model is None: + raise TopicMemoryGenerationError("embedding_unavailable") + # At most one provider request per text (the adapter may batch them). + await self._reserve( + requests=max(1, len(texts)), tokens=max(1, sum(self._stages.estimator.estimate(text) for text in texts)) + ) + return await self._embedding_model.embed(texts) + async def _read_window(self, assignment: ArtifactProcessingWorkAssignment) -> tuple[StoredSource, ...]: + if assignment.source_through - assignment.source_after > MAX_TOPIC_MEMORY_WINDOW_SOURCES: + raise TopicMemoryGenerationError("source_complexity_limit") count = assignment.source_through - assignment.source_after async with self._database.transaction() as connection: stored = await self._sources.list( @@ -648,7 +770,7 @@ async def _search( profile = None if self._embedding_model is not None: with self._usage(ModelUsagePurpose.TOPIC_MEMORY_RECALL, embedding=True): - embedded = await self._embedding_model.embed((query if semantic_query is None else semantic_query,)) + embedded = await self._embed((query if semantic_query is None else semantic_query,)) query_vector = embedded.vectors[0] profile = self._embedding_model.profile async with self._database.transaction() as connection: @@ -858,7 +980,7 @@ async def _signature_vector(self, content: TopicMemoryContent) -> tuple[float, . chunks = chunk_topic_memory_detail(content.detail) texts = (f"{content.title}\n{content.summary}", *(chunk.text for chunk in chunks)) with self._usage(ModelUsagePurpose.TOPIC_MEMORY_RECALL, embedding=True): - vectors = (await self._embedding_model.embed(tuple(texts))).vectors + vectors = (await self._embed(tuple(texts))).vectors return topic_memory_vector_centroid( vectors[0], tuple((len(chunk.text), vector) for chunk, vector in zip(chunks, vectors[1:], strict=True)), @@ -916,7 +1038,7 @@ async def _projection(self, content: TopicMemoryContent) -> TopicMemoryProjectio chunks = chunk_topic_memory_detail(content.detail) texts = (f"{content.title}\n{content.summary}", *(chunk.text for chunk in chunks)) with self._usage(ModelUsagePurpose.TOPIC_MEMORY_INDEXING, embedding=True): - vectors = (await self._embedding_model.embed(tuple(texts))).vectors + vectors = (await self._embed(tuple(texts))).vectors return prepare_topic_memory_projection( content, topic_embedding=vectors[0], @@ -1030,9 +1152,14 @@ async def _project_window( sources: SourceRepository, ) -> tuple[TopicMemoryEvidence, ...]: result: list[TopicMemoryEvidence] = [] + characters = 0 for index, item in enumerate(stored, start=1): if is_generation_eligible(item.value): - result.append(await _project_evidence(index, item, sources)) + projected = await _project_evidence(index, item, sources) + characters += len(projected.content) + if characters > MAX_TOPIC_MEMORY_SOURCE_CHARACTERS: + raise TopicMemoryGenerationError("source_complexity_limit") + result.append(projected) return tuple(result) @@ -1056,6 +1183,8 @@ async def _project_evidence( def _canonical_source_content(source_type: str, materialized: object) -> str: if isinstance(materialized, str): + if len(materialized) > MAX_TOPIC_MEMORY_SOURCE_CHARACTERS: + raise TopicMemoryGenerationError("source_complexity_limit") if not materialized.strip(): raise TopicMemoryGenerationError("unsupported_evidence") return materialized @@ -1085,12 +1214,41 @@ def _canonical_source_content(source_type: str, materialized: object) -> str: payload = {"name": materialized.name, "description": materialized.description} else: raise TopicMemoryGenerationError("unsupported_evidence") + _require_bounded_source_payload(payload) content = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + if len(content) > MAX_TOPIC_MEMORY_SOURCE_CHARACTERS: + raise TopicMemoryGenerationError("source_complexity_limit") if not content.strip(): raise TopicMemoryGenerationError("unsupported_evidence") return content +def _require_bounded_source_payload(payload: object) -> None: + # Traverse lazily: do not copy a huge container or serialize deep metadata + # before enforcing node/depth/text limits. Cycles hit the depth bound. + pending = [(iter((payload,)), 0)] + nodes = characters = 0 + while pending: + values, depth = pending[-1] + try: + value = next(values) + except StopIteration: + pending.pop() + continue + nodes += 1 + if nodes > MAX_TOPIC_MEMORY_SOURCE_NODES or depth > MAX_TOPIC_MEMORY_SOURCE_DEPTH: + raise TopicMemoryGenerationError("source_complexity_limit") + if isinstance(value, str): + characters += len(value) + elif isinstance(value, dict): + pending.append((iter(value), depth + 1)) + pending.append((iter(value.values()), depth + 1)) + elif isinstance(value, (list, tuple)): + pending.append((iter(value), depth + 1)) + if characters > MAX_TOPIC_MEMORY_SOURCE_CHARACTERS: + raise TopicMemoryGenerationError("source_complexity_limit") + + def _evidence_id(index: int) -> str: return f"evidence-{index:04d}" @@ -1217,6 +1375,51 @@ def _operation_order(operation: PreparedTopicMemoryOperation) -> tuple[bytes, by return operation.artifact_id.encode(), operation.proposal_id.encode() +def validate_topic_memory_provider_settings(inference: InferenceConfig) -> None: + """Keep worker requests stateless and limited to known bounded SDK paths.""" + from powercontext.builtin.runtime.composition import BuiltinConfigurationError + + generation = { + "max_tokens", + "temperature", + "top_p", + "top_k", + "seed", + "presence_penalty", + "frequency_penalty", + "timeout", + "openai_reasoning_effort", + "openai_text_verbosity", + "service_tier", + "openai_service_tier", + "anthropic_service_tier", + "anthropic_effort", + } + providers = { + "openai", + "openai-chat", + "openai-responses", + "anthropic", + "azure", + "azure-responses", + "deepseek", + "openrouter", + } + for name, settings, allowed in ( + (inference.generation_model, inference.generation_model_settings, generation), + (inference.embedding_model, inference.embedding_model_settings, {"dimensions", "truncate"}), + ): + # The built-in test model has no external I/O; retain hermetic workers. + if name is not None and name != "test" and name.split(":", 1)[0] not in providers: + raise BuiltinConfigurationError("topic-memory-provider-budget") + if set(settings) - allowed or any( + value is not None + and (not isinstance(value, (str, int, float, bool)) or (isinstance(value, str) and len(value) > 128)) + for value in settings.values() + ): + raise BuiltinConfigurationError("topic-memory-provider-budget") + + def run_topic_memory_worker( spec: TopicMemoryWorkerSpec, assignment: ArtifactProcessingWorkAssignment, @@ -1267,6 +1470,7 @@ async def _open_topic_memory_processor(spec: TopicMemoryWorkerSpec, scope_id: st inference = config.inference if inference.generation_model is None: raise BuiltinConfigurationError("topic-memory-generation") + validate_topic_memory_provider_settings(inference) budget = topic_memory_stage_budget( context_window_tokens=inference.generation_model_context_window_tokens, max_requests=inference.generation_max_requests, @@ -1278,6 +1482,7 @@ async def _open_topic_memory_processor(spec: TopicMemoryWorkerSpec, scope_id: st max_requests=inference.generation_max_requests, max_output_tokens_per_request=budget.max_output_tokens_per_request, output_tokens_limit=budget.output_tokens_limit, + allow_continuations=False, ) settings = cast(ModelSettings, dict(inference.generation_model_settings)) async with AsyncExitStack() as resources: @@ -1287,8 +1492,9 @@ async def _open_topic_memory_processor(spec: TopicMemoryWorkerSpec, scope_id: st headers=inference.generation_headers, resources=resources, instrumentation=None, + disable_provider_retries=True, ) - raw_embedding, _ = await _embedding_models(inference, resources, None) + raw_embedding, _ = await _embedding_models(inference, resources, None, disable_provider_retries=True) embedding = None if raw_embedding is None else UsageReportingEmbeddingModel(raw_embedding) contexts = await resources.enter_async_context( open_builtin_contexts(config, embedding_model=embedding, _topic_memory_worker=True) @@ -1375,6 +1581,8 @@ def stage( estimator=contexts.token_estimator, input_tokens_limit=budget.input_tokens_limit, fixed_prompts=fixed_prompts, + max_requests=budget.max_requests, + transcript_reserve=budget.transcript_reserve, ) async def report(purpose: ModelUsagePurpose, operation: ModelUsageOperation, usage: Any) -> None: diff --git a/tests/builtin/runtime/test_topic_memory_fragment_reduction.py b/tests/builtin/runtime/test_topic_memory_fragment_reduction.py index 826ddb9846..79d47ea86a 100644 --- a/tests/builtin/runtime/test_topic_memory_fragment_reduction.py +++ b/tests/builtin/runtime/test_topic_memory_fragment_reduction.py @@ -19,6 +19,7 @@ from dataclasses import replace import pytest +from sqlalchemy import select from powercontext.builtin.artifacts.topic_memory import TOPIC_MEMORY_SOURCE_WINDOW_BINDING, TopicMemoryContent from powercontext.builtin.artifacts.topic_memory.generation import ( @@ -46,6 +47,7 @@ from powercontext.builtin.persistence.cursors import SourceCursorRepository from powercontext.builtin.persistence.sources import SourceRepository from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository +from powercontext.builtin.persistence.tables import TOPIC_MEMORY_WORK_BUDGETS_TABLE from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingWorkerOutcome from powercontext.builtin.runtime.topic_memory_processing import ( TopicMemoryAtomicPublisher, @@ -226,10 +228,23 @@ async def _scenario(*, repeated=False, input_limit=100_000, characters=2_100_000 is None ) assert await topics.browse_current(connection, "scope-a", limit=10) == () + budget = (await connection.execute(select(TOPIC_MEMORY_WORK_BUDGETS_TABLE))).mappings().one() + # Every stage, including the failed reduction and Planner, is + # precharged. A new processor must retain those reservations. + assert budget["attempts"] == 1 + assert budget["requests"] == 2 * (len(fake.probes) + len(fake.temporaries) + len(fake.reductions) + 1) + assert budget["tokens"] == budget["requests"] * (input_limit * 5 // 4) fake.failure = None fake.probes.clear() fake.temporaries.clear() fake.reductions.clear() + processor = TopicMemoryProcessor( + database=profile.database, + sources=sources, + topics=topics, + stages=stages, + publisher=TopicMemoryAtomicPublisher(profile.database, sources, topics), + ) assert (await processor.process(assignment)).outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED for requests, stage in ((fake.probes, "probe"), (fake.temporaries, "temporary")): assert len(requests) > 20 diff --git a/tests/builtin/runtime/test_topic_memory_processing.py b/tests/builtin/runtime/test_topic_memory_processing.py index a6153b80aa..09a95ccbea 100644 --- a/tests/builtin/runtime/test_topic_memory_processing.py +++ b/tests/builtin/runtime/test_topic_memory_processing.py @@ -81,7 +81,11 @@ from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile from powercontext.builtin.persistence.sqlite.topic_memory_index import SQLiteTopicMemoryFTSIndex from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository -from powercontext.builtin.persistence.tables import BUILTIN_TABLES, TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE +from powercontext.builtin.persistence.tables import ( + BUILTIN_TABLES, + TOPIC_MEMORY_RETRIEVAL_SHAPE_TABLE, + TOPIC_MEMORY_WORK_BUDGETS_TABLE, +) from powercontext.builtin.persistence.topic_memory import TopicMemoryRepository from powercontext.builtin.persistence.topic_memory_index import ( CompositeTopicMemoryIndex, @@ -750,6 +754,10 @@ async def scenario() -> None: await SourceCursorRepository().load(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) is None ) + # Tail-fence rollback restores the debit row deleted earlier + # in the same publication transaction; costs cannot be reset. + budget = (await connection.execute(select(TOPIC_MEMORY_WORK_BUDGETS_TABLE))).mappings().one() + assert budget["attempts"] == 1 and budget["requests"] == 4 finally: await manager.__aexit__(None, None, None) diff --git a/tests/builtin/runtime/test_topic_memory_work_budget.py b/tests/builtin/runtime/test_topic_memory_work_budget.py new file mode 100644 index 0000000000..371ad50a3b --- /dev/null +++ b/tests/builtin/runtime/test_topic_memory_work_budget.py @@ -0,0 +1,589 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import asyncio +import json +import os +import subprocess +import sys +from contextlib import AsyncExitStack +from dataclasses import replace +from typing import Any, cast + +import httpx +import pytest +from pydantic import SecretStr +from sqlalchemy import select + +from powercontext.builtin.artifacts.topic_memory import TOPIC_MEMORY_SOURCE_WINDOW_BINDING +from powercontext.builtin.artifacts.topic_memory.generation import TopicMemoryGenerationError, TopicMemoryProbeOutput +from powercontext.builtin.inference import GenerationResult, character_token_estimator +from powercontext.builtin.persistence.cursors import SourceCursorRepository +from powercontext.builtin.persistence.processing import ArtifactProcessingPendingRepository +from powercontext.builtin.persistence.sources import SourceRepository +from powercontext.builtin.persistence.sqlite import SQLiteConfig +from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository +from powercontext.builtin.persistence.tables import TOPIC_MEMORY_WORK_BUDGETS_TABLE +from powercontext.builtin.persistence.topic_memory_budget import ( + MAX_TOPIC_MEMORY_WORK_ATTEMPTS, + MAX_TOPIC_MEMORY_WORK_REQUESTS, + MAX_TOPIC_MEMORY_WORK_TOKENS, +) +from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingWorkerOutcome +from powercontext.builtin.runtime.composition import ( + BuiltinConfigurationError, + _provider_factory, + _topic_memory_processing_available, + _topic_memory_processing_bindings, +) +from powercontext.builtin.runtime.config import BuiltinConfig, InferenceConfig, RuntimeConfig +from powercontext.builtin.runtime.topic_memory_processing import ( + MAX_TOPIC_MEMORY_SOURCE_CHARACTERS, + MAX_TOPIC_MEMORY_SOURCE_DEPTH, + MAX_TOPIC_MEMORY_SOURCE_NODES, + TopicMemoryAtomicPublisher, + TopicMemoryProcessor, + TopicMemoryWindowSelector, + TopicMemoryWorkerSpec, + _open_topic_memory_processor, +) +from powercontext.builtin.sources import CONTENT_SOURCE_ADAPTER, ContentCapture +from tests.builtin.persistence.contract import SOURCE_ADAPTERS +from tests.builtin.runtime.test_topic_memory_processing import _assignment, _repositories, _stages + + +class _FastProbe: + def __init__(self, failure=None): + self.calls = 0 + self.characters = 0 + self.failure = failure + + async def generate(self, value, /): + self.calls += 1 + self.characters += sum(len(item.content) for item in value.evidence) + if self.failure == "crash": + os._exit(73) + if self.failure == "cancel": + raise asyncio.CancelledError + if self.failure: + raise RuntimeError("provider unavailable") # noqa: TRY003 + return GenerationResult(output=TopicMemoryProbeOutput()) + + +def _processor(profile, sources, topics, fake, *, limit=100_000, requests=2, reserve=None): + stages = replace( + _stages(probe=TopicMemoryProbeOutput(), global_output=None, limit=limit), + probe=fake, + max_requests=requests, + transcript_reserve=reserve, + ) + return TopicMemoryProcessor( + database=profile.database, + sources=sources, + topics=topics, + stages=stages, + publisher=TopicMemoryAtomicPublisher(profile.database, sources, topics), + ) + + +async def _capture(profile, *, metadata=None, tail=True): + sources = SourceRepository((*SOURCE_ADAPTERS, CONTENT_SOURCE_ADAPTER)) + async with profile.database.transaction() as connection: + await sources.add( + connection, + "scope-a", + await CONTENT_SOURCE_ADAPTER.resolve( + ContentCapture(source_id="first", content="body", metadata=metadata or {}) + ), + ) + if tail: + await sources.add( + connection, + "scope-a", + await CONTENT_SOURCE_ADAPTER.resolve(ContentCapture(source_id="tail", content="ordinary tail")), + ) + await ArtifactProcessingPendingRepository().raise_source( + connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING, 2 if tail else 1 + ) + term = await ArtifactProcessingLeaseRepository().start_single_process_term(connection, "holder") + return sources, _assignment(term.fence("single-process")) + + +async def _row(profile): + async with profile.database.transaction() as connection: + row = (await connection.execute(select(TOPIC_MEMORY_WORK_BUDGETS_TABLE))).mappings().one_or_none() + return None if row is None else dict(row) + + +async def _assert_unpublished(profile, topics): + async with profile.database.transaction() as connection: + assert await SourceCursorRepository().load(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) is None + assert await topics.browse_current(connection, "scope-a", limit=10) == () + pending = await ArtifactProcessingPendingRepository().load( + connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING + ) + assert pending is not None and pending.source_through == 2 + + +@pytest.mark.parametrize("character", ["a", "界"]) +def test_maximum_canonical_metadata_fast_zero_probe_preserves_complete_source_and_tail(character): + async def scenario(): + manager, profile, _, topics = await _repositories() + try: + overhead = len(json.dumps({"content": "body", "metadata": {"data": ""}}, separators=(",", ":"))) + metadata = {"data": character * (MAX_TOPIC_MEMORY_SOURCE_CHARACTERS - overhead)} + sources, assignment = await _capture(profile, metadata=metadata) + fake = _FastProbe() + processor = _processor(profile, sources, topics, fake) + selector = TopicMemoryWindowSelector( + profile.database, sources, character_token_estimator(), context_window_tokens=125_000 + ) + assert await selector.select("scope-a", 0, 2) == 1 + assert (await processor.process(assignment)).outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + assert fake.characters == MAX_TOPIC_MEMORY_SOURCE_CHARACTERS + assert 1 < fake.calls * 2 <= MAX_TOPIC_MEMORY_WORK_REQUESTS + assert fake.calls * 250_000 <= MAX_TOPIC_MEMORY_WORK_TOKENS + assert await _row(profile) is None + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + assert cursor is not None and cursor.cursor.sequence == 1 + tail = replace( + assignment, source_after=1, source_through=2, wave_target=2, cursor_generation=cursor.generation + ) + assert (await processor.process(tail)).outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + assert cursor is not None and cursor.cursor.sequence == 2 + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("boundary", ["characters", "depth", "nodes"]) +def test_metadata_complexity_rejection_is_durable_and_never_skips_tail(boundary): + async def scenario(): + metadata = {"data": "界" * MAX_TOPIC_MEMORY_SOURCE_CHARACTERS} + if boundary == "depth": + metadata = {"data": "ok"} + for _ in range(MAX_TOPIC_MEMORY_SOURCE_DEPTH): + metadata = {"next": metadata} + elif boundary == "nodes": + metadata = {"data": [0] * MAX_TOPIC_MEMORY_SOURCE_NODES} + manager, profile, _, topics = await _repositories() + try: + sources, assignment = await _capture(profile, metadata=metadata) + fake = _FastProbe() + processor = _processor(profile, sources, topics, fake) + selector = TopicMemoryWindowSelector( + profile.database, sources, character_token_estimator(), context_window_tokens=125_000 + ) + assert await selector.select("scope-a", 0, 2) == 1 + for _ in range(2): + with pytest.raises(TopicMemoryGenerationError, match="source_complexity_limit"): + await processor.process(assignment) + row = await _row(profile) + assert row["attempts"] == 1 and row["requests"] == row["tokens"] == fake.calls == 0 + with pytest.raises(TopicMemoryGenerationError, match="source_complexity_limit"): + await selector.select("scope-a", 0, 2) + await _assert_unpublished(profile, topics) + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("ceiling,limit,requests", [("requests", 1_000, 2), ("tokens", 100_000, 2)]) +def test_fast_provider_stops_before_cumulative_request_or_token_ceiling(ceiling, limit, requests): + async def scenario(): + manager, profile, _, topics = await _repositories() + try: + sources, assignment = await _capture(profile, metadata={"data": "界" * 1_000_000}) + fake = _FastProbe() + reserve = 8_000_000 if ceiling == "tokens" else limit // 4 + capacity = limit + reserve + processor = _processor(profile, sources, topics, fake, limit=limit, requests=requests, reserve=reserve) + with pytest.raises(TopicMemoryGenerationError, match="window_provider_budget_exceeded"): + await processor.process(assignment) + before = await _row(profile) + assert before["failure_code"] == "window_provider_budget_exceeded" + assert before["requests"] == fake.calls * requests <= MAX_TOPIC_MEMORY_WORK_REQUESTS + assert before["tokens"] == fake.calls * requests * capacity <= MAX_TOPIC_MEMORY_WORK_TOKENS + allowance = ( + MAX_TOPIC_MEMORY_WORK_REQUESTS // requests + if ceiling == "requests" + else MAX_TOPIC_MEMORY_WORK_TOKENS // (requests * capacity) + ) + assert fake.calls == allowance + # New processor, wider window, new flush and worker cannot reset it. + replacement = _processor(profile, sources, topics, fake) + with pytest.raises(TopicMemoryGenerationError, match="window_provider_budget_exceeded"): + await replacement.process( + replace( + assignment, + source_through=2, + wave_target=2, + claimed_flush_generation=99, + worker_id="replacement", + ) + ) + assert await _row(profile) == before + await _assert_unpublished(profile, topics) + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) + + +def _crash_worker(database_path): + async def scenario(): + manager, profile, _, topics = await _repositories(SQLiteConfig(url=f"sqlite+aiosqlite:///{database_path}")) + try: + sources = SourceRepository((*SOURCE_ADAPTERS, CONTENT_SOURCE_ADAPTER)) + async with profile.database.transaction() as connection: + term = await ArtifactProcessingLeaseRepository().start_single_process_term(connection, "restarted") + await _processor(profile, sources, topics, _FastProbe("crash")).process( + _assignment(term.fence("single-process")) + ) + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) + + +def test_process_death_and_leader_restart_cannot_repeat_the_window_forever(tmp_path): + database_path = tmp_path / "restart.sqlite3" + + async def setup(): + manager, profile, _, _ = await _repositories(SQLiteConfig(url=f"sqlite+aiosqlite:///{database_path}")) + try: + await _capture(profile) + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(setup()) + command = [ + sys.executable, + "-c", + "from tests.builtin.runtime.test_topic_memory_work_budget import _crash_worker; import sys; _crash_worker(sys.argv[1])", + str(database_path), + ] + for _ in range(MAX_TOPIC_MEMORY_WORK_ATTEMPTS): + result = subprocess.run(command, capture_output=True, timeout=30, check=False) + assert result.returncode == 73, result.stderr.decode() + + async def verify(): + manager, profile, _, topics = await _repositories(SQLiteConfig(url=f"sqlite+aiosqlite:///{database_path}")) + try: + before = await _row(profile) + assert before["attempts"] == MAX_TOPIC_MEMORY_WORK_ATTEMPTS + assert before["requests"] == MAX_TOPIC_MEMORY_WORK_ATTEMPTS * 2 + assert before["tokens"] == MAX_TOPIC_MEMORY_WORK_ATTEMPTS * 250_000 + sources = SourceRepository((*SOURCE_ADAPTERS, CONTENT_SOURCE_ADAPTER)) + async with profile.database.transaction() as connection: + term = await ArtifactProcessingLeaseRepository().start_single_process_term(connection, "new-leader") + fake = _FastProbe() + processor = _processor(profile, sources, topics, fake) + with pytest.raises(TopicMemoryGenerationError, match="window_attempt_limit"): + await processor.process( + replace(_assignment(term.fence("single-process"), through=2), claimed_flush_generation=99) + ) + # Forging a later frontier without Cursor progress also cannot skip. + assert ( + await processor.process(replace(_assignment(term.fence("single-process"), through=2), source_after=1)) + ).outcome is ArtifactProcessingWorkerOutcome.CURSOR_CONFLICT + assert fake.calls == 0 + selector = TopicMemoryWindowSelector( + profile.database, sources, character_token_estimator(), context_window_tokens=125_000 + ) + with pytest.raises(TopicMemoryGenerationError, match="window_attempt_limit"): + await selector.select("scope-a", 0, 2) + await _assert_unpublished(profile, topics) + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(verify()) + + +def test_cancelled_reservation_is_not_refunded_and_retry_can_recover_tail(): + async def scenario(): + manager, profile, _, topics = await _repositories() + try: + sources, assignment = await _capture(profile) + fake = _FastProbe("cancel") + with pytest.raises(asyncio.CancelledError): + await _processor(profile, sources, topics, fake).process(assignment) + row = await _row(profile) + assert row["attempts"] == 1 and row["requests"] == 2 and row["tokens"] == 250_000 + await _assert_unpublished(profile, topics) + fake.failure = None + replacement = _processor(profile, sources, topics, fake) + assert ( + await replacement.process(replace(assignment, source_through=2, wave_target=2)) + ).outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + assert await _row(profile) is None + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + assert cursor is not None and cursor.cursor.sequence == 2 + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("provider_name", ["openai", "anthropic"]) +@pytest.mark.parametrize("with_headers", [False, True]) +def test_topic_provider_disables_sdk_transport_retries(provider_name, with_headers, monkeypatch): + async def scenario(): + calls = [] + + async def fail(request): + calls.append(request) + return httpx.Response( + 429, headers={"retry-after": "0"}, json={"error": {"message": "busy", "type": "rate_limit_error"}} + ) + + monkeypatch.setenv("OPENAI_API_KEY", "test") + monkeypatch.setenv("ANTHROPIC_API_KEY", "test") + async with AsyncExitStack() as resources: + provider = _provider_factory( + None, + {"x-test": SecretStr("test")} if with_headers else {}, + workload="generation", + resources=resources, + disable_retries=True, + )(provider_name) + await resources.enter_async_context(provider) + client = provider.client + assert client.max_retries == 0 + # Preserve the SDK's real request/retry implementation; substitute transport only. + transport = await resources.enter_async_context(httpx.AsyncClient(transport=httpx.MockTransport(fail))) + client._client = transport + with pytest.raises(Exception, match="busy"): + if provider_name == "openai": + await client.chat.completions.create( + model="test", messages=[{"role": "user", "content": "x"}], max_completion_tokens=7 + ) + else: + await client.messages.create( + model="test", messages=[{"role": "user", "content": "x"}], max_tokens=7 + ) + assert len(calls) == 1 + + asyncio.run(scenario()) + + +@pytest.mark.parametrize( + "workload,key,value", + [ + ("generation", "extra_body", {"max_completion_tokens": 999_999_999}), + ("embedding", "extra_body", {"input": "hidden"}), + ("generation", "openai_background", True), + ("generation", "openai_previous_response_id", "response-id"), + ("generation", "openai_conversation_id", "conversation-id"), + ("generation", "openai_native_tools", [{"type": "web_search"}]), + ], +) +def test_worker_and_binding_reject_unmetered_settings_before_opening_resources(workload, key, value): + async def scenario(): + settings = {"generation_model": "openai:test"} + if workload == "embedding": + settings.update(embedding_model="openai:test", embedding_profile_id="test", embedding_dimension=2) + settings[workload + "_model_settings"] = {key: value} + config = BuiltinConfig( + database=SQLiteConfig(url="sqlite+aiosqlite:///not-opened.sqlite3"), + inference=InferenceConfig.model_validate(settings), + ) + assert _topic_memory_processing_bindings(config, cast(Any, None), ()) == () + assert not _topic_memory_processing_available(config, ()) + api = config.model_copy(update={"runtime": RuntimeConfig(artifact_processing_role="api")}) + assert not _topic_memory_processing_available(api, ()) + scheduled = config.model_copy(update={"runtime": RuntimeConfig(topic_memory_schedule_seconds=60)}) + with pytest.raises(BuiltinConfigurationError): + _topic_memory_processing_bindings(scheduled, cast(Any, None), ()) + spec = TopicMemoryWorkerSpec(config=config) + with pytest.raises(BuiltinConfigurationError): + async with _open_topic_memory_processor(spec, "scope-a"): + pytest.fail("unsafe worker opened") + + asyncio.run(scenario()) + + +def test_structured_retries_and_failed_calls_share_durable_reservation(): + from pydantic_ai.messages import ModelResponse, TextPart + from pydantic_ai.models.function import FunctionModel + + from powercontext.builtin.artifacts.topic_memory.generation import TopicMemoryProbeInput + from powercontext.builtin.inference import InvalidInferenceOutputError + from powercontext.builtin.inference.pydantic_ai import InferenceLimits, PydanticAIStructuredGenerator + + async def scenario(): + manager, profile, _, topics = await _repositories() + observations = [] + valid = False + try: + sources, assignment = await _capture(profile) + + async def respond(_messages, _info): + observations.append(await _row(profile)) + return ModelResponse(parts=[TextPart('{"probes":[]}' if valid else "not JSON")]) + + raw = PydanticAIStructuredGenerator( + model=FunctionModel(respond), + instructions="Generate probes.", + input_type=TopicMemoryProbeInput, + output_type=TopicMemoryProbeOutput, + limits=InferenceLimits(max_requests=2, max_output_tokens_per_request=512, output_tokens_limit=1024), + ) + with pytest.raises(InvalidInferenceOutputError): + await _processor(profile, sources, topics, raw).process(assignment) + assert len(observations) == 2 + assert all(row["requests"] == 2 and row["tokens"] == 250_000 for row in observations) + await _assert_unpublished(profile, topics) + valid = True + assert ( + await _processor(profile, sources, topics, raw).process(assignment) + ).outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + assert len(observations) == 3 # The unused fourth request stays conservatively charged. + assert observations[-1]["attempts"] == 2 + assert observations[-1]["requests"] == 4 and observations[-1]["tokens"] == 500_000 + assert await _row(profile) is None + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) + + +def test_suspended_response_cannot_hide_multiple_provider_calls_in_one_request(): + from pydantic_ai.messages import ModelResponse, TextPart + from pydantic_ai.models.function import FunctionModel + from pydantic_ai.usage import RequestUsage + + from powercontext.builtin.artifacts.topic_memory.generation import TopicMemoryProbeInput + from powercontext.builtin.inference import InvalidInferenceOutputError + from powercontext.builtin.inference.pydantic_ai import InferenceLimits, PydanticAIStructuredGenerator + + async def scenario(): + manager, profile, _, topics = await _repositories() + calls = 0 + try: + sources, assignment = await _capture(profile) + + async def respond(_messages, _info): + nonlocal calls + calls += 1 + if calls == 1: + return ModelResponse( + parts=[], state="suspended", usage=RequestUsage(input_tokens=1, output_tokens=0) + ) + return ModelResponse(parts=[TextPart('{"probes":[]}')]) + + raw = PydanticAIStructuredGenerator( + model=FunctionModel(respond), + instructions="Generate probes.", + input_type=TopicMemoryProbeInput, + output_type=TopicMemoryProbeOutput, + limits=InferenceLimits( + max_requests=1, max_output_tokens_per_request=7, output_tokens_limit=7, allow_continuations=False + ), + ) + with pytest.raises(InvalidInferenceOutputError, match="continuation"): + await _processor(profile, sources, topics, raw, requests=1).process(assignment) + assert calls == 1 + row = await _row(profile) + assert row["requests"] == 1 and row["attempts"] == 1 + await _assert_unpublished(profile, topics) + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) + + +def test_unsupported_worker_provider_fails_when_binding_is_assembled(): + config = BuiltinConfig( + database=SQLiteConfig(url="sqlite+aiosqlite:///not-opened.sqlite3"), + inference=InferenceConfig(generation_model="google:test"), + runtime=RuntimeConfig(topic_memory_schedule_seconds=60), + ) + with pytest.raises(BuiltinConfigurationError, match="bounded stateless"): + _topic_memory_processing_bindings(config, cast(Any, None), ()) + + +def test_embedding_shares_exhausted_generation_budget_and_other_scope_can_progress(monkeypatch): + from powercontext.builtin.artifacts.memory import EmbeddingProfile + from powercontext.builtin.artifacts.topic_memory.generation import TopicMemoryProbe + from powercontext.builtin.inference import EmbeddingResult + from powercontext.builtin.persistence import topic_memory_budget + + async def scenario(): + manager, profile, _, topics = await _repositories() + try: + sources, assignment = await _capture(profile) + # A small allowance reaches the embedding boundary without a long + # synthetic model run. The default hard ceilings are tested above. + monkeypatch.setattr(topic_memory_budget, "MAX_TOPIC_MEMORY_WORK_REQUESTS", 2) + calls = 0 + + class Embedding: + profile = EmbeddingProfile( + profile_id="test", model="test", dimension=2, distance="l2", normalization="none" + ) + + async def embed(self, texts, /): + nonlocal calls + calls += 1 + return EmbeddingResult(vectors=tuple((1.0, 0.0) for _ in texts)) + + stages = _stages( + probe=TopicMemoryProbeOutput( + probes=(TopicMemoryProbe(query="query", evidence_ids=("evidence-0001",)),) + ), + global_output=None, + ) + processor = TopicMemoryProcessor( + database=profile.database, + sources=sources, + topics=topics, + stages=stages, + embedding_model=Embedding(), + publisher=TopicMemoryAtomicPublisher(profile.database, sources, topics), + ) + with pytest.raises(TopicMemoryGenerationError, match="window_provider_budget_exceeded"): + await processor.process(assignment) + assert calls == 0 + row = await _row(profile) + assert row["requests"] == 2 and row["failure_code"] == "window_provider_budget_exceeded" + await _assert_unpublished(profile, topics) + async with profile.database.transaction() as connection: + await sources.add( + connection, + "scope-b", + await CONTENT_SOURCE_ADAPTER.resolve( + ContentCapture(source_id="healthy", content="ordinary source") + ), + ) + healthy = _processor(profile, sources, topics, _FastProbe()) + assert ( + await healthy.process(replace(assignment, scope_id="scope-b")) + ).outcome is ArtifactProcessingWorkerOutcome.SUCCEEDED + async with profile.database.transaction() as connection: + cursor = await SourceCursorRepository().load(connection, "scope-b", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) + assert cursor is not None and cursor.cursor.sequence == 1 + assert await _row(profile) == row + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) From 5235867fb85b154baf03cfd1ffe58f8f252d0fdc Mon Sep 17 00:00:00 2001 From: Rongfeng Fu Date: Wed, 9 Sep 2026 03:00:37 +0800 Subject: [PATCH 5/5] fix(topic-memory): make worker integrity checks statement-consistent Co-authored-by: multica-agent --- .../oceanbase/topic_memory_index.py | 11 +- .../persistence/sqlite/topic_memory_index.py | 30 +- .../builtin/persistence/topic_memory.py | 82 +++-- .../builtin/persistence/topic_memory_index.py | 96 +++++- .../builtin/persistence/test_topic_memory.py | 3 + .../test_topic_memory_integrity.py | 305 ++++++++++++++++++ 6 files changed, 489 insertions(+), 38 deletions(-) create mode 100644 tests/builtin/persistence/test_topic_memory_integrity.py diff --git a/src/powercontext/builtin/persistence/oceanbase/topic_memory_index.py b/src/powercontext/builtin/persistence/oceanbase/topic_memory_index.py index 6e525ad436..d365f76e68 100644 --- a/src/powercontext/builtin/persistence/oceanbase/topic_memory_index.py +++ b/src/powercontext/builtin/persistence/oceanbase/topic_memory_index.py @@ -58,7 +58,10 @@ TOPIC_MEMORY_ACTIVE_TOPICS_TABLE, identity_string, ) -from powercontext.builtin.persistence.topic_memory_index import topic_memory_embedding_profile_fingerprint +from powercontext.builtin.persistence.topic_memory_index import ( + topic_memory_embedding_profile_fingerprint, + validate_current_topic_vectors, +) from powercontext.limits import MAX_ARTIFACT_ID_LENGTH, MAX_SCOPE_ID_LENGTH _TOPIC_FTS_INDEX = "ix_pc_topic_memory_active_topics_fts" @@ -137,6 +140,9 @@ class OceanBaseTopicMemoryFTSIndex: capabilities = TopicMemoryCapabilities(fts=True) tables: tuple[Table, ...] = () + async def validate_current(self, _connection: AsyncConnection, /) -> None: + pass + async def initialize(self, connection: AsyncConnection, /) -> None: if connection.dialect.name != "mysql": raise TopicMemoryCapabilityError("oceanbase-fts") @@ -352,6 +358,9 @@ async def initialize(self, connection: AsyncConnection, /) -> None: await connection.run_sync(lambda sync: self._topic_index.create(sync, checkfirst=True)) await connection.run_sync(lambda sync: self._chunk_index.create(sync, checkfirst=True)) + async def validate_current(self, connection: AsyncConnection, /) -> None: + await validate_current_topic_vectors(connection, self.topic_table, self.chunk_table, self._fingerprint) + async def replace( self, connection: AsyncConnection, diff --git a/src/powercontext/builtin/persistence/sqlite/topic_memory_index.py b/src/powercontext/builtin/persistence/sqlite/topic_memory_index.py index 34d3fc08fd..a44e0fd799 100644 --- a/src/powercontext/builtin/persistence/sqlite/topic_memory_index.py +++ b/src/powercontext/builtin/persistence/sqlite/topic_memory_index.py @@ -27,9 +27,11 @@ String, Table, UniqueConstraint, + column, delete, insert, select, + table, text, ) from sqlalchemy.exc import SQLAlchemyError @@ -55,7 +57,10 @@ TOPIC_MEMORY_ACTIVE_TOPICS_TABLE, identity_string, ) -from powercontext.builtin.persistence.topic_memory_index import topic_memory_embedding_profile_fingerprint +from powercontext.builtin.persistence.topic_memory_index import ( + topic_memory_embedding_profile_fingerprint, + validate_current_topic_vectors, +) from powercontext.limits import MAX_ARTIFACT_ID_LENGTH, MAX_SCOPE_ID_LENGTH SQLITE_TOPIC_MEMORY_FTS_MARKER_TABLE = Table( @@ -245,6 +250,9 @@ class SQLiteTopicMemoryFTSIndex: capabilities = TopicMemoryCapabilities(fts=True) tables: tuple[Table, ...] = SQLITE_TOPIC_MEMORY_FTS_TABLES + async def validate_current(self, _connection: AsyncConnection, /) -> None: + pass + async def initialize(self, connection: AsyncConnection, /) -> None: if connection.dialect.name != "sqlite": raise TopicMemoryCapabilityError("sqlite-fts") @@ -369,6 +377,26 @@ class SQLiteTopicMemoryVectorIndex: tables: tuple[Table, ...] = SQLITE_TOPIC_MEMORY_VECTOR_TABLES + async def validate_current(self, connection: AsyncConnection, /) -> None: + topic_rows = table("pc_topic_memory_topic_vec", column("rowid"), column("scope_id")) + chunk_rows = table("pc_topic_memory_chunk_vec", column("rowid"), column("scope_id")) + topics = SQLITE_TOPIC_MEMORY_VECTOR_TOPICS_TABLE + chunks = SQLITE_TOPIC_MEMORY_VECTOR_CHUNKS_TABLE + await validate_current_topic_vectors( + connection, + topics, + chunks, + self._fingerprint, + topic_present=select(topic_rows.c.rowid) + .where(topic_rows.c.rowid == topics.c.vector_id, topic_rows.c.scope_id == topics.c.scope_id) + .correlate(topics) + .exists(), + chunk_present=select(chunk_rows.c.rowid) + .where(chunk_rows.c.rowid == chunks.c.vector_id, chunk_rows.c.scope_id == chunks.c.scope_id) + .correlate(chunks) + .exists(), + ) + def __init__(self, profile: EmbeddingProfile) -> None: if profile.dimension < 1 or profile.distance != "l2" or profile.normalization != "unit": raise TopicMemoryCapabilityError( diff --git a/src/powercontext/builtin/persistence/topic_memory.py b/src/powercontext/builtin/persistence/topic_memory.py index 7d43e66eb7..44345fc6fe 100644 --- a/src/powercontext/builtin/persistence/topic_memory.py +++ b/src/powercontext/builtin/persistence/topic_memory.py @@ -157,24 +157,52 @@ async def initialize(self, connection: AsyncConnection, /, *, configure_retrieva if orphan_chunk is not None: raise TopicMemoryStorageInvariantError("active-chunk-not-head", tuple(orphan_chunk)) - active_rows = ( - await connection.execute( - select( - ARTIFACT_HEADS_TABLE.c.scope_id, - ARTIFACT_HEADS_TABLE.c.artifact_id, - ARTIFACT_HEADS_TABLE.c.revision, - TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.revision.label("active_revision"), - ) - .outerjoin( - TOPIC_MEMORY_ACTIVE_TOPICS_TABLE, - (TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.scope_id == ARTIFACT_HEADS_TABLE.c.scope_id) - & (TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.family == ARTIFACT_HEADS_TABLE.c.family) - & (TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.artifact_id == ARTIFACT_HEADS_TABLE.c.artifact_id), + # Check each Head and its chunks in the same statement snapshot. A + # Worker may use READ COMMITTED (or SQLite legacy SELECT mode), where a + # later query could otherwise see an already-replaced active Revision. + chunk_count = ( + select(func.count()) + .select_from(TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE) + .where( + TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE.c.scope_id == ARTIFACT_HEADS_TABLE.c.scope_id, + TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE.c.family == ARTIFACT_HEADS_TABLE.c.family, + TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE.c.artifact_id == ARTIFACT_HEADS_TABLE.c.artifact_id, + TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE.c.revision == ARTIFACT_HEADS_TABLE.c.revision, + ) + .correlate(ARTIFACT_HEADS_TABLE) + .scalar_subquery() + ) + invalid_head = ( + ( + await connection.execute( + select( + ARTIFACT_HEADS_TABLE.c.scope_id, + ARTIFACT_HEADS_TABLE.c.artifact_id, + ARTIFACT_HEADS_TABLE.c.revision, + TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.revision.label("active_revision"), + ) + .outerjoin( + TOPIC_MEMORY_ACTIVE_TOPICS_TABLE, + (TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.scope_id == ARTIFACT_HEADS_TABLE.c.scope_id) + & (TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.family == ARTIFACT_HEADS_TABLE.c.family) + & (TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.artifact_id == ARTIFACT_HEADS_TABLE.c.artifact_id), + ) + .where( + ARTIFACT_HEADS_TABLE.c.family == TopicMemory.family, + or_( + TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.revision.is_(None), + TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.revision != ARTIFACT_HEADS_TABLE.c.revision, + chunk_count == 0, + ), + ) + .limit(1) ) - .where(ARTIFACT_HEADS_TABLE.c.family == TopicMemory.family) ) - ).mappings() - for row in active_rows: + .mappings() + .one_or_none() + ) + if invalid_head is not None: + row = invalid_head ref = ArtifactRef( family=TopicMemory.family, artifact_id=str(row["artifact_id"]), @@ -182,25 +210,9 @@ async def initialize(self, connection: AsyncConnection, /, *, configure_retrieva ) if row["active_revision"] is None or int(row["active_revision"]) != ref.revision: raise TopicMemoryStorageInvariantError("head-not-active", (str(row["scope_id"]), ref)) - chunk_count = int( - await connection.scalar( - select(func.count()) - .select_from(TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE) - .where( - TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE.c.scope_id == row["scope_id"], - TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE.c.family == TopicMemory.family, - TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE.c.artifact_id == ref.artifact_id, - TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE.c.revision == ref.revision, - ) - ) - or 0 - ) - if chunk_count == 0: - raise TopicMemoryStorageInvariantError("missing-active-chunks", (str(row["scope_id"]), ref)) - if self.index.capabilities.vector and not await self.index.vector_complete( - connection, str(row["scope_id"]), ref - ): - raise TopicMemoryStorageInvariantError("incomplete-vector", (str(row["scope_id"]), ref)) + raise TopicMemoryStorageInvariantError("missing-active-chunks", (str(row["scope_id"]), ref)) + + await self.index.validate_current(connection) if not configure_retrieval_shape: await self._check_retrieval_shape(connection) diff --git a/src/powercontext/builtin/persistence/topic_memory_index.py b/src/powercontext/builtin/persistence/topic_memory_index.py index d40558443d..0feca4c179 100644 --- a/src/powercontext/builtin/persistence/topic_memory_index.py +++ b/src/powercontext/builtin/persistence/topic_memory_index.py @@ -19,17 +19,21 @@ import hashlib from typing import Protocol -from sqlalchemy import Table +from sqlalchemy import Table, and_, or_, select, true from sqlalchemy.ext.asyncio import AsyncConnection +from sqlalchemy.sql import ColumnElement from powercontext.artifacts import ArtifactRef from powercontext.builtin.artifacts.memory import EmbeddingProfile from powercontext.builtin.artifacts.topic_memory import ( + TopicMemory, TopicMemoryCapabilities, TopicMemoryProjection, TopicMemorySearchChannels, TopicMemorySearchRequest, + TopicMemoryStorageInvariantError, ) +from powercontext.builtin.persistence.tables import TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE, TOPIC_MEMORY_ACTIVE_TOPICS_TABLE class TopicMemoryIndex(Protocol): @@ -40,6 +44,8 @@ class TopicMemoryIndex(Protocol): async def initialize(self, connection: AsyncConnection, /) -> None: ... + async def validate_current(self, connection: AsyncConnection, /) -> None: ... + async def replace( self, connection: AsyncConnection, @@ -75,6 +81,9 @@ class NoTopicMemoryIndex: async def initialize(self, _connection: AsyncConnection, /) -> None: pass + async def validate_current(self, _connection: AsyncConnection, /) -> None: + pass + async def replace( self, _connection: AsyncConnection, @@ -126,6 +135,10 @@ async def initialize(self, connection: AsyncConnection, /) -> None: for index in self.indexes: await index.initialize(connection) + async def validate_current(self, connection: AsyncConnection, /) -> None: + for index in self.indexes: + await index.validate_current(connection) + async def replace( self, connection: AsyncConnection, @@ -171,6 +184,87 @@ async def vector_complete( return True +async def validate_current_topic_vectors( + connection: AsyncConnection, + topic_vectors: Table, + chunk_vectors: Table, + fingerprint: str, + *, + topic_present: ColumnElement[bool] | None = None, + chunk_present: ColumnElement[bool] | None = None, +) -> None: + """Check current vector projections in one statement snapshot, including RC. + + Never carry an active Revision into a later query: publication removes its + old projection atomically. Both directions of ordinal membership matter; + equal counts alone would accept a missing ordinal replaced by an extra one. + """ + + active = TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.alias("active") + expected = TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE.alias("expected") + expected_for_active = and_( + expected.c.scope_id == active.c.scope_id, + expected.c.family == active.c.family, + expected.c.artifact_id == active.c.artifact_id, + expected.c.revision == active.c.revision, + ) + expected_for_vector = and_( + expected.c.scope_id == chunk_vectors.c.scope_id, + expected.c.artifact_id == chunk_vectors.c.artifact_id, + expected.c.revision == chunk_vectors.c.revision, + expected.c.chunk_ordinal == chunk_vectors.c.chunk_ordinal, + ) + topic_complete = ( + select(topic_vectors.c.artifact_id) + .where( + topic_vectors.c.scope_id == active.c.scope_id, + topic_vectors.c.artifact_id == active.c.artifact_id, + topic_vectors.c.revision == active.c.revision, + topic_vectors.c.profile_fingerprint == fingerprint, + true() if topic_present is None else topic_present, + ) + .correlate(active) + .exists() + ) + chunk_complete = ( + select(chunk_vectors.c.chunk_ordinal) + .where( + expected_for_vector, + chunk_vectors.c.profile_fingerprint == fingerprint, + true() if chunk_present is None else chunk_present, + ) + .correlate(expected) + .exists() + ) + has_chunks = select(expected.c.chunk_ordinal).where(expected_for_active).correlate(active).exists() + missing_chunk = ( + select(expected.c.chunk_ordinal).where(expected_for_active, ~chunk_complete).correlate(active).exists() + ) + extra_chunk = ( + select(chunk_vectors.c.chunk_ordinal) + .where( + chunk_vectors.c.scope_id == active.c.scope_id, + chunk_vectors.c.artifact_id == active.c.artifact_id, + chunk_vectors.c.revision == active.c.revision, + ~select(expected.c.chunk_ordinal).where(expected_for_vector).correlate(chunk_vectors).exists(), + ) + .correlate(active) + .exists() + ) + invalid = ( + await connection.execute( + select(active.c.scope_id, active.c.artifact_id, active.c.revision) + .where(or_(~topic_complete, ~has_chunks, missing_chunk, extra_chunk)) + .limit(1) + ) + ).one_or_none() + if invalid is not None: + ref = ArtifactRef( + family=TopicMemory.family, artifact_id=str(invalid.artifact_id), revision=int(invalid.revision) + ) + raise TopicMemoryStorageInvariantError("incomplete-vector", (str(invalid.scope_id), ref)) + + def topic_memory_embedding_profile_fingerprint(profile: EmbeddingProfile, /) -> str: """Return the backend-independent identity of one immutable retrieval profile.""" diff --git a/tests/builtin/persistence/test_topic_memory.py b/tests/builtin/persistence/test_topic_memory.py index ab1736acfb..aa7e77f421 100644 --- a/tests/builtin/persistence/test_topic_memory.py +++ b/tests/builtin/persistence/test_topic_memory.py @@ -80,6 +80,9 @@ def __init__(self, delegate: TopicMemoryIndex) -> None: async def initialize(self, connection: AsyncConnection, /) -> None: await self.delegate.initialize(connection) + async def validate_current(self, connection: AsyncConnection, /) -> None: + await self.delegate.validate_current(connection) + async def replace( self, connection: AsyncConnection, diff --git a/tests/builtin/persistence/test_topic_memory_integrity.py b/tests/builtin/persistence/test_topic_memory_integrity.py new file mode 100644 index 0000000000..01af24cf0a --- /dev/null +++ b/tests/builtin/persistence/test_topic_memory_integrity.py @@ -0,0 +1,305 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Statement-consistent integrity checks on real SQLite and opt-in OceanBase.""" + +from __future__ import annotations + +import asyncio +import os +from collections.abc import AsyncIterator +from contextlib import AsyncExitStack, asynccontextmanager +from dataclasses import dataclass +from pathlib import Path +from typing import Any, cast +from uuid import uuid4 + +import pytest +from pydantic import SecretStr +from sqlalchemy import delete, insert, select, update +from sqlalchemy.engine import make_url +from sqlalchemy.ext.asyncio import AsyncConnection + +from powercontext.builtin.artifacts.memory import EmbeddingProfile +from powercontext.builtin.artifacts.topic_memory import ( + TopicMemory, + TopicMemoryContent, + TopicMemoryDraft, + TopicMemoryStorageInvariantError, + prepare_topic_memory_projection, +) +from powercontext.builtin.persistence.database import AsyncDatabase +from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile +from powercontext.builtin.persistence.oceanbase.topic_memory_index import ( + OceanBaseTopicMemoryFTSIndex, + OceanBaseTopicMemoryVectorIndex, +) +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.persistence.sqlite.topic_memory_index import ( + SQLiteTopicMemoryFTSIndex, + SQLiteTopicMemoryVectorIndex, +) +from powercontext.builtin.persistence.tables import BUILTIN_TABLES, TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE +from powercontext.builtin.persistence.topic_memory import TopicMemoryRepository +from powercontext.builtin.persistence.topic_memory_index import CompositeTopicMemoryIndex + +_LIVE_URL = os.environ.get("POWERCONTEXT_TEST_OCEANBASE_URL") +_OB = pytest.param("oceanbase", marks=pytest.mark.skipif(not _LIVE_URL, reason="requires test OceanBase URL")) +_PROFILE = EmbeddingProfile(profile_id="integrity", model="test", dimension=3, distance="l2", normalization="unit") +_VECTOR = (1.0, 0.0, 0.0) + + +@dataclass +class _Store: + database: AsyncDatabase + reader: AsyncDatabase + repository: TopicMemoryRepository + first: TopicMemory + index: CompositeTopicMemoryIndex + + async def publish(self, connection: AsyncConnection, previous: TopicMemory | None, scope: str) -> TopicMemory: + content = TopicMemoryContent(title="Recovery", summary="Durable evidence", detail="Evidence " * 400) + projection = prepare_topic_memory_projection(content) + if self.index.capabilities.vector: + projection = prepare_topic_memory_projection( + content, + topic_embedding=_VECTOR, + chunk_embeddings=(_VECTOR,) * len(projection.chunks), + embedding_profile=_PROFILE, + ) + draft = TopicMemoryDraft(content=content) + if previous is None: + result = await self.repository.publish_create(connection, scope, "shared-id", draft, projection) + else: + result = await self.repository.publish_revision(connection, scope, previous, draft, projection) + return result.topic + + +@asynccontextmanager +async def _open_store(tmp_path: Path, backend: str, *, vector: bool) -> AsyncIterator[_Store]: + async with AsyncExitStack() as stack: + if backend == "sqlite": + index = CompositeTopicMemoryIndex( + SQLiteTopicMemoryFTSIndex(), *((SQLiteTopicMemoryVectorIndex(_PROFILE),) if vector else ()) + ) + config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'integrity.db'}") + profile = await stack.enter_async_context( + SQLiteProfile.open(config, tables=BUILTIN_TABLES + index.tables, load_vector_extension=vector) + ) + reader = await stack.enter_async_context( + SQLiteProfile.open(config, tables=BUILTIN_TABLES + index.tables, load_vector_extension=vector) + ) + else: + assert _LIVE_URL is not None + server = await stack.enter_async_context( + OceanBaseProfile.open(OceanBaseConfig(url=SecretStr(_LIVE_URL)), tables=()) + ) + database_name = f"pc_p2_{uuid4().hex}" + async with server.database.transaction() as connection: + await connection.exec_driver_sql(f"CREATE DATABASE `{database_name}`") + + async def drop_database() -> None: + async with server.database.transaction() as connection: + await connection.exec_driver_sql(f"DROP DATABASE `{database_name}`") + + stack.push_async_callback(drop_database) + url = make_url(_LIVE_URL).set(database=database_name).render_as_string(hide_password=False) + index = CompositeTopicMemoryIndex( + OceanBaseTopicMemoryFTSIndex(), *((OceanBaseTopicMemoryVectorIndex(_PROFILE),) if vector else ()) + ) + ob_config = OceanBaseConfig(url=SecretStr(url)) + profile = await stack.enter_async_context( + OceanBaseProfile.open(ob_config, tables=BUILTIN_TABLES + index.tables) + ) + reader = await stack.enter_async_context( + OceanBaseProfile.open(ob_config, tables=BUILTIN_TABLES + index.tables) + ) + repository = TopicMemoryRepository(index=index) + store = _Store(profile.database, reader.database, repository, cast(TopicMemory, None), index) + async with profile.database.transaction() as connection: + await repository.initialize(connection) + async with profile.database.transaction() as connection: + store.first = await store.publish(connection, None, "scope-a") + await store.publish(connection, None, "scope-b") + yield store + + +class _ReadBarrier: + """Control commit timing, without mocking any SQL result or database write.""" + + def __init__(self, connection: AsyncConnection, marker: str, timing: str) -> None: + self.connection = connection + self.marker = marker + self.timing = timing + self.reached = asyncio.Event() + self.committed = asyncio.Event() + + def __getattr__(self, name: str) -> Any: + return getattr(self.connection, name) + + async def execute(self, statement: Any, *args: Any, **kwargs: Any) -> Any: + pause = not self.reached.is_set() and self.marker in str(statement.compile(dialect=self.connection.dialect)) + if pause and self.timing == "before": + self.reached.set() + await self.committed.wait() + result = await self.connection.execute(statement, *args, **kwargs) + if pause and self.timing == "after": + self.reached.set() + await self.committed.wait() + return result + + +async def _concurrent_revision(store: _Store, *, timing: str, vectors_only: bool = False) -> None: + async with store.reader.transaction() as connection: + if connection.dialect.name == "mysql": + await connection.exec_driver_sql("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED") + assert await connection.scalar(select(1)) == 1 + assert (await connection.exec_driver_sql("SELECT @@tx_isolation, @@autocommit")).one() == ( + "READ-COMMITTED", + 0, + ) + else: + await connection.exec_driver_sql("PRAGMA query_only = ON") + marker = "FROM pc_topic_memory_active_topics AS active" if vectors_only else "AS active_revision" + barrier = _ReadBarrier(connection, marker, timing) + + async def publish() -> None: + await barrier.reached.wait() + async with store.database.transaction() as writer: + await store.publish(writer, store.first, "scope-a") + barrier.committed.set() + + async def check() -> None: + wrapped = cast(AsyncConnection, barrier) + if vectors_only: + await store.index.validate_current(wrapped) + else: + await store.repository.initialize(wrapped, configure_retrieval_shape=False) + + # SQLite's vector initialization performs probe writes and therefore + # serializes publication. Direct validation exercises the unlocked + # vector read boundary; full FTS-only initialization covers bootstrap. + async with asyncio.timeout(20), asyncio.TaskGroup() as tasks: + tasks.create_task(publish()) + tasks.create_task(check()) + assert barrier.committed.is_set() + if connection.dialect.name == "sqlite": + await connection.exec_driver_sql("PRAGMA query_only = OFF") + async with store.reader.transaction() as connection: + await store.repository.initialize(connection, configure_retrieval_shape=False) + a = await store.repository.browse_current(connection, "scope-a", limit=10) + b = await store.repository.browse_current(connection, "scope-b", limit=10) + assert [item.artifact_ref.revision for item in a] == [2] + assert [item.artifact_ref.revision for item in b] == [1] + + +@pytest.mark.parametrize("backend", ["sqlite", _OB]) +@pytest.mark.parametrize("timing", ["before", "after"]) +def test_worker_integrity_accepts_another_scopes_concurrent_revision(tmp_path: Path, backend: str, timing: str) -> None: + async def scenario() -> None: + async with _open_store(tmp_path, backend, vector=False) as store: + await _concurrent_revision(store, timing=timing) + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("backend", ["sqlite", _OB]) +@pytest.mark.parametrize("timing", ["before", "after"]) +def test_current_vector_integrity_uses_one_revision(tmp_path: Path, backend: str, timing: str) -> None: + async def scenario() -> None: + async with _open_store(tmp_path, backend, vector=True) as store: + await _concurrent_revision(store, timing=timing, vectors_only=True) + + asyncio.run(scenario()) + + +@pytest.mark.skipif(not _LIVE_URL, reason="requires test OceanBase URL") +@pytest.mark.parametrize("timing", ["before", "after"]) +def test_oceanbase_hybrid_bootstrap_accepts_concurrent_revision(tmp_path: Path, timing: str) -> None: + async def scenario() -> None: + async with _open_store(tmp_path, "oceanbase", vector=True) as store: + await _concurrent_revision(store, timing=timing) + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("backend", ["sqlite", _OB]) +def test_worker_integrity_still_rejects_missing_active_chunks(tmp_path: Path, backend: str) -> None: + async def scenario() -> None: + async with _open_store(tmp_path, backend, vector=False) as store: + async with store.database.transaction() as connection: + await connection.execute( + delete(TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE).where( + TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE.c.scope_id == "scope-a" + ) + ) + async with store.reader.transaction() as connection: + with pytest.raises(TopicMemoryStorageInvariantError, match="missing-active-chunks"): + await store.repository.initialize(connection, configure_retrieval_shape=False) + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("backend", ["sqlite", _OB]) +@pytest.mark.parametrize( + "corruption", + ["topic-missing", "chunk-missing", "extra", "ordinal", "topic-profile", "chunk-profile", "extra-profile"], +) +def test_current_vector_integrity_rejects_real_corruption(tmp_path: Path, backend: str, corruption: str) -> None: + async def scenario() -> None: + async with _open_store(tmp_path, backend, vector=True) as store: + topics, chunks = store.index.indexes[1].tables + async with store.database.transaction() as connection: + table = topics if corruption.startswith("topic") else chunks + target = table.c.scope_id == "scope-a" + if "missing" in corruption: + await connection.execute(delete(table).where(target)) + elif corruption in {"topic-profile", "chunk-profile"}: + await connection.execute(update(table).where(target).values(profile_fingerprint="invalid")) + elif corruption == "ordinal": + await connection.execute( + update(chunks).where(target, chunks.c.chunk_ordinal == 0).values(chunk_ordinal=99) + ) + else: + row = dict((await connection.execute(select(chunks).where(target).limit(1))).mappings().one()) + row.pop("vector_id", None) + row["chunk_ordinal"] = 99 + if corruption == "extra-profile": + row["profile_fingerprint"] = "invalid" + if "embedding" in row: + row["embedding"] = _VECTOR + await connection.execute(insert(chunks).values(**row)) + async with store.reader.transaction() as connection: + with pytest.raises(TopicMemoryStorageInvariantError, match="incomplete-vector") as caught: + await store.repository.initialize(connection, configure_retrieval_shape=False) + assert caught.value.identity == ("scope-a", store.first.as_ref()) + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("channel", ["topic", "chunk"]) +def test_sqlite_integrity_rejects_missing_physical_vectors(tmp_path: Path, channel: str) -> None: + async def scenario() -> None: + async with _open_store(tmp_path, "sqlite", vector=True) as store: + async with store.database.transaction() as connection: + statements = { + "topic": "DELETE FROM pc_topic_memory_topic_vec WHERE scope_id = 'scope-a'", + "chunk": "DELETE FROM pc_topic_memory_chunk_vec WHERE scope_id = 'scope-a'", + } + await connection.exec_driver_sql(statements[channel]) + async with store.reader.transaction() as connection: + with pytest.raises(TopicMemoryStorageInvariantError, match="incomplete-vector"): + await store.repository.initialize(connection, configure_retrieval_shape=False) + + asyncio.run(scenario())