Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 20 additions & 9 deletions docs/en/development/processing-failures.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,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 |
Expand Down Expand Up @@ -47,14 +47,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 |
|---|---|---|---|
Expand All @@ -68,16 +68,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 rules are business validation; publication and 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.
Expand Down
27 changes: 19 additions & 8 deletions docs/zh/development/processing-failures.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,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 返回的请求标识 | 有界字符串 |
Expand Down Expand Up @@ -41,14 +41,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 | 状态 | 说明 |
|---|---|---|---|
Expand All @@ -62,14 +62,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 分类并补全矩阵。

Expand Down
42 changes: 38 additions & 4 deletions src/powercontext/builtin/artifacts/topic_memory/generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down Expand Up @@ -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)


Expand Down Expand Up @@ -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__ = [
Expand Down
63 changes: 57 additions & 6 deletions src/powercontext/builtin/persistence/topic_memory_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@
TOPIC_MEMORY_WORK_BLOCKS_TABLE,
TOPIC_MEMORY_WORK_BUDGETS_TABLE,
)
from powercontext.builtin.processing_diagnostics import (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] 改了 builtin/persistence/ 但没有同步 release/upgrade-support.json,make check 在当前 head 直接判红,全套 CI 因此被跳过

本文件位于 scripts/upgrade_release_gate.py::MANAGED_INPUTS 的 src/powercontext/builtin/persistence 之下,managed_digest() 会把该目录所有 .py/.sql/.json 的内容哈希进 schema_review.persistence_sha256;本 PR 修改了本文件,摘要必然变化,但 release/upgrade-support.json 未随之更新。

证据(head 7e6f6803,Main run 41430808818,CI preflight job 125228607409):

  1. make check 的 Run checks 步骤失败,日志原文:
    Upgrade release gate failed: Persistence changed (file set or content; CRLF/LF normalized): update the compatibility review
    make: *** [Makefile:257: upgrade-policy-check] Error 1(job 退出码 2)。
  2. 因为 CI preflight 红,master.yml 中依赖 needs.tests.result / needs.quality.outputs.suites 的 suite job 全部 skipped:本 head 的 check run 里只有 license/cla 通过,tests (*) 与 windows-unit-portability 一个都没执行。本 PR 新增的 5 个用例(含 tests/builtin/runtime/test_processing_scheduler.py::test_worker_blocked_log_carries_diagnostics、tests/e2e/test_worker_logging.py 的 worker→supervisor 字段传播断言)目前没有任何 CI 执行证据。

影响:这是仓库强制门禁(make check 内含 upgrade-policy-check)的红,PR 无法合入;同时本 PR 的核心声明——诊断字段能从子 Worker 传到 supervisor 日志——完全缺少 CI 侧证据。

建议:

  • 在本 head 上复算并写回 release/upgrade-support.json 的 schema_review:persistence_sha256 取 scripts/upgrade_release_gate.py::managed_digest(Path(".")) 的值(不要沿用 master 上的 404bcc68…,本 head 的 base 已前进)。
  • rationale 增补一句说明本次仅新增诊断字段与日志投影,未改表结构、迁移资源、revision 标识与行编码;这样复核人能从 rationale 直接判断为何是 review trigger 而不是布局变更。
  • 该文件与 feat(runtime): durable Work Ledger rebased onto current master #2270 的迁移链、1.5.0 发布对账有交叉,写入时以本 head 的实际摘要为准,避免与其他 PR 的摘要互相覆盖。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

补充一条排除「base 摘要滞后」的对照证据,避免把基线问题算到本 PR 头上(R-PC51 的反向场景):

  • compare/1c52626d...7e6f6803 的 15 个文件里,落在 MANAGED_INPUTS(src/powercontext/builtin/persistence、builtin/code、server/identity.py、server/authz、limits.py)内的只有 src/powercontext/builtin/persistence/topic_memory_budget.py 一个,所以摘要变化确实只由本 PR 引起。
  • 同一 base 1c52626d 的 fix(dsh): exclude current runtime context from recall queries #2386(head afc66e09,3 个文件均在 integrations 下、未碰 MANAGED_INPUTS)其 CI preflight 在 2026-11-02T08:27:34Z 为 success ⇒ base 树上的 managed_digest 与 release/upgrade-support.json 的声明值一致,base 不滞后。

