Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions .agents/flow/issues/bugfix-bad-case-sync-type-title.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ priority: P2
status: ready
scope:
- .agents/flow/issues/bugfix-bad-case-sync-type-title*
- .agents/flow/issues/bugfix-edit-insert-anchor-multiline*
- .agents/notes/**
- apps/api/app/service/acquisition/bad_case_catalog_sync.py
- apps/api/app/third_party_api/bad_case_query/models.py
- apps/api/tests/m6-16-bad-case-catalog-sync/**
- plans/fullstack-design/12-bad-case-catalog-sync.md
- plans/2026-11-25-pr606-review.md
adr: []
github:
number: 600
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的
# git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录:
# pnpm run record:i18n -- .agents/flow/issues/bugfix-bad-case-sync-type-title.md
bugfix-bad-case-sync-type-title.md: 38cfcf071b5768dd36077c8bcaacedc116e67da8
bugfix-bad-case-sync-type-title.en.md: 16bb03abc94d8d9874bd4fe5d8ce41f40eb2b6c3
bugfix-bad-case-sync-type-title.md: c0223d72aceb766d65b4549cb8ee5d0a5c3c0737
bugfix-bad-case-sync-type-title.en.md: eb2a824ac3667be9b52e8ff848ab4a9e4c4db4a7
2 changes: 2 additions & 0 deletions .agents/flow/issues/bugfix-bad-case-sync-type-title.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ priority: P2
status: ready
scope:
- .agents/flow/issues/bugfix-bad-case-sync-type-title*
- .agents/flow/issues/bugfix-edit-insert-anchor-multiline*
- .agents/notes/**
- apps/api/app/service/acquisition/bad_case_catalog_sync.py
- apps/api/app/third_party_api/bad_case_query/models.py
- apps/api/tests/m6-16-bad-case-catalog-sync/**
- plans/fullstack-design/12-bad-case-catalog-sync.md
- plans/2026-11-25-pr606-review.md
adr: []
github:
number: 600
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ milestone: bugfix
depends:
- bugfix-46
priority: P2
status: in-progress
status: done
scope:
- apps/api/app/third_party_api/ai_agent/edits.py
- apps/api/app/service/evolution/patch_source.py
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的
# git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录:
# pnpm run record:i18n -- .agents/flow/issues/bugfix-edit-insert-anchor-multiline.md
bugfix-edit-insert-anchor-multiline.md: 00d6a2d2a430e344007c21ed74e3e6260e52378d
bugfix-edit-insert-anchor-multiline.en.md: c20a7de8526598c5dad2b878e633f02565b2f66d
bugfix-edit-insert-anchor-multiline.md: f600bee4f272ea9a95b74388146e38d96df7ead7
bugfix-edit-insert-anchor-multiline.en.md: 7b38185aeb7253e731ad911bfb750389169d3a8f
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ milestone: bugfix
depends:
- bugfix-46
priority: P2
status: in-progress
status: done
scope:
- apps/api/app/third_party_api/ai_agent/edits.py
- apps/api/app/service/evolution/patch_source.py
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Agent Note: Type and title normalization for upstream catalog sync

Status: implemented

English | [中文](2026-11-25-bad-case-sync-type-title-normalization.md)

## Problem

The catalog sync feeds each upstream bad_cases page into strict `BadCasePage` validation, and `BadCaseItem` treated upstream data as already satisfying the local `bad_cases` constraints: `bad_case_type` had to be a non-empty string of 1–16 characters and `title` was capped at 255. Real upstream data already contains items with a null `bad_case_type` and overlong titles, and page validation is all-or-nothing — one such item fails the whole page's `model_validate`, which surfaces as `BAD_CASE_QUERY_INVALID_RESPONSE`; the page rolls back, the cursor does not move, and the next scheduled tick retries the same page from the same cursor, so one dirty row becomes a poison pill that blocks every later bad case. m6-17 already degraded empty `object_name` / `object_type` values ([2026-10-30-bad-case-catalog-sync.en.md](../feature/2026-10-30-bad-case-catalog-sync.en.md)) but explicitly listed these two fields as non-goals, and a 200-character rule did not exist anywhere in the code; the measured cutoff was the 255-column width.

## Decision

Keep m6-17's "relax the transport, normalize at write" layering and change only two places. Transport, `BadCaseItem`: `bad_case_type` becomes optional (None or missing is accepted, non-null values still validate against 1–16 characters) and `title` drops the 255 cap while keeping non-empty; `extra="forbid"`, the timezone validation, and `BadCasePage`'s sort, uniqueness, and limit/total checks are untouched. Write mapping, `_row`: `bad_case_type=item.bad_case_type or "self"` and `title=item.title[:200]`; whenever either rule fires, one structured info record is logged with extras carrying `badCaseId` and the hit field names, and no status column is added. Table shape and column width, read paths, page transactions, and cursor semantics stay unchanged.

## Alternatives considered

- **Default and truncate inside the transport model**: rewriting values at parse time would make the model stop mirroring the upstream shape, upstream drift would become invisible at that layer, and any future consumer would receive rewritten data; normalization is a local write policy, not part of the upstream contract. Rejected.
- **Keep the strict model and wait for upstream to fix its data**: the defect exists precisely because upstream and local contracts drifted while the sync layer had nowhere to stand; without upstream cooperation the sync stalls forever, every retry consumes budget, and the popover shows only a stable error code with no pointer to the case or field. Rejected.
- **Skip bad rows and commit the rest**: that breaks page atomicity and cursor semantics and creates silent data holes; the issue lists it as a non-goal. Rejected.
- **Truncate titles at 255 (following the column width)**: titles of 205–255 characters would land verbatim, contradicting the required 200-character rule; 200 is the established short-title budget on the attribution side (`attribution.py` and `attribution_executor.py` both take `[:200]`), and read paths consume 200. Rejected.
- **Tighten the `title` column to 200 with a migration**: after truncation the write cap is 200 and can never reach the 255 column width; changing the width would drag in existing rows and a migration, and this issue changes no tables. Rejected.

## Consequences

- Pages with null/missing types or overlong titles parse and land again, and the sync keeps advancing; explicit `self` / `discovery` values and titles up to 200 characters stay verbatim.
- Title truncation is lossy: anything beyond 200 characters is dropped forever, and since the cursor only moves forward old ids are never re-pulled, so truncated content cannot be recovered; acceptable because `title` is by design a short headline that read paths and the attribution budget consume at 200.
- The column width stays 255: the 200 write cap leaves headroom, and this fix adds no migration and touches no existing rows.
- The only observability for normalization is the info log (`badCaseId` plus the hit field names), used to tell upstream drift from local logic errors; truncated values are never written back upstream.
- Illegal shapes beyond the two fields (missing required fields, an empty `title`, a type longer than 16 characters, naive timestamps, and so on) still fail the whole page with rollback, and the existing semantics of a bad page never advancing the cursor are unchanged.
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# 双语配对一致性记录(docs/i18n/README.md):两侧在最后一次确认一致状态下的
# git blob hash。两种语言同等权威;编辑任一侧后带上另一侧,然后重录:
# pnpm run record:i18n -- .agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.md
2026-11-25-bad-case-sync-type-title-normalization.md: dd6ab5c792a6cff0065f706e42769313e13c67df
2026-11-25-bad-case-sync-type-title-normalization.en.md: f35c62ce4049e3323db12d9eeabc591aaca4ed13
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Agent Note: 上游目录同步的 bad case 类型与标题归一化

Status: implemented

[English](2026-11-25-bad-case-sync-type-title-normalization.en.md) | 中文

## Problem

目录同步把上游 bad_cases 按页塞进 `BadCasePage` 严格校验,而 `BadCaseItem` 把上游数据当成已满足本地 `bad_cases` 约束的成品:`bad_case_type` 必须是 1–16 字符的非空字符串,`title` 上限 255。上游真实数据里已经出现 `bad_case_type` 为 null 与 `title` 超长的条目,页级校验又是全有或全无——页内只要有一条这样的 item,整页 `model_validate` 即失败并被收敛为 `BAD_CASE_QUERY_INVALID_RESPONSE`,该页回滚、游标不动,下一轮定时任务从同一游标重试同一页,单条脏数据成为 poison pill,后续所有 bad case 都同步不进来。m6-17 已为 `object_name` / `object_type` 做空值降级([2026-10-30-bad-case-catalog-sync.md](../feature/2026-10-30-bad-case-catalog-sync.md)),但把这两个字段明确列为非目标;200 口径当时在代码里并不存在,实测的截断阈值就是列宽 255。

## Decision

沿用 m6-17 的「传输放宽、写入归一」分层,只改两处。传输层 `BadCaseItem`:`bad_case_type` 改为可空(None 或缺失放行,非空仍校验 1–16 字符),`title` 去掉 255 上限、保留非空;`extra="forbid"`、时间戳时区校验与 `BadCasePage` 的排序、唯一、limit/total 校验全部不动。写入层 `_row`:`bad_case_type=item.bad_case_type or "self"`,`title=item.title[:200]`;命中任一条时记录一次结构化 info 日志,extra 携带 `badCaseId` 与命中的字段名,不新增状态列。表结构与列宽、读路径、页级事务与游标语义都不变。

## Alternatives considered

- **把默认值与截断做进传输模型**:解析层改写值会让模型不再忠实表达上游形状,上游漂移在这一层就不可见,未来的其他消费方拿到的是被改写过的数据;归一化是本地写入策略,不属于上游契约。拒绝。
- **维持严格模型,等上游修复数据**:缺陷的成因正是上游与本地契约错位而同步层无处容身;上游不配合时同步永久停滞,每轮重试消耗预算,浮层只剩一个稳定错误码,定位不到具体 case 或字段。拒绝。
- **跳过坏行、其余照常落库**:破坏页级原子性与游标推进语义,制造静默数据空洞;本 issue 明确列为非目标。拒绝。
- **title 按 255 截断(跟随列宽)**:205–255 字符的标题会原样落库,与需求的 200 口径不符;200 是归因侧短标题预算的既有口径(`attribution.py` 与 `attribution_executor.py` 都取 `[:200]`),读路径按 200 消费。拒绝。
- **把 `title` 列宽收紧到 200 并加迁移**:截断后写入上限 200,永远触碰不到 255 列宽;改列宽牵动存量行与迁移,本 issue 不做任何表变更。拒绝。

## Consequences

- null/缺失 type 与超长标题的页都能解析并落库,同步继续推进;显式 `self` / `discovery` 与不超过 200 字符的标题保持原样。
- 标题截断是有损的:超出 200 的尾部被永久丢弃,游标只增不减、旧 id 不会重推,被截内容无法回捞;可接受是因为 `title` 的设计语义就是短标题,读路径展示与归因预算都按 200 口径消费。
- 列宽保持 255:写入上限 200 留有余量,本次修复不引入迁移、不触碰存量行。
- 归一化的可观测性只有 info 日志(`badCaseId` + 字段名),用于区分上游漂移与本地逻辑错误;截断值不回写上游。
- 两个字段之外的非法形状(缺必填字段、空 `title`、type 超 16 字符、naive 时间戳等)仍整页拒绝并回滚,坏页不推进游标的既有语义不变。
19 changes: 16 additions & 3 deletions apps/api/app/service/acquisition/bad_case_catalog_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,17 +59,30 @@ def _object_name(item: BadCaseItem) -> str:


def _row(item: BadCaseItem, fallback: datetime) -> CatalogCaseRow:
"""Map one upstream item to local column names, defaulting timestamps."""
"""Map one upstream item to local columns, normalizing type and title."""
normalized = [
field
for field, drifted in (
("bad_case_type", item.bad_case_type is None),
("title", len(item.title) > 200),
)
if drifted
]
if normalized:
logger.info(
"upstream bad case normalized",
extra={"badCaseId": item.bad_case_id, "fields": ",".join(normalized)},
)
return CatalogCaseRow(
bad_case_id=item.bad_case_id,
bad_case_session_id=item.bad_case_session_id,
bad_case_type=item.bad_case_type,
bad_case_type=item.bad_case_type or "self",
object_name=_object_name(item),
object_type=item.object_type or "skill",
object_version=item.object_version,
bad_case_agent_id=item.bad_case_agent_id,
trigger_line=item.trigger_line,
title=item.title,
title=item.title[:200],
description=item.description,
meta_data=item.meta_data,
source=item.source,
Expand Down
6 changes: 3 additions & 3 deletions apps/api/app/third_party_api/bad_case_query/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,19 @@


class BadCaseItem(BaseModel):
"""One upstream bad case shaped like the local bad_cases columns."""
"""One upstream bad case; null type and overlong titles stay for write normalization."""

model_config = ConfigDict(extra="forbid", populate_by_name=True)

bad_case_id: int = Field(ge=0)
bad_case_session_id: str = Field(min_length=1, max_length=36)
bad_case_type: str = Field(min_length=1, max_length=16)
bad_case_type: str | None = Field(default=None, min_length=1, max_length=16)
object_name: str | None = Field(default=None, max_length=128)
object_type: str | None = Field(default=None, max_length=16)
object_version: str | None = Field(default=None, max_length=64)
bad_case_agent_id: str | None = Field(default=None, max_length=64)
trigger_line: int | None = Field(default=None, ge=0)
title: str = Field(alias="bad_case_title", min_length=1, max_length=255)
title: str = Field(alias="bad_case_title", min_length=1)
description: str = Field(alias="bad_case_description")
meta_data: Any | None = None
source: str | None = Field(default=None, max_length=64)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,95 @@ def handler(request: httpx.Request) -> httpx.Response:
assert page.items[1].object_type == ""


@pytest.mark.asyncio
@pytest.mark.parametrize("mode", ["null", "missing"])
async def test_fetch_page_allows_null_bad_case_type(mode: str) -> None:
"""A null or absent bad_case_type parses; defaulting is the write layer's job."""
item = _item(1)
if mode == "null":
item["bad_case_type"] = None
else:
del item["bad_case_type"]

def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json=_page([item], total=1))

source = HttpBadCaseCatalogSource(
httpx.AsyncClient(
transport=httpx.MockTransport(handler),
base_url="http://query.test",
),
max_retries=0,
)
try:
page = await source.fetch_page(after_id=0, offset=0, limit=2)
finally:
await source.close()

assert page.items[0].bad_case_type is None
assert page.items[0].bad_case_id == 1
assert page.items[0].title == "case title"
assert page.items[0].created_at is not None


@pytest.mark.asyncio
async def test_fetch_page_allows_overlong_title() -> None:
"""The transport keeps a 300-character title verbatim; truncation happens at write."""
long_title = "t" * 300

def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json=_page([_item(1, title=long_title)], total=1))

source = HttpBadCaseCatalogSource(
httpx.AsyncClient(
transport=httpx.MockTransport(handler),
base_url="http://query.test",
),
max_retries=0,
)
try:
page = await source.fetch_page(after_id=0, offset=0, limit=2)
finally:
await source.close()

assert page.items[0].title == long_title
assert len(page.items[0].title) == 300


@pytest.mark.asyncio
@pytest.mark.parametrize(
"overrides",
[
{"bad_case_session_id": ""},
{"bad_case_session_id": "s" * 37},
{"bad_case_type": "x" * 17},
{"bad_case_type": ""},
{"bad_case_title": ""},
],
)
async def test_fetch_page_still_rejects_illegal_shapes(overrides: dict[str, Any]) -> None:
"""Only the null-type and overlong-title shapes were relaxed; the rest stays strict."""
payload = _page([_item(1, **overrides)], total=1)

def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json=payload)

source = HttpBadCaseCatalogSource(
httpx.AsyncClient(
transport=httpx.MockTransport(handler),
base_url="http://query.test",
),
max_retries=0,
)
try:
with pytest.raises(AppError) as failure:
await source.fetch_page(after_id=0, offset=0, limit=2)
finally:
await source.close()

assert failure.value.code is ErrorCode.BAD_CASE_QUERY_INVALID_RESPONSE


@pytest.mark.asyncio
@pytest.mark.parametrize(
"payload",
Expand Down
Loading
Loading