diff --git a/.github/workflows/e2e-harness.yml b/.github/workflows/e2e-harness.yml index 815c481a2e..c42a3049e0 100644 --- a/.github/workflows/e2e-harness.yml +++ b/.github/workflows/e2e-harness.yml @@ -282,7 +282,8 @@ jobs: POWERCONTEXT_TEST_MIGRATION_OCEANBASE_URL: >- mysql+aoceanbase://root%40test:powercontext-e2e@127.0.0.1:2881/pc_migration_probe_server_recovery?charset=utf8mb4 run: | - timeout --signal=TERM --kill-after=10s 600s uv run --locked pytest -vv -s -rs \ + # Allow the five native cases to finish fixture cleanup and write the JUnit report. + timeout --signal=TERM --kill-after=10s 900s uv run --locked pytest -vv -s -rs \ tests/builtin/persistence/test_mysql_migration_runner.py::test_mysql_registered_processing_mode_switch_preserves_revision_and_history \ tests/builtin/persistence/test_mysql_migration_runner.py::test_mysql_atomic_compatibility_command_uses_shared_server_upgrade \ tests/builtin/persistence/test_mysql_migration_runner.py::test_mysql_registered_projection_repair_preserves_authority_and_revision \ diff --git a/docs/en/development/processing-failures.md b/docs/en/development/processing-failures.md index 112cad46e3..bf3b4ff2e5 100644 --- a/docs/en/development/processing-failures.md +++ b/docs/en/development/processing-failures.md @@ -19,7 +19,7 @@ Every processing failure keeps the existing identity and outcome fields (`family | `processing_stage` | The stage that owned the failure | `generation`, `embedding`, `output_parsing`, `business_validation`, `persistence`, `usage_accounting` (reserved for usage reporting or persistence) | | `failure_reason` | A bounded reason, only when evidence supports it | `context_overflow`, `output_truncated`, `rate_limit`, `timeout`, `schema_invalid`, `provider_unavailable`, `configuration`, `invalid_output`, `storage_failure`, `usage_limit` | | `input_item_count` | Number of input items in the failing call | Non-negative integer | -| `estimated_input_tokens` | Estimated input tokens | Non-negative integer | +| `estimated_input_tokens` | Estimated input tokens; for a window token ceiling, the charged or reserved token count | Non-negative integer | | `token_estimator_id` | Identity of the estimator that produced the estimate | Bounded string | | `effective_budget` | Budget applied to the call | Non-negative integer | | `provider_request_id` | Provider request identity, when reported | Bounded string | @@ -35,6 +35,8 @@ carries no stage. A child failure without a domain block may omit `stage` entire is the bounded domain stage. Counts and identifiers are bounded before they reach a log record, and unknown or unsupported values are omitted rather than guessed. +For Topic Memory window budgets, request and attempt ceilings retain the usage-limit reason and failure location without token-specific fields. A rejected reservation does not persist its proposed charges. Later reads omit token-specific fields when the committed counters cannot establish the limiting dimension; they never reconstruct token overflow from the failure code alone. + ## Privacy boundary Diagnostics never carry Source or Artifact bodies, prompts, model responses, credentials, @@ -52,14 +54,14 @@ in its processing path. | Family | Generation | Embedding | Output parsing | Business validation | Persistence | Usage accounting | |---|---|---|---|---|---|---| | Memory / Atomic Memory | Partial | Covered | Partial | Covered | Partial | Missing | -| Topic Memory | Partial | Partial | Partial | Missing | Missing | Missing | +| Topic Memory | Partial | Covered | Partial | Covered | Partial | Missing | | Experience | Partial | N/A | Partial | Missing | Missing | Missing | | Profile | Partial | N/A | Partial | Missing | Missing | Missing | | Skill | Partial | N/A | Partial | Missing | Missing | Missing | | Handoff | Partial | N/A | Partial | Missing | Missing | Missing | | Prompt | Partial | N/A | Partial | Missing | Missing | Missing | -Memory / Atomic Memory is tracked at operation granularity while it is the active slice: +Memory / Atomic Memory and Topic Memory are tracked at operation granularity while they are the active slices: | Operation | Stage | Status | Notes | |---|---|---|---| @@ -73,16 +75,27 @@ Memory / Atomic Memory is tracked at operation granularity while it is the activ | Publish / index | Persistence | Partial | `AtomicMemoryIndexError` codes are mapped; other storage failures keep unknown. | | Usage accounting | Usage accounting | Missing | Usage-reporting and persistence failures are not classified; inference usage limits are reported in their originating stage (generation, or embedding when an adapter reports the limit). | -The first rollout slice covers Memory / Atomic Memory: provider failures, budget exhaustion, and -extraction/reconciliation validation are classified, and safe accounting fields travel from the -child Worker to the supervisor log. Other Families keep their current behavior until their own slice -lands; the matrix is updated in the same change as each slice. +Topic Memory operation-level coverage: + +| Operation | Stage | Status | Notes | +|---|---|---|---| +| `topic-memory` stages (`probe`, `global`, `planner`, `evolve`, `temporary`, `reconcile`) | Generation | Partial | Provider timeout, unavailability, rate limit, and configuration are classified; a provider finish reason is only visible where the adapter exposes it. | +| `topic-memory` stages | Output parsing | Partial | Provider schema failures use the shared mapping; semantic rejections are business validation. | +| `topic-memory` stages | Business validation | Covered | Every `TopicMemoryGenerationError` code maps to bounded diagnostics: domain and model rejections carry a stage and, when evidence supports it, a reason; control-flow rejections carry only `failure_location`. Input-budget failures carry input counts, token estimates, estimator identity, and the effective budget; the window token ceiling carries the charged tokens and the ceiling, while attempt and request ceilings are reported through their block details. | +| `topic-memory.index` and query embedding | Embedding | Covered | A missing embedding adapter and a wrong vector count are classified. | +| Publish / persistence | Persistence | Partial | Projection content and vector-completeness rules are business validation; storage-invariant failures map to `persistence` / `storage_failure`; unsupported capabilities report `configuration`; publisher conflicts keep their domain outcomes, and other storage failures keep unknown. | +| Usage accounting | Usage accounting | Missing | The window provider budget is reported as `generation` / `usage_limit`; accounting failures are not classified. | + +The first two rollout slices cover Memory / Atomic Memory and Topic Memory: provider failures, +budget exhaustion, and extraction/reconciliation/domain validation are classified, and safe +accounting fields travel from the child Worker to the supervisor log. Other Families keep their +current behavior until their own slice lands; the matrix is updated in the same change as each slice. ## Rollout 1. Shared diagnostics contract, allowlisted fields, Worker propagation, and the Memory / Atomic - Memory slice (this change). -2. Topic Memory: tag its staged generation, index/embedding, and persistence failures. + Memory slice. +2. Topic Memory: tag its staged generation, index/embedding, and persistence failures (this change). 3. Experience, Profile, and Skill: tag generation output validation and persistence entry points. 4. Handoff and Prompt: tag generation and publication failures, then add usage-accounting classification and complete the matrix. diff --git a/docs/zh/development/processing-failures.md b/docs/zh/development/processing-failures.md index 08ca876226..ec9bccbdb3 100644 --- a/docs/zh/development/processing-failures.md +++ b/docs/zh/development/processing-failures.md @@ -18,7 +18,7 @@ telemetry 系统。 | `processing_stage` | 失败所属的处理阶段 | `generation`、`embedding`、`output_parsing`、`business_validation`、`persistence`、`usage_accounting`(预留给账务上报或持久化) | | `failure_reason` | 有证据支持时才给出的有界原因 | `context_overflow`、`output_truncated`、`rate_limit`、`timeout`、`schema_invalid`、`provider_unavailable`、`configuration`、`invalid_output`、`storage_failure`、`usage_limit` | | `input_item_count` | 失败调用涉及的输入条目数 | 非负整数 | -| `estimated_input_tokens` | 估算的输入 token 数 | 非负整数 | +| `estimated_input_tokens` | 估算的输入 token 数;window token 上限触发时为已计费或已预留的 token 数 | 非负整数 | | `token_estimator_id` | 产生估算值的估算器标识 | 有界字符串 | | `effective_budget` | 本次调用生效的预算 | 非负整数 | | `provider_request_id` | provider 返回的请求标识 | 有界字符串 | @@ -33,6 +33,8 @@ Worker/supervisor 值(`worker_process`、`work_admission`、`supervisor`、`le `processing_stage` 表示有界的领域阶段。计数与标识在写入日志前会被限界;未知或不受支持的值直接省略, 不做猜测。 +对于 Topic Memory 窗口预算,请求次数和尝试次数上限保留 usage-limit 原因和失败位置,不附带 token 专用字段。被拒绝的预留不会持久化拟议扣费。当已提交的计数无法确定限制维度时,后续读取省略 token 专用字段,不会仅根据失败码推断 token 超限。 + ## 隐私边界 诊断不得包含 Source/Artifact 正文、prompt、模型响应、凭据、授权头、SQL 参数或任意异常文本。provider @@ -46,14 +48,14 @@ Worker/supervisor 值(`worker_process`、`work_admission`、`supervisor`、`le | Family | Generation | Embedding | Output parsing | Business validation | Persistence | Usage accounting | |---|---|---|---|---|---|---| | Memory / Atomic Memory | Partial | Covered | Partial | Covered | Partial | Missing | -| Topic Memory | Partial | Partial | Partial | Missing | Missing | Missing | +| Topic Memory | Partial | Covered | Partial | Covered | Partial | Missing | | Experience | Partial | N/A | Partial | Missing | Missing | Missing | | Profile | Partial | N/A | Partial | Missing | Missing | Missing | | Skill | Partial | N/A | Partial | Missing | Missing | Missing | | Handoff | Partial | N/A | Partial | Missing | Missing | Missing | | Prompt | Partial | N/A | Partial | Missing | Missing | Missing | -Memory / Atomic Memory 作为当前切片,按 operation 粒度跟踪: +Memory / Atomic Memory 与 Topic Memory 作为当前切片,按 operation 粒度跟踪: | Operation | Stage | 状态 | 说明 | |---|---|---|---| @@ -67,14 +69,25 @@ Memory / Atomic Memory 作为当前切片,按 operation 粒度跟踪: | Publish / index | Persistence | Partial | `AtomicMemoryIndexError` 的 code 已映射;其他存储失败保持 unknown。 | | Usage accounting | Usage accounting | Missing | 尚未分类账务上报与持久化失败;推理用量限制归入其来源阶段(generation,或 embedding adapter 上报时归入 embedding)。 | -第一个落地切片覆盖 Memory / Atomic Memory:provider 失败、预算耗尽、提取/对账校验均有分类,安全计数字段 -可从子 Worker 传播到 supervisor 日志。其他 Family 在各自切片落地前保持现有行为;每次切片在同一变更中更新 -本矩阵。 +Topic Memory 的 operation 级覆盖: + +| Operation | Stage | 状态 | 说明 | +|---|---|---|---| +| `topic-memory` 各阶段(`probe`、`global`、`planner`、`evolve`、`temporary`、`reconcile`) | Generation | Partial | provider timeout、不可用、限流、配置错误已分类;仅 adapter 暴露 finish reason 时可见。 | +| `topic-memory` 各阶段 | Output parsing | Partial | provider schema 失败走共享映射;语义拒绝归为 business validation。 | +| `topic-memory` 各阶段 | Business validation | Covered | 每个 `TopicMemoryGenerationError` code 都有有界诊断:领域/模型拒绝携带 stage,并在有证据时给出 reason;控制流拒绝只携带 `failure_location`。输入预算失败携带输入计数、token 估算、estimator 标识和生效预算;window token 上限触发时携带已计费 token 与上限,attempt/request 上限通过 block details 报告。 | +| `topic-memory.index` 与查询嵌入 | Embedding | Covered | 缺少 embedding adapter、向量数量错误均已分类。 | +| Publish / persistence | Persistence | Partial | 投影内容及向量完整性规则归业务校验;存储不变量失败归 `persistence` / `storage_failure`;不支持的能力归 `configuration`;publisher 冲突保留既有领域结果,其他存储失败保持 unknown。 | +| Usage accounting | Usage accounting | Missing | window provider budget 归为 `generation` / `usage_limit`;账务失败未分类。 | + +前两个落地切片覆盖 Memory / Atomic Memory 与 Topic Memory:provider 失败、预算耗尽、提取/对账/领域校验 +均有分类,安全计数字段可从子 Worker 传播到 supervisor 日志。其他 Family 在各自切片落地前保持现有行为; +每次切片在同一变更中更新本矩阵。 ## 落地顺序 -1. 共享诊断契约、日志白名单字段、Worker 传播,以及 Memory / Atomic Memory 切片(本次变更)。 -2. Topic Memory:标注分阶段生成、索引/嵌入与持久化失败。 +1. 共享诊断契约、日志白名单字段、Worker 传播,以及 Memory / Atomic Memory 切片。 +2. Topic Memory:标注分阶段生成、索引/嵌入与持久化失败(本次变更)。 3. Experience、Profile、Skill:标注生成输出校验与持久化入口。 4. Handoff、Prompt:标注生成与发布失败,再补 usage accounting 分类并补全矩阵。 diff --git a/release/upgrade-support.json b/release/upgrade-support.json index bbf19063bd..68cdfbafd2 100644 --- a/release/upgrade-support.json +++ b/release/upgrade-support.json @@ -3,8 +3,8 @@ "target_version": "1.5.0", "mode": "upgrade-required", "schema_review": { - "persistence_sha256": "53f1fd23a2a23cf77c2b70acd6e29e11c5d3e0d6eb3ee56a8b1cf8e9e0334a33", - "rationale": "The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. New Server revisions use software-version-plus-sequence names directly; software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum." + "persistence_sha256": "02dc8322b0f3440903e3831a41daf43307f2ec2cc77d6ec9cc3e63b3d4c98889", + "rationale": "Topic Memory processing failures attach bounded, content-free stage, reason and budget diagnostics to in-flight exceptions. Rejected reservations retain their existing durable charges; readback omits token-specific fields unless committed evidence establishes the limiting dimension, and repeated rejected calls cannot reinterpret prior evidence. Source structure and history-count guards do not imply context overflow. Missing FTS capability is configuration, and incomplete vector projections are business validation. No database schema, migration resource, registered table layout, frozen revision checksum, row encoding, persisted journal format or worker retry behavior is changed by these diagnostic annotations. The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. New Server revisions use software-version-plus-sequence names directly; software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum." }, "cases": [], "automatic_sources": { diff --git a/src/powercontext/builtin/artifacts/topic_memory/generation.py b/src/powercontext/builtin/artifacts/topic_memory/generation.py index fdda968087..a4953e70c4 100644 --- a/src/powercontext/builtin/artifacts/topic_memory/generation.py +++ b/src/powercontext/builtin/artifacts/topic_memory/generation.py @@ -26,12 +26,25 @@ from powercontext.builtin.artifacts.topic_memory.models import TopicMemoryContent from powercontext.builtin.inference import GenerationResult, StructuredGenerator, TokenEstimator +from powercontext.builtin.processing_diagnostics import ( + ProcessingDiagnostics, + ProcessingFailureReason, + ProcessingStage, + attach_diagnostics, +) MAX_TOPIC_MEMORY_STAGE_ITEMS = 20 _OUTPUT_RESERVE_RATIO = 0.20 _RETRY_FEEDBACK_TOKENS = 128 +def _estimator_id(estimator: TokenEstimator) -> str | None: + try: + return estimator.profile.estimator_id + except Exception: + return None + + class TopicMemoryGenerationError(RuntimeError): """Reject unsafe or internally inconsistent model output without publishing.""" @@ -137,8 +150,19 @@ def __init__( async def generate(self, value: InputT, /) -> GenerationResult[OutputT]: request = f"{self._fixed_prompt}\n{value.model_dump_json(exclude_none=False)}" - if self._estimator.estimate(request) > self._budget.input_tokens_limit: - raise TopicMemoryGenerationError("input_budget_exceeded") + estimate = self._estimator.estimate(request) + if estimate > self._budget.input_tokens_limit: + raise attach_diagnostics( + TopicMemoryGenerationError("input_budget_exceeded"), + ProcessingDiagnostics( + stage=ProcessingStage.BUSINESS_VALIDATION, + reason=ProcessingFailureReason.CONTEXT_OVERFLOW, + estimated_input_tokens=estimate, + token_estimator_id=_estimator_id(self._estimator), + effective_budget=self._budget.input_tokens_limit, + failure_location="generation", + ), + ) return await self._delegate.generate(value) @@ -461,8 +485,18 @@ def validate_topic_memory_stage_capacity( """Require every stage's real fixed prompt plus a minimal valid input to fit.""" for request in _topic_memory_minimum_stage_requests(): - if estimator.estimate(request) > budget.input_tokens_limit: - raise TopicMemoryGenerationError("input_budget_exceeded") + estimate = estimator.estimate(request) + if estimate > budget.input_tokens_limit: + raise attach_diagnostics( + TopicMemoryGenerationError("input_budget_exceeded"), + ProcessingDiagnostics( + reason=ProcessingFailureReason.CONFIGURATION, + estimated_input_tokens=estimate, + token_estimator_id=_estimator_id(estimator), + effective_budget=budget.input_tokens_limit, + failure_location="stage-capacity", + ), + ) __all__ = [ diff --git a/src/powercontext/builtin/persistence/topic_memory_budget.py b/src/powercontext/builtin/persistence/topic_memory_budget.py index ddbc6257aa..cc35ac1ac5 100644 --- a/src/powercontext/builtin/persistence/topic_memory_budget.py +++ b/src/powercontext/builtin/persistence/topic_memory_budget.py @@ -37,6 +37,12 @@ TOPIC_MEMORY_WORK_BLOCKS_TABLE, TOPIC_MEMORY_WORK_BUDGETS_TABLE, ) +from powercontext.builtin.processing_diagnostics import ( + ProcessingDiagnostics, + ProcessingFailureReason, + ProcessingStage, + attach_diagnostics, +) # Server-owned ceilings, shared by ALL attempts and stages at the same Cursor. MAX_TOPIC_MEMORY_WORK_ATTEMPTS = 3 @@ -91,13 +97,61 @@ async def load_topic_memory_work_budget( return (await connection.execute(statement)).mappings().one_or_none() +def _ceiling_dimension(requests: int, tokens: int) -> bool | None: + """Infer a limiting dimension only when committed charges establish it. + + Rejected proposed charges are absent on readback; both counters below + their ceilings (or both at their ceilings) leave the dimension unknown. + """ + if requests < MAX_TOPIC_MEMORY_WORK_REQUESTS and tokens >= MAX_TOPIC_MEMORY_WORK_TOKENS: + return True # token ceiling + if requests >= MAX_TOPIC_MEMORY_WORK_REQUESTS and tokens < MAX_TOPIC_MEMORY_WORK_TOKENS: + return False # request ceiling + return None + + +def _topic_memory_budget_error( + reason: str, *, tokens: int | None = None, token_ceiling: bool | None = None +) -> TopicMemoryGenerationError: + error = TopicMemoryGenerationError(reason) + if reason == "window_attempt_limit": + # The attempt ceiling ended the window; charged tokens are not the limiting budget. + attach_diagnostics( + error, + ProcessingDiagnostics( + stage=ProcessingStage.GENERATION, + reason=ProcessingFailureReason.USAGE_LIMIT, + failure_location=reason, + ), + ) + elif reason == "window_provider_budget_exceeded": + # None → cannot tell which ceiling was crossed from the persisted state + # alone (a rejected reservation's proposed charges are not stored). + # True → token ceiling; False → request ceiling. + attach_diagnostics( + error, + ProcessingDiagnostics( + stage=ProcessingStage.GENERATION, + reason=ProcessingFailureReason.USAGE_LIMIT, + estimated_input_tokens=tokens if token_ceiling else None, + effective_budget=MAX_TOPIC_MEMORY_WORK_TOKENS if token_ceiling else None, + failure_location=reason, + ), + ) + return error + + async def require_topic_memory_work_available( connection: AsyncConnection, scope_id: str, binding_name: str, source_after: int ) -> None: """Worker-side guard before Source materialization and projection.""" row = await load_topic_memory_work_budget(connection, scope_id, binding_name, source_after) if row is not None and (reason := exhausted_reason(row)): - raise TopicMemoryGenerationError(reason) + raise _topic_memory_budget_error( + reason, + tokens=int(row["tokens"]), + token_ceiling=_ceiling_dimension(int(row["requests"]), int(row["tokens"])), + ) async def record_topic_memory_work_failure( @@ -242,7 +296,11 @@ async def begin(self) -> None: ) ) if reason: - raise TopicMemoryGenerationError(reason) + raise _topic_memory_budget_error( + reason, + tokens=None if row is None else int(row["tokens"]), + token_ceiling=None if row is None else _ceiling_dimension(int(row["requests"]), int(row["tokens"])), + ) async def _current(self, connection: AsyncConnection): table = TOPIC_MEMORY_WORK_BUDGETS_TABLE @@ -260,15 +318,20 @@ async def reserve(self, *, requests: int, tokens: int) -> None: await self._lock(connection) row = await self._current(connection) reason = str(row["failure_code"]) + requests_after = row["requests"] + requests + tokens_after = row["tokens"] + tokens + diagnostic_requests = row["requests"] + diagnostic_tokens = row["tokens"] if reason in RECOVERABLE_TOPIC_MEMORY_REJECTIONS: # Diagnosis only: this attempt is still allowed to run and to charge # the reservation, or the frontier could never be retried. reason = "" if not reason and ( - row["requests"] + requests > MAX_TOPIC_MEMORY_WORK_REQUESTS - or row["tokens"] + tokens > MAX_TOPIC_MEMORY_WORK_TOKENS + requests_after > MAX_TOPIC_MEMORY_WORK_REQUESTS or tokens_after > MAX_TOPIC_MEMORY_WORK_TOKENS ): reason = "window_provider_budget_exceeded" + diagnostic_requests = requests_after + diagnostic_tokens = tokens_after values = ( {"failure_code": reason} if reason @@ -277,7 +340,11 @@ async def reserve(self, *, requests: int, tokens: int) -> None: 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) + raise _topic_memory_budget_error( + reason, + tokens=diagnostic_tokens, + token_ceiling=_ceiling_dimension(diagnostic_requests, diagnostic_tokens), + ) async def fail(self, reason: str) -> None: """Record a rejection cause on the frontier without storing source text. @@ -312,5 +379,9 @@ async def complete(self, connection: AsyncConnection) -> None: row = await self._current(connection) code = str(row["failure_code"]) if code and code not in RECOVERABLE_TOPIC_MEMORY_REJECTIONS: - raise TopicMemoryGenerationError(code) + raise _topic_memory_budget_error( + code, + tokens=int(row["tokens"]), + token_ceiling=_ceiling_dimension(int(row["requests"]), int(row["tokens"])), + ) await connection.execute(delete(TOPIC_MEMORY_WORK_BUDGETS_TABLE).where(*self._key())) diff --git a/src/powercontext/builtin/processing_diagnostics.py b/src/powercontext/builtin/processing_diagnostics.py index d70db7e029..1655adeba3 100644 --- a/src/powercontext/builtin/processing_diagnostics.py +++ b/src/powercontext/builtin/processing_diagnostics.py @@ -150,6 +150,76 @@ def diagnostics_of(error: BaseException) -> ProcessingDiagnostics | None: return value if isinstance(value, ProcessingDiagnostics) else None +def _topic_memory_diagnostics(code: str) -> ProcessingDiagnostics | None: + """Classify the bounded Topic Memory generation rejection vocabulary.""" + + value = code.lower() + if value == "embedding_unavailable": + return ProcessingDiagnostics( + stage=ProcessingStage.EMBEDDING, + reason=ProcessingFailureReason.CONFIGURATION, + failure_location=value, + ) + if value in {"input_budget_exceeded", "reduction_input_budget_exceeded"}: + return ProcessingDiagnostics( + stage=ProcessingStage.BUSINESS_VALIDATION, + reason=ProcessingFailureReason.CONTEXT_OVERFLOW, + failure_location=value, + ) + if value in {"window_provider_budget_exceeded", "window_attempt_limit"}: + return ProcessingDiagnostics( + stage=ProcessingStage.GENERATION, + reason=ProcessingFailureReason.USAGE_LIMIT, + failure_location=value, + ) + if value == "reduction_output_budget_exceeded": + return ProcessingDiagnostics( + stage=ProcessingStage.GENERATION, + reason=ProcessingFailureReason.USAGE_LIMIT, + failure_location=value, + ) + if value in {"output_budget_exceeded", "invalid_stage_budget", "invalid_max_tokens"}: + return ProcessingDiagnostics(reason=ProcessingFailureReason.CONFIGURATION, failure_location=value) + if value in { + "source_window_changed", + "invalid_window", + "duplicate_operation", + "window_attempt_superseded", + "target_did_not_converge", + "unaccepted_invocation", + "invalid_invocation", + "invalid_work_reservation", + }: + # Control-flow and concurrency rejections do not belong to a processing stage. + return ProcessingDiagnostics(failure_location=value) + if value in {"source_complexity_limit", "related_history_limit"}: + # Source structure/character and history-item caps do not establish + # that a model context window was exceeded. + return ProcessingDiagnostics( + stage=ProcessingStage.BUSINESS_VALIDATION, + failure_location=value, + ) + if value == "incomplete_target": + return ProcessingDiagnostics( + stage=ProcessingStage.PERSISTENCE, + reason=ProcessingFailureReason.STORAGE_FAILURE, + failure_location=value, + ) + if value.startswith("invalid_") or value in { + "unsupported_evidence", + "reduction_did_not_progress", + "duplicate_target", + "identity_merge", + "proposal_limit", + }: + return ProcessingDiagnostics( + stage=ProcessingStage.BUSINESS_VALIDATION, + reason=ProcessingFailureReason.INVALID_OUTPUT, + failure_location=value, + ) + return None + + def safe_classify_processing_error(error: BaseException) -> ProcessingDiagnostics | None: """Never let classification itself change a processing outcome.""" @@ -159,6 +229,17 @@ def safe_classify_processing_error(error: BaseException) -> ProcessingDiagnostic return None +def classify_block_code(stage: str | None, code: str | None) -> ProcessingDiagnostics | None: + """Classify a durable block that was observed without a Worker failure.""" + + if not isinstance(code, str) or not code: + return None + try: + return _topic_memory_diagnostics(code) if stage == "topic_memory" else None + except Exception: + return None + + def safe_log_fields(diagnostics: ProcessingDiagnostics | None) -> dict[str, str | int]: """Never let a diagnostics field failure suppress the failure record.""" @@ -275,6 +356,43 @@ def classify_processing_error(error: BaseException) -> ProcessingDiagnostics | N if code == "publication": return ProcessingDiagnostics(reason=ProcessingFailureReason.CONFIGURATION) return None + if "TopicMemoryGenerationError" in names: + return _topic_memory_diagnostics(str(getattr(error, "code", "") or "")) + if "TopicMemoryProjectionError" in names: + code = str(getattr(error, "code", "") or "").lower() + if code in {"content", "chunks", "lexical", "vector-incomplete"}: + return ProcessingDiagnostics( + stage=ProcessingStage.BUSINESS_VALIDATION, + reason=ProcessingFailureReason.INVALID_OUTPUT, + failure_location=code, + ) + if code in {"fts", "vector-unconfigured", "embedding-profile"}: + return ProcessingDiagnostics( + stage=ProcessingStage.PERSISTENCE, + reason=ProcessingFailureReason.CONFIGURATION, + failure_location=code, + ) + if code == "embedding-values": + return ProcessingDiagnostics( + stage=ProcessingStage.EMBEDDING, + reason=ProcessingFailureReason.INVALID_OUTPUT, + failure_location=code, + ) + return ProcessingDiagnostics(stage=ProcessingStage.PERSISTENCE, failure_location=code) + if "TopicMemoryStorageInvariantError" in names: + code = str(getattr(error, "code", "") or "").lower() + return ProcessingDiagnostics( + stage=ProcessingStage.PERSISTENCE, + reason=ProcessingFailureReason.STORAGE_FAILURE, + failure_location=code or None, + ) + if "TopicMemoryCapabilityError" in names: + capability = str(getattr(error, "capability", "") or "").lower() + return ProcessingDiagnostics( + stage=ProcessingStage.PERSISTENCE, + reason=ProcessingFailureReason.CONFIGURATION, + failure_location=capability or None, + ) return None @@ -283,6 +401,7 @@ def classify_processing_error(error: BaseException) -> ProcessingDiagnostics | N "ProcessingFailureReason", "ProcessingStage", "attach_diagnostics", + "classify_block_code", "classify_processing_error", "diagnostics_of", "safe_classify_processing_error", diff --git a/src/powercontext/builtin/runtime/artifact_processing.py b/src/powercontext/builtin/runtime/artifact_processing.py index 163fd58778..59e491a286 100644 --- a/src/powercontext/builtin/runtime/artifact_processing.py +++ b/src/powercontext/builtin/runtime/artifact_processing.py @@ -63,7 +63,12 @@ database_utc_now, ) from powercontext.builtin.persistence.tables import ARTIFACT_PROCESSING_LEASES_TABLE -from powercontext.builtin.processing_diagnostics import safe_classify_processing_error, safe_log_fields +from powercontext.builtin.processing_diagnostics import ( + ProcessingDiagnostics, + classify_block_code, + safe_classify_processing_error, + safe_log_fields, +) from powercontext.builtin.runtime.observations import DurationObservations, DurationObservationSnapshot from powercontext.builtin.runtime.processing_contracts import ( ArtifactProcessingBlock, @@ -1327,7 +1332,10 @@ def _wait_for_block( block: ArtifactProcessingBlock, *, trace_id: str | None = None, + diagnostics: ProcessingDiagnostics | None = None, ) -> None: + if diagnostics is None: + diagnostics = classify_block_code(block.stage, block.error_code) previous = state.retries.get(assignment.scope_id) if previous is None or previous.block != block: last_error_trace_id = None if previous is None else previous.last_error_trace_id @@ -1337,6 +1345,7 @@ def _wait_for_block( "Artifact processing blocked; operator remediation required", extra={ **dict(block.details), + **safe_log_fields(diagnostics), "event": "artifact_processing.blocked", "stage": block.stage, "error_code": block.error_code, @@ -1620,7 +1629,14 @@ async def _reap(self, state: _FamilyState) -> None: # noqa: C901 - distinct Wor if block is not None: observed_outcome = "blocked" diagnostic_code = block.error_code - self._wait_for_block(state, running.assignment, block, trace_id=running.trace_id) + diagnostics = ( + error.failure.diagnostics + if isinstance(error, _WorkerExecutionError) + else safe_classify_processing_error(error) + ) + self._wait_for_block( + state, running.assignment, block, trace_id=running.trace_id, diagnostics=diagnostics + ) continue if isinstance(error, TimeoutError): observed_outcome = "timeout" diff --git a/src/powercontext/builtin/runtime/topic_memory_processing.py b/src/powercontext/builtin/runtime/topic_memory_processing.py index 04899e2469..455cbe9e8b 100644 --- a/src/powercontext/builtin/runtime/topic_memory_processing.py +++ b/src/powercontext/builtin/runtime/topic_memory_processing.py @@ -108,6 +108,12 @@ TopicMemoryWorkBudget, require_topic_memory_work_available, ) +from powercontext.builtin.processing_diagnostics import ( + ProcessingDiagnostics, + ProcessingFailureReason, + ProcessingStage, + attach_diagnostics, +) from powercontext.builtin.runtime.config import BuiltinConfig, InferenceConfig from powercontext.builtin.runtime.processing_contracts import ( ArtifactProcessingWorkAssignment, @@ -584,7 +590,7 @@ async def process( async def _reserve_stage(self, value: BaseModel, stage: str) -> None: self._used_stages.add(stage) if not self._stages.fits(value, stage): - raise TopicMemoryGenerationError("input_budget_exceeded") + raise self._input_budget_error(value, stage, input_item_count=_topic_memory_item_count(value)) # 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 @@ -593,6 +599,41 @@ async def _reserve_stage(self, value: BaseModel, stage: str) -> None: ) await self._reserve(requests=self._stages.max_requests, tokens=self._stages.max_requests * capacity) + def _estimate_stage_input(self, value: BaseModel, stage: str) -> int: + fixed = self._stages.fixed_prompts.get(stage, stage) + return self._stages.estimator.estimate(f"{fixed}\n{value.model_dump_json(exclude_none=False)}") + + def _token_estimator_id(self) -> str | None: + try: + return self._stages.estimator.profile.estimator_id + except Exception: + return None + + def _input_budget_error( + self, + value: BaseModel, + stage: str, + *, + input_item_count: int | None = None, + code: str = "input_budget_exceeded", + ) -> TopicMemoryGenerationError: + try: + estimate = self._estimate_stage_input(value, stage) + except Exception: + estimate = None + return attach_diagnostics( + TopicMemoryGenerationError(code), + ProcessingDiagnostics( + stage=ProcessingStage.BUSINESS_VALIDATION, + reason=ProcessingFailureReason.CONTEXT_OVERFLOW, + input_item_count=input_item_count, + estimated_input_tokens=estimate, + token_estimator_id=self._token_estimator_id(), + effective_budget=self._stages.input_tokens_limit, + failure_location=stage, + ), + ) + async def _reserve(self, *, requests: int, tokens: int) -> None: budget = self._work_budget.get() if budget is not None: @@ -600,18 +641,34 @@ async def _reserve(self, *, requests: int, tokens: int) -> None: 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 + requests_after = self._local_requests + requests + tokens_after = self._local_tokens + tokens + if requests_after > MAX_TOPIC_MEMORY_WORK_REQUESTS or tokens_after > MAX_TOPIC_MEMORY_WORK_TOKENS: + token_ceiling = requests_after <= MAX_TOPIC_MEMORY_WORK_REQUESTS + raise attach_diagnostics( + TopicMemoryGenerationError("window_provider_budget_exceeded"), + ProcessingDiagnostics( + stage=ProcessingStage.GENERATION, + reason=ProcessingFailureReason.USAGE_LIMIT, + estimated_input_tokens=tokens_after if token_ceiling else None, + effective_budget=MAX_TOPIC_MEMORY_WORK_TOKENS if token_ceiling else None, + failure_location="window_provider_budget_exceeded", + ), + ) + self._local_requests = requests_after + self._local_tokens = tokens_after async def _embed(self, texts: tuple[str, ...]): model = self._embedding_model if model is None: - raise TopicMemoryGenerationError("embedding_unavailable") + raise attach_diagnostics( + TopicMemoryGenerationError("embedding_unavailable"), + ProcessingDiagnostics( + stage=ProcessingStage.EMBEDDING, + reason=ProcessingFailureReason.CONFIGURATION, + failure_location="topic-memory-embed", + ), + ) cached = self._document_vectors.get() if cached is None: cached = {} @@ -624,13 +681,27 @@ async def _embed(self, texts: tuple[str, ...]): ) result = await model.embed(pending) if len(result.vectors) != len(pending): - raise InvalidInferenceOutputError("topic-memory.index", "requires one vector per input") + raise attach_diagnostics( + InvalidInferenceOutputError("topic-memory.index", "requires one vector per input"), + ProcessingDiagnostics( + stage=ProcessingStage.EMBEDDING, + reason=ProcessingFailureReason.INVALID_OUTPUT, + failure_location="topic-memory-index", + ), + ) cached.update(((profile, text), vector) for text, vector in zip(pending, result.vectors, strict=True)) return EmbeddingResult(vectors=tuple(cached[profile, text] for text in texts)) async def _embed_query(self, texts: tuple[str, ...]): if self._embedding_model is None: - raise TopicMemoryGenerationError("embedding_unavailable") + raise attach_diagnostics( + TopicMemoryGenerationError("embedding_unavailable"), + ProcessingDiagnostics( + stage=ProcessingStage.EMBEDDING, + reason=ProcessingFailureReason.CONFIGURATION, + failure_location="topic-memory-embed-query", + ), + ) # 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)) @@ -705,6 +776,21 @@ def _reduction_input( max_result_tokens=max(1, self._stages.input_tokens_limit // 8), ) + def _reduction_input_error( + self, items: Sequence[TopicMemoryProbe | TopicMemoryProposal], *, temporary: bool + ) -> TopicMemoryGenerationError: + if self._stages.reducer is None: + return attach_diagnostics( + TopicMemoryGenerationError("reduction_input_budget_exceeded"), + ProcessingDiagnostics(reason=ProcessingFailureReason.CONFIGURATION, failure_location="reduce"), + ) + return self._input_budget_error( + self._reduction_input(items[:1], temporary=temporary), + "reduce", + input_item_count=1, + code="reduction_input_budget_exceeded", + ) + async def _compact_intermediates( self, values: Sequence[TopicMemoryProbe | TopicMemoryProposal], @@ -738,7 +824,7 @@ async def _compact_intermediates( 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") + raise self._reduction_input_error(items, temporary=temporary) request = self._reduction_input(items[:size], temporary=temporary) with self._usage(ModelUsagePurpose.TOPIC_MEMORY_GENERATION): output = (await self._stages.reducer.generate(request)).output @@ -755,7 +841,17 @@ async def _compact_intermediates( 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") + raise attach_diagnostics( + TopicMemoryGenerationError("reduction_output_budget_exceeded"), + ProcessingDiagnostics( + stage=ProcessingStage.GENERATION, + reason=ProcessingFailureReason.USAGE_LIMIT, + input_item_count=len(items[:size]), + token_estimator_id=self._token_estimator_id(), + effective_budget=request.max_result_tokens, + failure_location="reduce", + ), + ) if size == 1 and result_tokens >= self._stages.estimator.estimate(items[0].model_dump_json()): raise TopicMemoryGenerationError("reduction_did_not_progress") items[:size] = [result] @@ -809,7 +905,12 @@ def _evidence_fragments(self, item: TopicMemoryEvidence, stage: str) -> Iterable break size //= 2 else: - raise TopicMemoryGenerationError("input_budget_exceeded") + value = ( + TopicMemoryProbeInput(evidence=(item,)) + if stage == "probe" + else TopicMemoryTemporaryInput(work_id="work-batch", evidence=(item,)) + ) + raise self._input_budget_error(value, stage, input_item_count=1) def _evidence_batch_fits( self, @@ -1024,7 +1125,11 @@ async def _plan( # noqa: C901 historical=historical, ) if not self._stages.fits(flattened, "evolve"): - raise TopicMemoryGenerationError("input_budget_exceeded") + raise self._input_budget_error( + flattened, + "evolve", + input_item_count=len(temporary) + (1 if historical is not None else 0), + ) with self._usage(ModelUsagePurpose.TOPIC_MEMORY_GENERATION): proposal = (await self._stages.evolver.generate(flattened)).output.proposal if proposal is not None: @@ -1122,7 +1227,7 @@ async def _coordinate( ), ) if not self._stages.fits(reconcile_input, "reconcile"): - raise TopicMemoryGenerationError("input_budget_exceeded") + raise self._input_budget_error(reconcile_input, "reconcile", input_item_count=len(members)) known_ids.add(reconcile_input.component_id) with self._usage(ModelUsagePurpose.TOPIC_MEMORY_GENERATION): reconciled = (await self._stages.reconciler.generate(reconcile_input)).output.proposals @@ -1947,6 +2052,14 @@ def stage( await contexts.flush_model_usage() +def _topic_memory_item_count(value: BaseModel) -> int | None: + for name in ("evidence", "items", "proposals", "candidates", "temporary"): + items = getattr(value, name, None) + if isinstance(items, (tuple, list)): + return len(items) + return None + + __all__ = [ "PreparedTopicMemoryOperation", "TopicMemoryAtomicPublisher", diff --git a/src/powercontext/builtin/runtime/topic_memory_scope.py b/src/powercontext/builtin/runtime/topic_memory_scope.py index 7f45899370..fdbb01eba7 100644 --- a/src/powercontext/builtin/runtime/topic_memory_scope.py +++ b/src/powercontext/builtin/runtime/topic_memory_scope.py @@ -31,6 +31,11 @@ from powercontext.builtin.persistence.supervision import ArtifactProcessingLeaseRepository from powercontext.builtin.persistence.tables import SOURCE_JOURNAL_HEADS_TABLE, TOPIC_MEMORY_PROCESSING_TARGETS_TABLE from powercontext.builtin.persistence.topic_memory_recovery import observe_topic_memory_block +from powercontext.builtin.processing_diagnostics import ( + attach_diagnostics, + diagnostics_of, + safe_classify_processing_error, +) from powercontext.builtin.runtime.processing_contracts import ( ArtifactProcessingBlock, ArtifactProcessingBlockedError, @@ -165,7 +170,12 @@ async def _generation_failure( return ArtifactProcessingWorkerCompletion(ArtifactProcessingWorkerOutcome.LEADERSHIP_LOST) block = await topic_memory_processing_block(connection, assignment.scope_id, assignment.binding_name) if block is not None and block.error_code == error.code: - raise ArtifactProcessingBlockedError(block) from error + blocked = ArtifactProcessingBlockedError(block) + attach_diagnostics( + blocked, + diagnostics_of(error) or safe_classify_processing_error(error), + ) + raise blocked from error raise error async def _target(self, assignment: ArtifactProcessingWorkAssignment) -> TopicMemoryProcessingTarget | None: diff --git a/tests/builtin/persistence/test_topic_memory.py b/tests/builtin/persistence/test_topic_memory.py index bbebde8f6d..c0f8373f30 100644 --- a/tests/builtin/persistence/test_topic_memory.py +++ b/tests/builtin/persistence/test_topic_memory.py @@ -76,6 +76,11 @@ TopicMemoryIndex, topic_memory_embedding_profile_fingerprint, ) +from powercontext.builtin.processing_diagnostics import ( + ProcessingFailureReason, + ProcessingStage, + classify_processing_error, +) from powercontext.builtin.records import InvalidBaseAccessRequestError from powercontext.sources import SourceMaterialization, SourceRef from tests.builtin.persistence.contract import SOURCE_ADAPTERS, NoteSource @@ -1610,6 +1615,33 @@ async def scenario() -> None: asyncio.run(scenario()) +def test_publication_without_fts_reports_configuration_failure() -> None: + async def scenario() -> None: + repository = TopicMemoryRepository() + content = _content("Missing", "FTS") + async with ( + SQLiteProfile.open(SQLiteConfig(), tables=BUILTIN_TABLES) as profile, + profile.database.transaction() as connection, + ): + with pytest.raises(TopicMemoryProjectionError) as raised: + await repository.publish_create( + connection, + "scope-a", + "topic-missing-fts", + _draft(content), + prepare_topic_memory_projection(content), + ) + assert raised.value.code == "fts" + diagnostics = classify_processing_error(raised.value) + assert diagnostics is not None + assert diagnostics.stage is ProcessingStage.PERSISTENCE + assert diagnostics.reason is ProcessingFailureReason.CONFIGURATION + assert diagnostics.failure_location == "fts" + assert await connection.scalar(select(func.count()).select_from(ARTIFACTS_TABLE)) == 0 + + asyncio.run(scenario()) + + def test_sqlite_vector_and_hybrid_require_complete_active_embeddings() -> None: async def scenario() -> None: embedding_profile = EmbeddingProfile( @@ -1632,7 +1664,9 @@ async def scenario() -> None: async with profile.database.transaction() as connection: await repository.initialize(connection) incomplete_content = _content("Missing", "vector") - with pytest.raises(TopicMemoryProjectionError, match="requires the topic and every detail chunk"): + with pytest.raises( + TopicMemoryProjectionError, match="requires the topic and every detail chunk" + ) as raised: await repository.publish_create( connection, "scope-a", @@ -1640,6 +1674,11 @@ async def scenario() -> None: _draft(incomplete_content), prepare_topic_memory_projection(incomplete_content), ) + diagnostics = classify_processing_error(raised.value) + assert diagnostics is not None + assert diagnostics.stage is ProcessingStage.BUSINESS_VALIDATION + assert diagnostics.reason is ProcessingFailureReason.INVALID_OUTPUT + assert diagnostics.failure_location == "vector-incomplete" assert ( int( await connection.scalar( diff --git a/tests/builtin/runtime/test_processing_scheduler.py b/tests/builtin/runtime/test_processing_scheduler.py index dbb7c92c56..0305f0a976 100644 --- a/tests/builtin/runtime/test_processing_scheduler.py +++ b/tests/builtin/runtime/test_processing_scheduler.py @@ -29,10 +29,17 @@ ArtifactProcessingLeaseRepository, ) from powercontext.builtin.persistence.tables import SHARED_TABLES +from powercontext.builtin.processing_diagnostics import ( + ProcessingDiagnostics, + ProcessingFailureReason, + ProcessingStage, + attach_diagnostics, +) from powercontext.builtin.runtime import artifact_processing as processing from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingBinding, ArtifactProcessingSupervisor from powercontext.builtin.runtime.processing_contracts import ( ArtifactProcessingBlock, + ArtifactProcessingBlockedError, ArtifactProcessingWorkerCompletion, ArtifactProcessingWorkerOutcome, ) @@ -808,6 +815,9 @@ async def check(_connection, _scope, _binding): assert intent.requested_generation == 4 and intent.handled_generation == 0 blocked_logs = [r for r in caplog.records if getattr(r, "event", None) == "artifact_processing.blocked"] assert len(blocked_logs) == 1 + assert blocked_logs[0].processing_stage == "generation" + assert blocked_logs[0].failure_reason == "usage_limit" + assert blocked_logs[0].failure_location == "window_attempt_limit" assert not [r for r in caplog.records if getattr(r, "event", None) == "artifact_processing.failed"] recheck_logs = [ r for r in caplog.records if getattr(r, "event", None) == "artifact_processing.block_recheck_failed" @@ -856,3 +866,50 @@ async def check(_connection, scope, _binding): assert not [r for r in caplog.records if getattr(r, "stage", None) == "work_admission"] asyncio.run(scenario()) + + +def test_worker_blocked_log_carries_diagnostics(tmp_path, caplog): + caplog.set_level(logging.WARNING, logger=processing.__name__) + + async def scenario(): + async with _profile(tmp_path, "blocked-diagnostics") as profile: + await _request(profile.database, "topic-binding", "blocked") + + async def blocked(_assignment): + error = ArtifactProcessingBlockedError( + ArtifactProcessingBlock("0", "topic_memory", "window_attempt_limit", (("attempts", 3),)) + ) + attach_diagnostics( + error, + ProcessingDiagnostics( + stage=ProcessingStage.GENERATION, + reason=ProcessingFailureReason.USAGE_LIMIT, + failure_location="window_attempt_limit", + ), + ) + raise error + + launcher = _Launcher(profile.database, on_work=blocked) + async with ArtifactProcessingSupervisor( + database=profile.database, + bindings=(ArtifactProcessingBinding("topic-binding", "topic-memory", launcher),), + lease_mode="single-process", + retry_base_seconds=0.01, + retry_cap_seconds=0.01, + retry_jitter=lambda: 1, + blocked_check_seconds=60, + ) as supervisor: + await _wait( + lambda: any(getattr(r, "event", None) == "artifact_processing.blocked" for r in caplog.records) + ) + logs = [r for r in caplog.records if getattr(r, "event", None) == "artifact_processing.blocked"] + assert len(logs) == 1 + record = logs[0] + assert record.stage == "topic_memory" and record.error_code == "window_attempt_limit" + assert record.attempts == 3 + assert record.processing_stage == "generation" + assert record.failure_reason == "usage_limit" + assert record.failure_location == "window_attempt_limit" + assert supervisor.family_status["topic-memory"]["failed"] == 0 + + asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_topic_memory_fragment_reduction.py b/tests/builtin/runtime/test_topic_memory_fragment_reduction.py index 79d47ea86a..fdddc3056b 100644 --- a/tests/builtin/runtime/test_topic_memory_fragment_reduction.py +++ b/tests/builtin/runtime/test_topic_memory_fragment_reduction.py @@ -48,6 +48,11 @@ 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.processing_diagnostics import ( + ProcessingFailureReason, + ProcessingStage, + classify_processing_error, +) from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingWorkerOutcome from powercontext.builtin.runtime.topic_memory_processing import ( TopicMemoryAtomicPublisher, @@ -220,8 +225,15 @@ async def _scenario(*, repeated=False, input_limit=100_000, characters=2_100_000 ) assignment = _assignment(term.fence("single-process"), through=selected) if failure: - with pytest.raises((TopicMemoryGenerationError, RuntimeError), match="reduction"): + with pytest.raises((TopicMemoryGenerationError, RuntimeError), match="reduction") as raised: await processor.process(assignment) + if failure == "budget": + assert isinstance(raised.value, TopicMemoryGenerationError) + diagnostics = classify_processing_error(raised.value) + assert diagnostics is not None + assert diagnostics.token_estimator_id == estimator.profile.estimator_id + assert diagnostics.reason is ProcessingFailureReason.USAGE_LIMIT + assert diagnostics.estimated_input_tokens is None async with profile.database.transaction() as connection: assert ( await SourceCursorRepository().load(connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING) @@ -284,3 +296,53 @@ async def _scenario(*, repeated=False, input_limit=100_000, characters=2_100_000 assert cursor is not None and cursor.cursor.sequence == tail.journal_position finally: await manager.__aexit__(None, None, None) + + +def test_reduction_input_budget_diagnostics_include_the_fixed_prompt() -> None: + async def scenario(): + manager, profile, _, topics = await _repositories() + sources = SourceRepository((*SOURCE_ADAPTERS, CONTENT_SOURCE_ADAPTER)) + try: + estimator = character_token_estimator() + fixed = "R" * 10_000 + stages = TopicMemoryStageSet( + probe=_QueueGenerator(), + global_evolver=_QueueGenerator(), + planner=_QueueGenerator(), + evolver=_QueueGenerator(), + temporary=_QueueGenerator(), + reconciler=_QueueGenerator(), + reducer=_QueueGenerator(), + estimator=estimator, + input_tokens_limit=250, + fixed_prompts={"reduce": fixed}, + ) + processor = TopicMemoryProcessor( + database=profile.database, + sources=sources, + topics=topics, + stages=stages, + publisher=TopicMemoryAtomicPublisher(profile.database, sources, topics), + ) + values = (TopicMemoryProbe(query="observation", evidence_ids=("evidence-0001",)),) + + with pytest.raises(TopicMemoryGenerationError, match="reduction_input_budget_exceeded") as raised: + await processor._compact_intermediates(values) + + diagnostics = classify_processing_error(raised.value) + assert diagnostics is not None + assert diagnostics.stage is ProcessingStage.BUSINESS_VALIDATION + assert diagnostics.reason is ProcessingFailureReason.CONTEXT_OVERFLOW + assert diagnostics.input_item_count == 1 + assert diagnostics.token_estimator_id == estimator.profile.estimator_id + assert diagnostics.effective_budget == 250 + assert diagnostics.failure_location == "reduce" + expected = estimator.estimate( + f"{fixed}\n{processor._reduction_input(values, temporary=False).model_dump_json(exclude_none=False)}" + ) + assert diagnostics.estimated_input_tokens == expected + assert expected > diagnostics.effective_budget + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_topic_memory_processing.py b/tests/builtin/runtime/test_topic_memory_processing.py index c33ae49629..6ed2ecf37c 100644 --- a/tests/builtin/runtime/test_topic_memory_processing.py +++ b/tests/builtin/runtime/test_topic_memory_processing.py @@ -101,6 +101,11 @@ CompositeTopicMemoryIndex, topic_memory_embedding_profile_fingerprint, ) +from powercontext.builtin.processing_diagnostics import ( + ProcessingFailureReason, + ProcessingStage, + classify_processing_error, +) from powercontext.builtin.runtime.artifact_processing import ( ArtifactProcessingBinding, ArtifactProcessingSupervisor, @@ -1708,9 +1713,19 @@ def unexpected_id() -> str: id_factory=unexpected_id, ) - with pytest.raises(TopicMemoryGenerationError, match="input_budget_exceeded"): + with pytest.raises(TopicMemoryGenerationError, match="input_budget_exceeded") as raised: await processor.process(_assignment(term.fence("single-process"))) + diagnostics = classify_processing_error(raised.value) + assert diagnostics is not None + assert diagnostics.stage is ProcessingStage.BUSINESS_VALIDATION + assert diagnostics.reason is ProcessingFailureReason.CONTEXT_OVERFLOW + assert diagnostics.estimated_input_tokens is not None + assert diagnostics.effective_budget is not None + assert diagnostics.estimated_input_tokens > diagnostics.effective_budget + assert diagnostics.token_estimator_id is not None + assert diagnostics.failure_location is not None + assert stages.reconciler.inputs == [] async with profile.database.transaction() as connection: cursor = await SourceCursorRepository().load( diff --git a/tests/builtin/runtime/test_topic_memory_scope.py b/tests/builtin/runtime/test_topic_memory_scope.py index 754eb4ddd2..ab242afa5c 100644 --- a/tests/builtin/runtime/test_topic_memory_scope.py +++ b/tests/builtin/runtime/test_topic_memory_scope.py @@ -18,7 +18,7 @@ from dataclasses import replace import pytest -from sqlalchemy import select, update +from sqlalchemy import insert, select, update from powercontext.builtin.artifacts.topic_memory import TOPIC_MEMORY_SOURCE_WINDOW_BINDING from powercontext.builtin.artifacts.topic_memory.generation import TopicMemoryProbeOutput @@ -32,7 +32,13 @@ TOPIC_MEMORY_PROCESSING_TARGETS_TABLE, TOPIC_MEMORY_WORK_BUDGETS_TABLE, ) +from powercontext.builtin.processing_diagnostics import ( + ProcessingFailureReason, + ProcessingStage, + classify_processing_error, +) from powercontext.builtin.runtime.processing_contracts import ( + ArtifactProcessingBlockedError, ArtifactProcessingWorkAssignment, ArtifactProcessingWorkerOutcome, ) @@ -365,3 +371,41 @@ async def process_window(self, window, *, commit_hook=None): await manager.__aexit__(None, None, None) asyncio.run(scenario()) + + +def test_blocked_conversion_keeps_generation_diagnostics(): + async def scenario(): + manager, profile, sources, topics = await _repositories() + try: + await _capture(profile, sources, 1) + async with profile.database.transaction() as connection: + await connection.execute( + insert(TOPIC_MEMORY_WORK_BUDGETS_TABLE).values({ + "scope_id": "scope-a", + "binding_name": BINDING, + "source_after": 0, + "source_through": 1, + "attempt_id": "exhausted-attempt", + "attempts": 3, + "requests": 9, + "tokens": 1000, + "failure_code": "", + }) + ) + processor = _processor(profile, sources, topics, _Probe()) + + with pytest.raises(ArtifactProcessingBlockedError) as raised: + await processor.process(await _assignment(profile)) + + assert raised.value.block.error_code == "window_attempt_limit" + diagnostics = classify_processing_error(raised.value) + assert diagnostics is not None + assert diagnostics.stage is ProcessingStage.GENERATION + assert diagnostics.reason is ProcessingFailureReason.USAGE_LIMIT + assert diagnostics.failure_location == "window_attempt_limit" + assert diagnostics.estimated_input_tokens is None + assert diagnostics.effective_budget is None + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_topic_memory_work_budget.py b/tests/builtin/runtime/test_topic_memory_work_budget.py index 193a256b8f..49e0e94be1 100644 --- a/tests/builtin/runtime/test_topic_memory_work_budget.py +++ b/tests/builtin/runtime/test_topic_memory_work_budget.py @@ -44,6 +44,11 @@ MAX_TOPIC_MEMORY_WORK_REQUESTS, MAX_TOPIC_MEMORY_WORK_TOKENS, ) +from powercontext.builtin.processing_diagnostics import ( + ProcessingFailureReason, + ProcessingStage, + classify_processing_error, +) from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingWorkerOutcome from powercontext.builtin.runtime.composition import ( BuiltinConfigurationError, @@ -218,8 +223,21 @@ async def scenario(): 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"): + with pytest.raises(TopicMemoryGenerationError, match="window_provider_budget_exceeded") as raised: await processor.process(assignment) + + diagnostics = classify_processing_error(raised.value) + assert diagnostics is not None + assert diagnostics.stage is ProcessingStage.GENERATION + assert diagnostics.reason is ProcessingFailureReason.USAGE_LIMIT + assert diagnostics.failure_location == "window_provider_budget_exceeded" + if ceiling == "requests": + # The request ceiling stopped the window; the token budget did not. + assert diagnostics.estimated_input_tokens is None + assert diagnostics.effective_budget is None + else: + assert diagnostics.estimated_input_tokens is not None + assert diagnostics.effective_budget == MAX_TOPIC_MEMORY_WORK_TOKENS before = await _row(profile) assert before["failure_code"] == "window_provider_budget_exceeded" assert before["requests"] == fake.calls * requests <= MAX_TOPIC_MEMORY_WORK_REQUESTS @@ -626,3 +644,69 @@ async def embed(self, texts, /): await manager.__aexit__(None, None, None) asyncio.run(scenario()) + + +@pytest.mark.parametrize("dimension", ["requests", "tokens", "both", "exact_requests"]) +def test_rejected_reservation_readback_does_not_invent_token_evidence(dimension): + from powercontext.builtin.persistence.topic_memory_budget import ( + TopicMemoryWorkBudget, + require_topic_memory_work_available, + ) + + async def scenario(): + manager, profile, _, _ = await _repositories() + try: + _, assignment = await _capture(profile) + budget = TopicMemoryWorkBudget( + profile.database, + scope_id="scope-a", + binding_name=TOPIC_MEMORY_SOURCE_WINDOW_BINDING, + source_after=0, + source_through=2, + cursor_generation=None, + fence=assignment.fence, + ) + await budget.begin() + initial_requests = MAX_TOPIC_MEMORY_WORK_REQUESTS if dimension == "exact_requests" else 510 + await budget.reserve(requests=initial_requests, tokens=1000) + requests = 3 if dimension in {"requests", "both"} else 1 + tokens = MAX_TOPIC_MEMORY_WORK_TOKENS if dimension in {"tokens", "both"} else 10 + with pytest.raises(TopicMemoryGenerationError) as rejected: + await budget.reserve(requests=requests, tokens=tokens) + original = classify_processing_error(rejected.value) + assert original is not None + assert original.reason is ProcessingFailureReason.USAGE_LIMIT + assert original.effective_budget == (MAX_TOPIC_MEMORY_WORK_TOKENS if dimension == "tokens" else None) + before = await _row(profile) + assert before["requests"] == initial_requests and before["tokens"] == 1000 + + async def guard(): + async with profile.database.transaction() as connection: + await require_topic_memory_work_available( + connection, "scope-a", TOPIC_MEMORY_SOURCE_WINDOW_BINDING, 0 + ) + + async def complete(): + async with profile.database.transaction() as connection: + await budget.complete(connection) + + for readback in (guard, budget.begin, complete): + with pytest.raises(TopicMemoryGenerationError) as failure: + await readback() + diagnostics = classify_processing_error(failure.value) + assert diagnostics is not None + assert diagnostics.reason is original.reason + assert diagnostics.failure_location == original.failure_location + assert diagnostics.estimated_input_tokens is None + assert diagnostics.effective_budget is None + # A new oversized proposal must not reinterpret the existing rejection. + with pytest.raises(TopicMemoryGenerationError) as repeated: + await budget.reserve(requests=1, tokens=MAX_TOPIC_MEMORY_WORK_TOKENS) + diagnostics = classify_processing_error(repeated.value) + assert diagnostics is not None + assert diagnostics.estimated_input_tokens is None + assert diagnostics.effective_budget is None + finally: + await manager.__aexit__(None, None, None) + + asyncio.run(scenario()) diff --git a/tests/builtin/test_processing_diagnostics.py b/tests/builtin/test_processing_diagnostics.py index 11d1bf593a..542aedf349 100644 --- a/tests/builtin/test_processing_diagnostics.py +++ b/tests/builtin/test_processing_diagnostics.py @@ -33,6 +33,12 @@ AtomicMemoryGenerationPipeline, ) from powercontext.builtin.artifacts.memory.extraction import MemoryExtractionCandidate, _selected_evidence +from powercontext.builtin.artifacts.topic_memory.errors import ( + TopicMemoryCapabilityError, + TopicMemoryProjectionError, + TopicMemoryStorageInvariantError, +) +from powercontext.builtin.artifacts.topic_memory.generation import TopicMemoryGenerationError from powercontext.builtin.inference.errors import ( InferenceTimeoutError, InferenceUnavailableError, @@ -53,6 +59,7 @@ ProcessingFailureReason, ProcessingStage, attach_diagnostics, + classify_block_code, classify_processing_error, safe_classify_processing_error, ) @@ -408,3 +415,122 @@ def test_console_filter_renders_the_new_processing_fields() -> None: assert 'processing_stage="generation"' in processing_context assert 'failure_reason="rate_limit"' in processing_context assert 'cause_exception_type="ModelHTTPError"' in processing_context + + +@pytest.mark.parametrize( + ("code", "stage", "reason"), + [ + ("embedding_unavailable", ProcessingStage.EMBEDDING, ProcessingFailureReason.CONFIGURATION), + ("input_budget_exceeded", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.CONTEXT_OVERFLOW), + ( + "reduction_input_budget_exceeded", + ProcessingStage.BUSINESS_VALIDATION, + ProcessingFailureReason.CONTEXT_OVERFLOW, + ), + ("window_provider_budget_exceeded", ProcessingStage.GENERATION, ProcessingFailureReason.USAGE_LIMIT), + ("window_attempt_limit", ProcessingStage.GENERATION, ProcessingFailureReason.USAGE_LIMIT), + ("reduction_output_budget_exceeded", ProcessingStage.GENERATION, ProcessingFailureReason.USAGE_LIMIT), + ("invalid_plan", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("invalid_evidence", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("invalid_proposal", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("invalid_reconciliation", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("invalid_reduction", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("invalid_target", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("invalid_temporary", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("invalid_work_item", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("unsupported_evidence", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("reduction_did_not_progress", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("duplicate_target", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("identity_merge", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("proposal_limit", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("incomplete_target", ProcessingStage.PERSISTENCE, ProcessingFailureReason.STORAGE_FAILURE), + ( + "source_complexity_limit", + ProcessingStage.BUSINESS_VALIDATION, + None, + ), + ("related_history_limit", ProcessingStage.BUSINESS_VALIDATION, None), + ("source_window_changed", None, None), + ("invalid_window", None, None), + ("duplicate_operation", None, None), + ("window_attempt_superseded", None, None), + ("target_did_not_converge", None, None), + ("unaccepted_invocation", None, None), + ("invalid_invocation", None, None), + ("invalid_work_reservation", None, None), + ("invalid_stage_budget", None, ProcessingFailureReason.CONFIGURATION), + ("invalid_max_tokens", None, ProcessingFailureReason.CONFIGURATION), + ("output_budget_exceeded", None, ProcessingFailureReason.CONFIGURATION), + ], +) +def test_topic_memory_generation_errors_classify_by_code(code, stage, reason) -> None: + diagnostics = classify_processing_error(TopicMemoryGenerationError(code)) + + assert diagnostics is not None + assert diagnostics.stage is stage + assert diagnostics.reason is reason + assert diagnostics.failure_location == code + + +def test_unknown_topic_memory_code_keeps_unknown_classification() -> None: + assert classify_processing_error(TopicMemoryGenerationError("unknown_future_code")) is None + + +@pytest.mark.parametrize( + ("code", "stage", "reason"), + [ + ("content", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("chunks", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("lexical", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("vector-incomplete", ProcessingStage.BUSINESS_VALIDATION, ProcessingFailureReason.INVALID_OUTPUT), + ("fts", ProcessingStage.PERSISTENCE, ProcessingFailureReason.CONFIGURATION), + ("vector-unconfigured", ProcessingStage.PERSISTENCE, ProcessingFailureReason.CONFIGURATION), + ("embedding-profile", ProcessingStage.PERSISTENCE, ProcessingFailureReason.CONFIGURATION), + ("embedding-values", ProcessingStage.EMBEDDING, ProcessingFailureReason.INVALID_OUTPUT), + ], +) +def test_topic_memory_projection_errors_classify_by_code(code, stage, reason) -> None: + diagnostics = classify_processing_error(TopicMemoryProjectionError(code)) + + assert diagnostics is not None + assert diagnostics.stage is stage + assert diagnostics.reason is reason + assert diagnostics.failure_location == code + + +def test_unknown_topic_memory_projection_code_keeps_reason_unknown() -> None: + diagnostics = classify_processing_error(TopicMemoryProjectionError("future-code")) + + assert diagnostics is not None + assert diagnostics.stage is ProcessingStage.PERSISTENCE + assert diagnostics.reason is None + assert diagnostics.failure_location == "future-code" + + +def test_topic_memory_storage_invariant_errors_classify_as_persistence() -> None: + diagnostics = classify_processing_error(TopicMemoryStorageInvariantError("missing-publication", ("scope",))) + + assert diagnostics is not None + assert diagnostics.stage is ProcessingStage.PERSISTENCE + assert diagnostics.reason is ProcessingFailureReason.STORAGE_FAILURE + assert diagnostics.failure_location == "missing-publication" + + +def test_topic_memory_capability_errors_classify_as_configuration() -> None: + diagnostics = classify_processing_error(TopicMemoryCapabilityError("vector")) + + assert diagnostics is not None + assert diagnostics.stage is ProcessingStage.PERSISTENCE + assert diagnostics.reason is ProcessingFailureReason.CONFIGURATION + assert diagnostics.failure_location == "vector" + + +def test_durable_blocks_classify_only_for_topic_memory() -> None: + diagnostics = classify_block_code("topic_memory", "window_attempt_limit") + + assert diagnostics is not None + assert diagnostics.stage is ProcessingStage.GENERATION + assert diagnostics.reason is ProcessingFailureReason.USAGE_LIMIT + assert diagnostics.failure_location == "window_attempt_limit" + assert classify_block_code("memory", "window_attempt_limit") is None + assert classify_block_code("topic_memory", "") is None diff --git a/tests/e2e/test_kimi_code_host.py b/tests/e2e/test_kimi_code_host.py index 7f159e0cbc..4ace6475f6 100644 --- a/tests/e2e/test_kimi_code_host.py +++ b/tests/e2e/test_kimi_code_host.py @@ -256,7 +256,8 @@ def serving(app, *, startup_diagnostic: Path | None = None): failure = None try: started = time.monotonic() - deadline = started + 15 + # Startup includes loading the inference client's CA bundle on the Windows runner. + deadline = started + 60 while not server.started and thread.is_alive() and time.monotonic() < deadline: time.sleep(0.05) if not server.started: diff --git a/tests/e2e/test_worker_logging.py b/tests/e2e/test_worker_logging.py index 06680e72b7..b4e96f5ce5 100644 --- a/tests/e2e/test_worker_logging.py +++ b/tests/e2e/test_worker_logging.py @@ -383,9 +383,20 @@ def _logging_worker(assignment: ArtifactProcessingWorkAssignment) -> ArtifactPro if assignment.scope_id == "denied": raise AccessDeniedError() if assignment.scope_id == "blocked": - raise ArtifactProcessingBlockedError( + blocked = ArtifactProcessingBlockedError( ArtifactProcessingBlock("frontier", "topic_memory", "window_attempt_limit", (("attempts", 3),)) ) + attach_diagnostics( + blocked, + ProcessingDiagnostics( + stage=ProcessingStage.GENERATION, + reason=ProcessingFailureReason.USAGE_LIMIT, + estimated_input_tokens=123, + effective_budget=100, + failure_location="window_attempt_limit", + ), + ) + raise blocked return ArtifactProcessingWorkerCompletion() @@ -405,7 +416,7 @@ def _logging_worker(assignment: ArtifactProcessingWorkAssignment) -> ArtifactPro ], ) def test_supervisor_traces_preserve_spawned_worker_failure_semantics( - capfd, tmp_path, scope_id, category, outcome + capfd, caplog, tmp_path, scope_id, category, outcome ) -> None: exporter = InMemorySpanExporter() provider = TracerProvider(shutdown_on_exit=False) @@ -431,12 +442,16 @@ async def run() -> None: bindings=(binding,), lease_mode="single-process", tracing=tracing, - ): + ) as supervisor: async with asyncio.timeout(30): while not any( # noqa: ASYNC110 - bounded polling of exported observations span.name == "artifact_processing.worker" for span in exporter.get_finished_spans() ): await asyncio.sleep(0.01) + if outcome == "blocked": + # The worker span can end before the supervisor handles the result. + while not supervisor.family_status["memory"]["blocked"]: # noqa: ASYNC110 - bounded polling + await asyncio.sleep(0.01) async with profile.database.transaction() as connection: intent = await intents.load(connection, scope_id, binding_name) assert intent is not None and intent.requested_generation > intent.handled_generation @@ -457,6 +472,13 @@ async def run() -> None: assert _PRIVATE not in captured.out + captured.err + repr([dict(span.attributes or {}) for span in spans]) terminal = [record for record in _json_records(captured.out) if record.get("duration_ms") is not None] assert terminal and terminal[-1]["error_category"] == category + if outcome == "blocked": + blocked = next(r for r in caplog.records if getattr(r, "event", None) == "artifact_processing.blocked") + worker_span = next(span for span in spans if span.name == "artifact_processing.worker") + assert worker_span.context is not None + assert blocked.trace_id == f"{worker_span.context.trace_id:032x}" + assert blocked.estimated_input_tokens == 123 + assert blocked.effective_budget == 100 finally: tracing.shutdown() @@ -631,6 +653,12 @@ async def run() -> None: assert failure.block == ArtifactProcessingBlock( "frontier", "topic_memory", "window_attempt_limit", (("attempts", 3),) ) + assert failure.diagnostics is not None + assert failure.diagnostics.stage is ProcessingStage.GENERATION + assert failure.diagnostics.reason is ProcessingFailureReason.USAGE_LIMIT + assert failure.diagnostics.estimated_input_tokens == 123 + assert failure.diagnostics.effective_budget == 100 + assert failure.diagnostics.failure_location == "window_attempt_limit" finally: await handle.terminate() @@ -644,6 +672,11 @@ async def run() -> None: assert terminal["level"] == "WARNING" and terminal["outcome"] == "blocked" assert terminal["error_category"] == "blocked" and terminal["error_code"] == "window_attempt_limit" assert terminal["stage"] == "topic_memory" and terminal["worker_id"] == "blocked-attempt" + assert terminal["processing_stage"] == "generation" + assert terminal["failure_reason"] == "usage_limit" + assert terminal["estimated_input_tokens"] == 123 + assert terminal["effective_budget"] == 100 + assert terminal["failure_location"] == "window_attempt_limit" else: terminal_line = captured.out.splitlines()[-1] assert " WARNING " in terminal_line @@ -654,6 +687,11 @@ async def run() -> None: 'error_code="window_attempt_limit"', 'stage="topic_memory"', 'worker_id="blocked-attempt"', + 'processing_stage="generation"', + 'failure_reason="usage_limit"', + "estimated_input_tokens=123", + "effective_budget=100", + 'failure_location="window_attempt_limit"', ): assert field in terminal_line diff --git a/tests/test_managed_resource_producer.py b/tests/test_managed_resource_producer.py index 43f8b25c21..782e973f87 100644 --- a/tests/test_managed_resource_producer.py +++ b/tests/test_managed_resource_producer.py @@ -541,7 +541,9 @@ def test_native_candidate_is_consumed_and_runs_independent_ops(native_candidates ], cwd=_ROOT, check=True, - timeout=300, + # Leave room for the launcher and Ops phase deadlines, archive I/O, + # and writing failure evidence before the outer process is stopped. + timeout=1200, ) diff --git a/tests/test_upgrade_release_gate.py b/tests/test_upgrade_release_gate.py index e0296dec1a..7e25bbc80a 100644 --- a/tests/test_upgrade_release_gate.py +++ b/tests/test_upgrade_release_gate.py @@ -960,7 +960,8 @@ def _process_identity(pid: int) -> str | None: # PID reuse during the parallel suite must not look like a surviving descendant. try: stat = Path(f"/proc/{pid}/stat").read_text() - except FileNotFoundError: + except (FileNotFoundError, ProcessLookupError): + # Linux can remove the task after opening its proc entry but before reading it. return None fields = stat[stat.rfind(")") + 2 :].split() return fields[19] if len(fields) > 19 else None