因此这里需要的是在本 head 上复算并写回 schema_review.persistence_sha256,而不是 rebase。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

补充本 head 的修复核对:摘要已同步,上一轮的 P1 前提不再成立。

在 exact head ec56a47f 的隔离副本(sparse clone,工作区干净)上,按 scripts/upgrade_release_gate.py::managed_digest 的算法独立复算(MANAGED_INPUTS 五个路径下 237 个 .py/.sql/.json,逐个 sha256 后 → 归一化,再对 json.dumps(files, sort_keys=True) 求摘要):

recomputed 4f078e0d46b6164d008299092a5128bab7dd9419e8dcb7d93eef4c6d9e73abaa
declared   4f078e0d46b6164d008299092a5128bab7dd9419e8dcb7d93eef4c6d9e73abaa   → MATCH

所以 make upgrade-policy-check 在本 head 上不再因本文件变红,本轮不重复该 P1。

同 head 的另外两点(仅供对账,不另开线程):

  • 反向去重也成立:本 PR 对 MANAGED_INPUTS 的改动确实只有 builtin/persistence/topic_memory_budget.py 与新增的 builtin/processing_diagnostics.py(后者不在 MANAGED_INPUTS 内),摘要变化全部由本 PR 引起,不是 base 滞后。
  • 本地跑新增的分类用例 tests/builtin/test_processing_diagnostics.py -k "classify_by_code or unknown_topic_memory or durable_blocks or storage_invariant or capability_errors":77 passed(Python 3.12.13)。该文件里其余用例在本机 150s 内未跑完,同一文件在 master 工作区同样如此,属环境/基线耗时,不归责本 PR。

CI 侧仍有与代码无关的缺口,需注意不要把它读成「已跑过 CI」:本 head 的 CI preflight 红在 Check License Header(缺 header 的是 master 上的 gateway/crates/pc-gateway-core/src/lifecycle.rs),quality 失败导致全部 suite job skip,新增用例目前零 CI 证据。

ProcessingDiagnostics,
ProcessingFailureReason,
ProcessingStage,
attach_diagnostics,
)

# Server-owned ceilings, shared by ALL attempts and stages at the same Cursor.
MAX_TOPIC_MEMORY_WORK_ATTEMPTS = 3
Expand Down Expand Up @@ -91,13 +97,45 @@ async def load_topic_memory_work_budget(
return (await connection.execute(statement)).mappings().one_or_none()


def _topic_memory_budget_error(
reason: str, *, tokens: int | None = None, token_ceiling: bool = True
) -> 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":
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=int(row["requests"]) < MAX_TOPIC_MEMORY_WORK_REQUESTS,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Preserve the actual ceiling when reconstructing a budget failure

A rejected reservation does not persist its proposed charges, so the stored request count cannot identify which ceiling was crossed. With 510 requests and 1,000 tokens already charged, reserving 3 requests and 10 tokens correctly fails on the 512-request ceiling, but a subsequent require_topic_memory_work_available read reconstructs the error with estimated_input_tokens=1000 and effective_budget=64000000, falsely presenting a token-ceiling failure. begin and complete use the same inference. Preserve the limiting dimension in durable evidence, or omit the token-specific fields when it cannot be established; verify the original rejection and subsequent readback agree.

)


async def record_topic_memory_work_failure(
Expand Down Expand Up @@ -242,7 +280,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=row is None or int(row["requests"]) < MAX_TOPIC_MEMORY_WORK_REQUESTS,
)

async def _current(self, connection: AsyncConnection):
table = TOPIC_MEMORY_WORK_BUDGETS_TABLE
Expand All @@ -260,13 +302,14 @@ 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
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"
values = (
Expand All @@ -277,7 +320,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=tokens_after,
token_ceiling=requests_after <= MAX_TOPIC_MEMORY_WORK_REQUESTS,
)

async def fail(self, reason: str) -> None:
"""Record a rejection cause on the frontier without storing source text.
Expand Down Expand Up @@ -312,5 +359,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=int(row["requests"]) < MAX_TOPIC_MEMORY_WORK_REQUESTS,
)
await connection.execute(delete(TOPIC_MEMORY_WORK_BUDGETS_TABLE).where(*self._key()))
Loading
Loading