diff --git a/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md b/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md index 16bb03ab..eb2a824a 100644 --- a/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md +++ b/.agents/flow/issues/bugfix-bad-case-sync-type-title.en.md @@ -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 diff --git a/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml b/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml index 38e62ff5..81b0a80d 100644 --- a/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml +++ b/.agents/flow/issues/bugfix-bad-case-sync-type-title.i18n.yaml @@ -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 diff --git a/.agents/flow/issues/bugfix-bad-case-sync-type-title.md b/.agents/flow/issues/bugfix-bad-case-sync-type-title.md index 38cfcf07..c0223d72 100644 --- a/.agents/flow/issues/bugfix-bad-case-sync-type-title.md +++ b/.agents/flow/issues/bugfix-bad-case-sync-type-title.md @@ -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 diff --git a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md index c20a7de8..7b38185a 100644 --- a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md +++ b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.en.md @@ -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 diff --git a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml index 4e59ad79..ac9375a9 100644 --- a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml +++ b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.i18n.yaml @@ -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 diff --git a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md index 00d6a2d2..f600bee4 100644 --- a/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md +++ b/.agents/flow/issues/bugfix-edit-insert-anchor-multiline.md @@ -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 diff --git a/.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.en.md b/.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.en.md new file mode 100644 index 00000000..f35c62ce --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.en.md @@ -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. diff --git a/.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.i18n.yaml new file mode 100644 index 00000000..495693fb --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.md b/.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.md new file mode 100644 index 00000000..dd6ab5c7 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.md @@ -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 时间戳等)仍整页拒绝并回滚,坏页不推进游标的既有语义不变。 diff --git a/apps/api/app/service/acquisition/bad_case_catalog_sync.py b/apps/api/app/service/acquisition/bad_case_catalog_sync.py index 01bd35a6..00c8137a 100644 --- a/apps/api/app/service/acquisition/bad_case_catalog_sync.py +++ b/apps/api/app/service/acquisition/bad_case_catalog_sync.py @@ -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, diff --git a/apps/api/app/third_party_api/bad_case_query/models.py b/apps/api/app/third_party_api/bad_case_query/models.py index 3c4de2a0..7fa0a1f3 100644 --- a/apps/api/app/third_party_api/bad_case_query/models.py +++ b/apps/api/app/third_party_api/bad_case_query/models.py @@ -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) diff --git a/apps/api/tests/m6-16-bad-case-catalog-sync/test_bad_case_query_client.py b/apps/api/tests/m6-16-bad-case-catalog-sync/test_bad_case_query_client.py index 58465ca4..dbee2536 100644 --- a/apps/api/tests/m6-16-bad-case-catalog-sync/test_bad_case_query_client.py +++ b/apps/api/tests/m6-16-bad-case-catalog-sync/test_bad_case_query_client.py @@ -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", diff --git a/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py b/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py index 50330636..2e2ca3af 100644 --- a/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py +++ b/apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py @@ -2,9 +2,11 @@ from __future__ import annotations -from collections.abc import AsyncIterator +import logging +from collections.abc import AsyncIterator, Mapping from datetime import datetime from pathlib import Path +from typing import Any import pytest import pytest_asyncio @@ -62,6 +64,7 @@ def _item( case_id: int, *, title: str | None = None, + bad_case_type: str | None = "self", object_name: str | None = "deep-research", object_type: str | None = "skill", source: str | None = "test", @@ -69,7 +72,7 @@ def _item( return BadCaseItem( bad_case_id=case_id, bad_case_session_id=f"session-{case_id}", - bad_case_type="self", + bad_case_type=bad_case_type, object_name=object_name, object_type=object_type, object_version="v1", @@ -336,6 +339,117 @@ async def test_missing_object_name_and_source_fall_back_to_unknown( assert row["object_type"] == "skill" +async def _row_by_id(database: Database, case_id: int) -> Mapping[str, Any]: + """Return the stored bad_cases row for one id.""" + async with database.session() as session: + rows = (await session.execute(select(bad_cases))).mappings().all() + return {str(row["bad_case_id"]): dict(row) for row in rows}[str(case_id)] + + +@pytest.mark.asyncio +async def test_null_bad_case_type_falls_back_to_self(database: Database) -> None: + """A null upstream type lands as self so type-scoped counts keep the row.""" + source = FakeSource([_item(1, bad_case_type=None)]) + service = _service(database, source) + + await service.run(owner="job-1") + + row = await _row_by_id(database, 1) + assert row["bad_case_type"] == "self" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("upstream_length", [200, 201, 300]) +async def test_title_is_verbatim_up_to_200_and_truncated_beyond( + database: Database, + upstream_length: int, +) -> None: + """At most the first 200 characters of an upstream title reach the column.""" + title = "t" * upstream_length + source = FakeSource([_item(1, title=title)]) + service = _service(database, source) + + await service.run(owner="job-1") + + assert (await _titles(database))["1"] == title[:200] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("explicit_type", ["self", "discovery"]) +async def test_explicit_bad_case_type_and_short_title_stay_verbatim( + database: Database, + explicit_type: str, +) -> None: + """Explicit types and short titles are never rewritten by the mapping.""" + source = FakeSource([_item(1, bad_case_type=explicit_type)]) + service = _service(database, source) + + await service.run(owner="job-1") + + row = await _row_by_id(database, 1) + assert row["bad_case_type"] == explicit_type + assert row["title"] == "case 1" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("bad_case_type", "title_length", "fields"), + [ + (None, 300, "bad_case_type,title"), + (None, 10, "bad_case_type"), + ("self", 300, "title"), + ], +) +async def test_normalization_logs_bad_case_id_and_hit_fields( + database: Database, + bad_case_type: str | None, + title_length: int, + fields: str, + caplog: pytest.LogCaptureFixture, +) -> None: + """Each normalized row logs one record naming the case and the hit fields.""" + source = FakeSource( + [_item(1, bad_case_type=bad_case_type, title="t" * title_length)], + ) + service = _service(database, source) + + with caplog.at_level( + logging.INFO, + logger="app.service.acquisition.bad_case_catalog_sync", + ): + await service.run(owner="job-1") + + records = [ + record + for record in caplog.records + if record.name == "app.service.acquisition.bad_case_catalog_sync" + ] + assert [getattr(record, "badCaseId", None) for record in records] == [1] + assert [getattr(record, "fields", None) for record in records] == [fields] + + +@pytest.mark.asyncio +async def test_verbatim_rows_emit_no_normalization_log( + database: Database, + caplog: pytest.LogCaptureFixture, +) -> None: + """A row that needs no normalization emits no normalization record.""" + source = FakeSource([_item(1)]) + service = _service(database, source) + + with caplog.at_level( + logging.INFO, + logger="app.service.acquisition.bad_case_catalog_sync", + ): + await service.run(owner="job-1") + + assert not [ + record + for record in caplog.records + if record.name == "app.service.acquisition.bad_case_catalog_sync" + ] + + @pytest.mark.asyncio async def test_analysis_rows_survive_upsert(database: Database) -> None: """Updating a case never touches its attribution row.""" diff --git a/plans/2026-11-25-pr606-review.md b/plans/2026-11-25-pr606-review.md new file mode 100644 index 00000000..ac0adaab --- /dev/null +++ b/plans/2026-11-25-pr606-review.md @@ -0,0 +1,412 @@ +# PR #606 检视记录:归一化上游 bad case 类型与标题 + +- 检视对象:[PR #606](https://github.com/Shadow-Azure/harness-evolution/pull/606)(`agent/develop-issue-600-bad-case-sync-type-title` → `main`,head `bd348fe7`,基线 `907d3446`,OPEN,+291/−9,8 文件) +- owning Note:[上游目录同步的 bad case 类型与标题归一化](../.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.md) +- 实现计划:[12 bad case 目录同步](../fullstack-design/12-bad-case-catalog-sync.md) §3.2 / §3.3 +- 关联 issue:[#600](https://github.com/Shadow-Azure/harness-evolution/issues/600)(不自动关闭;合入后按流程单独提交闭环 PR) +- 日期:2026-11-25 + +> 本文按 `pr-review` skill 的体例产出;检视文档落 `plans/`,不进入 Agent Notes。本文只描述当前实现与检视判断,不写变更史。所有行号锚点来自本次实际 Read;第三方行为主张(pydantic 约束、MySQL 字符宽度)均已实测或给出官方文档出处。 + +## §0 变更文件树与职责 + +共 8 = 新增 A 3 + 修改 M 5 + 删除 D 0。 + +| 组 | 文件 | 状态 | 职责 | +|---|---|---|---| +| 传输层 | `apps/api/app/third_party_api/bad_case_query/models.py` | M | `BadCaseItem.bad_case_type` 放宽为可空、`title` 去掉 255 上限,其余严格校验原样 | +| 服务层 | `apps/api/app/service/acquisition/bad_case_catalog_sync.py` | M | `_row` 写入映射归一化:null type 落 `self`、title 截前 200,命中记一条结构化 info 日志 | +| 测试 | `apps/api/tests/m6-16-bad-case-catalog-sync/test_bad_case_query_client.py` | M | 新增 null/缺失 type 放行、300 字符 title 保真、4 种非法形状仍拒绝(+88 行) | +| 测试 | `apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py` | M | 新增 null→`self`、200/201/300 截断、显式值保留、归一化日志 3 形状参数化与无日志反例(+118 行) | +| 设计文档 | `plans/fullstack-design/12-bad-case-catalog-sync.md` | M | §3.2 字段映射表补 `bad_case_type` 行与 title 截断规则,§3.3 补「仅有的两处放宽」条款 | +| 决策记录 | `.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.{md,en.md,i18n.yaml}` | A×3 | 四段骨架 Note:传输放宽 + 写入归一的分层理由、截断的有损取舍、列宽保持 255 的理由 | + +存储层(`db/crud/bad_case_catalog_sync.py`)、读路径(`db/crud/overview.py`)、表结构(`db/models/domain.py`)、调度(`bad_case_catalog_sync_coordinator.py`)、前端与契约产物:本 PR 零变更;本文走查涉及它们时只读不评。 + +## §1 一页速览 + +一句话:上游 bad case 真实数据里出现了「`bad_case_type` 为 null」和「`title` 超过 255 字符」的条目,旧传输模型一票否决整页、游标卡死、同步永久停摆;本 PR 沿用 m6-17 的「传输放宽、写入归一」分层,让传输模型接受这两种真实形状,由写入映射统一落库——null/缺失 type 落 `self`、超长 title 截前 200 字符,命中归一化时记一条含 `badCaseId` 与字段名的 info 日志,不改表结构、不改读路径、不改游标语义。 + +一个比喻:传输模型原来是入库门卫,手里攥着本地仓库的规格书,上游每页货物必须逐件符合规格才放行,一件不合规格整批退回——而上游偏偏会送来「没贴类型标签」和「标签过长」的货,整批退回让补货线彻底停摆。本 PR 把门卫的差事一分为二:门卫只负责「看清来货长相」(接受 null 与超长标签),怎么入库由标签员(`_row` 写入映射)决定——补一张 `self` 标签、把超长标题剪到 200 字符,并且登记一笔「这批有 N 件被加工过」的流水(info 日志)。门卫自己不动手改货,其他规格(缺必填、超长 type、空标题)仍然整批退回。 + +| 交付块 | 用户可见结果 | +|---|---| +| 传输放宽 | `bad_case_type` 为 null 或缺失的页解析成功;300 字符 title 传输层保真;`extra="forbid"`、时间戳时区、页级排序/唯一/limit/total 校验全部不动 | +| 写入归一 | null/缺失 type 落库 `self`;title 超过 200 截前 200,200 以内原样;显式 `self` / `discovery` 与短标题不被改写 | +| 可观测性 | 归一化命中才记一条 `logger.info`,extra 带 `badCaseId` 与命中字段名;无命中无日志;不新增状态列 | +| 读路径统计 | 归一化后的行落进 `KNOWN_BAD_CASE_TYPES` 白名单,总览计数与列表不再静默漏行 | +| 同步恢复 | 坏页从 poison pill 变为正常页,游标继续推进,后续 bad case 恢复同步 | +| 文档与记录 | 12 章 §3.2/§3.3 与实现一致;Note 三件套记录分层理由与有损取舍 | + +验证基线(检视侧实测): + +| 命令 / 手段 | 结果 | +|---|---| +| `gh pr view 606 --json statusCheckRollup` | 12 checks 全 SUCCESS(web-static / api-static / unit-tests-web / unit-tests-api / db-sqlite / e2e / build-lane / docs-flow / mysql / flow-online / deploy-contract / ci-ok) | +| `pnpm test:api -- tests/m6-16-bad-case-catalog-sync`(本机 Windows 复跑) | 67 passed(179.01s),与 PR 声明一致 | +| pydantic 探针(`apps/api/.venv`,pydantic 2.14.4 / Python 3.14.3) | null 放行、缺失放行、空串拒绝(string_too_short)、17 字符 type 拒绝(string_too_long)、300 字符 title 放行、空 title 拒绝、250 个 emoji title 放行且 `len==250` | +| MySQL 字符宽度主张 | 本机无 MySQL 实例未实测;依据 [MySQL 8.0 手册 §13.3.1](https://docs.oracle.com/cd/E17952_01/mysql-8.0-en/string-type-syntax.html)(字符列长度按字符单位解释)+ `config.py:217` 默认连接串 `charset=utf8mb4` + CI `mysql` lane 绿 | +| `pnpm lint:api` / `typecheck:api` / `test:db` / `verify:flow` / `lint:docs` / `contract:check` | 未本地复跑;以 CI 全绿与 PR 声明为据(PR body 已声明 typecheck/contract 在本地 Windows 有预先存在的平台伪红) | + +新增依赖:无(diff 未触碰 `pyproject.toml` / `package.json`),依赖类硬约束检查不适用。 + +## §2 架构导览 + +### 2.1 传输层:`third_party_api/bad_case_query/` + +`http.py` 是出站 HTTP 客户端 `HttpBadCaseCatalogSource`:`fetch_page`(http.py:34-49)用一把 `asyncio.Lock`(http.py:32)保证进程内不并发;`_request`(http.py:55-98)做有界重试——超时与传输错误退避重试(http.py:72-81),401/403 直接映射 `BAD_CASE_QUERY_UNAUTHORIZED`(http.py:83-88),429/5xx 重试(http.py:89-94),其余 ≥400 映射 `BAD_CASE_QUERY_REQUEST_FAILED`(http.py:95-96)。`_parse`(http.py:100-128)是页级校验三连:JSON 可解析(http.py:108-113)→ `BadCasePage.model_validate`(http.py:114-119)→ 回显 offset/limit 一致(http.py:120-123)+ 所有 id 严格大于请求游标(http.py:124-127);任何一环失败都收敛为 `BAD_CASE_QUERY_INVALID_RESPONSE`(http.py:149-155)。 + +`models.py` 是严格模型:`BadCaseItem`(models.py:11-37)`extra="forbid"`(models.py:14),本 PR 改了两处——`bad_case_type: str | None = Field(default=None, min_length=1, max_length=16)`(models.py:18,原为必填 `str`)、`title` 去掉 `max_length=255` 保留 `min_length=1`(models.py:24,alias `bad_case_title`)。`BadCasePage`(models.py:40-62)的页级结构校验未动:`limit ≤ 200`(models.py:47),`consistent` 校验器拒绝超页、乱序、重 id、`total < len(items)`(models.py:50-62)。`BadCaseCatalogSource` Protocol(models.py:65-78)定义只读分页源契约。 + +### 2.2 服务层:`service/acquisition/bad_case_catalog_sync.py` + +`_row`(bad_case_catalog_sync.py:61-91)是本 PR 的核心:先检测漂移(bad_case_catalog_sync.py:63-70,`bad_case_type is None` 与 `len(title) > 200` 两项),命中则记一条 `logger.info("upstream bad case normalized", extra={"badCaseId": ..., "fields": ...})`(bad_case_catalog_sync.py:71-75),再构造 `CatalogCaseRow`——`bad_case_type=item.bad_case_type or "self"`(bad_case_catalog_sync.py:79)、`title=item.title[:200]`(bad_case_catalog_sync.py:85),其余映射与 m6-17 的空值降级(`_object_name` bad_case_catalog_sync.py:53-58、`object_type or "skill"` bad_case_catalog_sync.py:81)保持不变。`BadCaseCatalogSyncService.run`(bad_case_catalog_sync.py:144-226)循环翻页:读游标(bad_case_catalog_sync.py:147-149)→ `mark_running`(bad_case_catalog_sync.py:161)→ 每页 `fetch_bad_case_page`(bad_case_catalog_sync.py:177-181)→ 空页即 exhausted(bad_case_catalog_sync.py:182-185)→ 游标不前进则报 502(bad_case_catalog_sync.py:186-192)→ `commit_page`(bad_case_catalog_sync.py:195-200)→ 推进游标与计数(bad_case_catalog_sync.py:201-206)→ 预算上限 `max_pages` / `deadline` 控制单轮规模(bad_case_catalog_sync.py:103-112、176)→ 收尾 `mark_idle`(bad_case_catalog_sync.py:210)或异常 `mark_failed` 后重抛(bad_case_catalog_sync.py:211-216)。 + +### 2.3 调度层:`bad_case_catalog_sync_coordinator.py` + +`trigger`(bad_case_catalog_sync_coordinator.py:77-99)查 `find_active_kind` 保证单飞;`start` 先 `reconcile`(把上一个进程遗留的 running 行标 failed,bad_case_catalog_sync_coordinator.py:105-116)再立即跑一轮,然后按 `interval` 起周期任务(bad_case_catalog_sync_coordinator.py:118-139、184-201);`status`(bad_case_catalog_sync_coordinator.py:151-182)把游标、计数与最近错误聚合给同步浮层。 + +### 2.4 存储层:`db/crud/bad_case_catalog_sync.py` + +`commit_page`(bad_case_catalog_sync.py:232-301,crud 文件)是页级原子写入:先查每条 id 的当前写入者归属 `_ownership`(crud:303-324);非本源 id 跳过,本源新 id 走 `begin_nested` 批量插入,`IntegrityError` 兜底重查归属再插(crud:247-264);catalog 自有行按 `_UPDATE_COLUMNS`(crud:25-39,含 `title` 与 `bad_case_type`)更新(crud:265-278);同事务里重算 `synced_count` 并把 `last_bad_case_id` 推到本页最大 id(crud:279-296)——游标推进与行写入同事务,崩溃只回滚整页。docstring 明确所有权规则:reporter 写过的行 catalog 永不覆盖,只计 skipped(crud:240-245)。 + +### 2.5 读路径:`db/crud/overview.py` + +`KNOWN_BAD_CASE_TYPES = ("self", "discovery")`(overview.py:35);`_case_conditions` 对所有读路径统一加 `bad_case_type.in_(KNOWN_BAD_CASE_TYPES)`(overview.py:119,注释明说这是防列内出现契约外类型的读侧防线);`counts`(overview.py:158-208)按 self/discovery 分桶聚合,`page_cases`(overview.py:380-467)取 `title`(overview.py:402、461)供列表展示。null type 若不归一化,要么插不进 NOT NULL 列(domain.py:306),要么以契约外值落库后被 :119 静默排除——这就是归一化落 `self` 的读路径理由。 + +### 2.6 表结构与连接 + +`bad_cases`(domain.py:294-330):`bad_case_type` String(16) NOT NULL(domain.py:306)、`title` String(255) NOT NULL(domain.py:312)——本 PR 未动。MySQL 走 asyncmy(mysql.py:13),默认连接串带 `charset=utf8mb4`(config.py:217),这决定 utf8mb4 的字符宽度语义适用于本表(见 D3)。 + +### 2.7 装配 + +`main.py:299-312`:`BadCaseCatalogSyncRepository` → `BadCaseCatalogSyncService.from_settings`(main.py:300-304)→ `BadCaseCatalogSyncCoordinator`(main.py:305-311)→ `jobs.register_handler(BAD_CASE_CATALOG_SYNC_KIND, catalog_service.handle)`(main.py:312)。定时触发入口在 coordinator,执行入口在 service,存储入口在 crud,三层职责分离。 + +## §3 数据流走查 + +剧本:上游返回一页 2 条——id=101 `bad_case_type=null`、title 正常;id=102 `type="self"`、title 恰好 300 个字符。 + +1. 周期触发:coordinator `_scheduler_loop` 到点调 `run_once` → `trigger`(coordinator:101-103、77-99),提交 `KIND="bad_case_catalog_sync"` job;JobRunner 通过 main.py:312 注册的 handler 进入 `service.handle`(service:131-142)→ `run(owner=job.id)`。 +2. 读游标与开工:`get_state` 拿 `last_bad_case_id`(service:147-149 → crud:128-142),`mark_running` 清上轮错误(service:161 → crud:186-198)。 +3. 取页:`fetch_bad_case_page(after_id=cursor, offset=0, limit=page_size)`(service:177-181)→ `HttpBadCaseCatalogSource.fetch_page` 持锁发请求(http.py:34-49、42)→ `_parse` 校验。**修复前**:id=101 的 null type 在 `model_validate` 违反必填约束、id=102 的 300 字符 title 违反 255 上限,`ValidationError` → 整页 `BAD_CASE_QUERY_INVALID_RESPONSE`(http.py:114-119、149-155),游标卡死。**修复后**:models.py:18 与 :24 放行这两种形状,页通过;页级排序/唯一/limit/total 校验照常把关(models.py:50-62)。 +4. 逐条归一化:`_row(item, page_now)`(service:195-200 → 61-91)。id=101 命中 `bad_case_type is None` → 日志 `fields="bad_case_type"`,落库 `bad_case_type="self"`(service:79);id=102 命中 `len(title)=300 > 200` → 日志 `fields="title"`,落库 title 为前 200 字符(service:85)。若一条同时命中两项,`fields="bad_case_type,title"`(service:63-75)。 +5. 原子落页:`commit_page`(crud:232-301)。101/102 都是 catalog 新 id → `begin_nested` 批量插入(crud:255-256);`bad_case_type` 列 NOT NULL(domain.py:306)由第 4 步的 `self` 兜住;同事务把 `last_bad_case_id` 推到 102、`synced_count` 重算(crud:286-296)。 +6. 游标推进与收尾:`pages+1`、`cursor=102`、`pending = total − len(items) = 0`(service:201-206、194);本页 2 条 ≥ total 2 → `exhausted=True`(service:207-209)→ `mark_idle` 归零 attempts 与 last_error(service:210 → crud:214-230)。 +7. 读路径统计:总览 `counts` 的 `_case_conditions` 用 `bad_case_type.in_(("self","discovery"))` 过滤(overview.py:114-132、119)——id=101 归一化后带 `self` 标签进入 `self_cases` 计数(overview.py:180-182),而不是被白名单静默排除;`page_cases` 列表展示 id=102 的截后 200 字符标题(overview.py:402、461),前端与同步浮层不需要任何感知。 + +反路径(未放宽的形状照旧拒绝):空 session_id、37 字符 session_id、17 字符 type、空 title 任一出现,仍在第 3 步整页 `BAD_CASE_QUERY_INVALID_RESPONSE`,游标不动、`mark_failed` 记稳定错误码(service:211-216、crud:200-212)——页级原子性与「坏页不推进」的既有语义未被本 PR 触碰(test_bad_case_query_client.py:205-235 锁定)。 + +## §4 导读地图 + +| 文件 | 状态 | +|---|---| +| `apps/api/app/third_party_api/bad_case_query/http.py` | ✅ 已通读 | +| `apps/api/app/third_party_api/bad_case_query/models.py` | ✅ 已通读 | +| `apps/api/app/service/acquisition/bad_case_catalog_sync.py` | ✅ 已通读 | +| `apps/api/app/service/acquisition/bad_case_catalog_sync_coordinator.py` | ✅ 已通读 | +| `apps/api/app/db/crud/bad_case_catalog_sync.py` | ✅ 已通读 | +| `apps/api/app/db/crud/overview.py`(读路径相关段) | ✅ 已读 96-210、378-497 与 grep 命中区 | +| `apps/api/app/db/models/domain.py`(bad_cases / bad_case_catalog_sync 表段) | ✅ 已读 280-339 | +| `apps/api/app/db/mysql.py`、`apps/api/app/config.py`(连接串段) | ✅ 已读相关段 | +| `apps/api/app/main.py`(装配区) | ✅ 已读 280-324 | +| `apps/api/tests/m6-16-bad-case-catalog-sync/test_bad_case_query_client.py` | ✅ 已通读 | +| `apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py` | ✅ 已通读 | +| `apps/api/tests/bad_case_sync_fakes.py` | ✅ 已读 1-59 | +| `.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.md`(中文版) | ✅ 已通读 | +| `plans/fullstack-design/12-bad-case-catalog-sync.md`(§3.2/§3.3/§4.1) | ✅ 已读 95-154 与 diff | +| 8 个变更文件的 `git diff 907d3446...HEAD` | ✅ 已读 | +| `.agents/notes/...-normalization.en.md` 与 `.i18n.yaml` | ◻ 未逐行(配对一致性由 `lint:docs` 双语门禁兜底,CI docs-flow 绿) | +| `plans/fullstack-design/12-bad-case-catalog-sync.md` 其余章节 | ◻ 只读走查涉及段 | +| `apps/api/app/third_party_api/bad_case_sync_source.py`(`BaseBadCaseSyncSource` 模板) | ◻ 未读(仅确认 `fetch_bad_case_page` 委托关系) | +| `tests/m6-16-bad-case-catalog-sync/` 其余 4 个测试文件(coordinator / repository / status api / migration) | ◻ 未读(本 PR 未改,聚焦测试复跑 67 passed 间接覆盖) | +| `apps/api/app/service/evolution/attribution.py` / `attribution_executor.py` | ◻ 只 grep `[:200]` 两行(attribution.py:436、attribution_executor.py:118),确认 200 口径出处 | +| `plans/fullstack-design/06-database-design.md` §4.1 | ◻ 未读(列宽主张转引 Note 与 domain.py 实读) | + +## §5 人工验收清单 + +PR body 本身没有显式 checkbox 清单(其「检视与复核」段声明清单落本文);以下从关联 issue #600「验收标准」段原样提取。前 3 条的代码路径已被自动化测试锁定,人工验收指在真实上游环境下的运行确认,合并前由维护者勾选: + +- [ ] 上游返回 null/缺失 `bad_case_type` 时同步成功,落库 `self`。(自动化已锁:`test_fetch_page_allows_null_bad_case_type` 2 形状、`test_null_bad_case_type_falls_back_to_self`) +- [ ] 上游返回超过 200 字符的 `title` 时同步成功,落库前 200 字符。(自动化已锁:`test_fetch_page_allows_overlong_title`、`test_title_is_verbatim_up_to_200_and_truncated_beyond` 3 边界) +- [ ] 200 字符以内与非空 type 的值保持原样。(自动化已锁:`test_explicit_bad_case_type_and_short_title_stay_verbatim` 2 形状) +- [ ] 相关测试、类型检查、lint 与流程/文档门禁全绿。(自动化证据已闭合:CI 12 checks 全绿 + 本机复跑目录聚焦 67 passed;`lint:api` / `typecheck:api` / `test:db` / `verify:flow` / `lint:docs` / `contract:check` 检视侧未复跑,以 CI 为据) +- [ ] 合并后按流程单独提交闭环 PR,关闭 #600。(PR body 明示不自动关闭) + +## §6 讨论点 + +### D1 `bad_case_type=""`(空字符串)形状未被测试覆盖 + +- **位置**:`apps/api/app/third_party_api/bad_case_query/models.py:18`(约束)、`apps/api/app/service/acquisition/bad_case_catalog_sync.py:79`(归一化)、`apps/api/tests/m6-16-bad-case-catalog-sync/test_bad_case_query_client.py:205-235`(非法形状参数化,含 17 字符 type 与空 title,无空串 type) +- **现象**:传输约束 `str | None = Field(default=None, min_length=1, max_length=16)` 对非 None 值生效——探针实测(pydantic 2.14.4):空串被拒 `string_too_short`,null 与缺失放行。该 `min_length=1` 是 main 原样保留项,本 PR 只把类型改为可空。测试覆盖了 null、缺失、超长三种漂移形状,空串形状不在任何参数化列表里。 +- **问题**:是否值得在本 PR 补一条参数化用例(把 `{"bad_case_type": ""}` 加进客户端非法形状列表),还是留给后续? +- **预判**:当前行为是自洽的:传输层拒绝空串,空串永远到不了 `_row`;即使将来放行,`or "self"`(falsy 兜底)也会把空串落成 `self`(见 D4 的漂移实例)。所以这是「防未来无意放宽」的回归锁,而非修复项:往现有 `pytest.mark.parametrize` 列表加一项的成本约一行,收益是把「传输层继续拒绝空串」这一 main 既有契约显式钉住。倾向本 PR 顺手补一条;若维护者认为该约束无需回归保护,留后续亦可——两种选择当前都无实害。 +- **结论**:已决(2026-11-25,采纳并修复):`test_fetch_page_still_rejects_illegal_shapes` 参数化列表补 `{"bad_case_type": ""}`,断言空串 type 仍整页 `BAD_CASE_QUERY_INVALID_RESPONSE`——传输层 `min_length=1` 拒绝空串是 main 既有契约(pydantic 探针已证实),用例钉住它防未来无意放宽。 + +### D2 归一化日志用 `logger.info` 的量级影响 + +- **位置**:`apps/api/app/service/acquisition/bad_case_catalog_sync.py:63-75`(配合 `page_size` 上限 200(service:110、models.py:47)与 `max_pages` 默认 100(service:103)) +- **现象**:每条命中归一化的 item 记一条 info 日志,逐条携带 `badCaseId`。极端场景(上游全量漂移,如冷启动同步十万条、全部 title 超长):单轮 run 理论上限 100 页 × 200 条 = 2 万条 info 日志。 +- **问题**:上游大面积漂移时,info 级逐条日志的噪音与存储量是否可接受?要不要改成每页一条聚合、或降级/采样? +- **预判**:逐条 + 带 `badCaseId` 正是这条日志的设计意图——「区分上游漂移与本地逻辑错误」需要能定位到具体 case(Note Consequences 第 4 条已记录此取舍);聚合会丢掉可定位性,采样会丢掉漂移规模。漂移量本身就是需要被看见的信号:万级漂移暴露的是上游数据治理问题,日志量只是它的影子,且 info 级别在常规日志管线下可控。倾向维持现状,无实害;真出现量级问题时再议采样,届时 owning Note 的 Consequences 是现成的重评估起点。 +- **结论**:已决(2026-11-25,不改代码):逐条带 `badCaseId` 的 info 日志正是「区分上游漂移与本地逻辑错误」的设计意图,极端量级(单轮至多 2 万条)是上游数据治理问题的影子且 info 级可控;真出现量级问题再议采样,owning Note Consequences 为现成重评起点。 + +### D3 `title[:200]` 的截断边界:Python 码点 vs 数据库 utf8mb4 字符宽度 + +- **位置**:`apps/api/app/service/acquisition/bad_case_catalog_sync.py:85`(截断)、`apps/api/app/db/models/domain.py:312`(`title` String(255))、`apps/api/app/config.py:217`(默认连接串 `charset=utf8mb4`) +- **现象**:Python 字符串切片按 Unicode 码点截断(`len('😄') == 1`);MySQL 官方手册 §13.3.1 明确「对字符字符串列(CHAR/VARCHAR/TEXT),长度规格按字符单位解释」「VARCHAR(M) 的 M 是最大字符数」,utf8mb4 下 BMP 之外的增补字符(如 emoji)同样计 1 字符。本表通过 utf8mb4 连接访问。 +- **问题**:码点截断语义与数据库字符宽度语义是否一致?4 字节字符(emoji)会不会因「字节 vs 字符」错位导致截后仍超列宽? +- **预判**:一致,无风险。两端计数都是码点口径:Python `[:200]` 最多 200 个码点,MySQL utf8mb4 的 VARCHAR(255) 按 255 个字符(码点)计,200 ≤ 255 恒成立,写入永不触列宽。探针实测传输层放行 250 个 emoji 的 title 且 `len==250`(每 emoji 计 1 码点),佐证码点口径。SQLite 测试环境不强制 VARCHAR 长度,更无影响。检视侧未起本地 MySQL 实例做端到端写入实测(本机无 MySQL),依据为官方文档 + CI `mysql` lane 绿;组合字符(变音符等 grapheme cluster 拆成多码点)在两端都按码点计,口径同样一致。结论:无实害。 +- **结论**:已决(2026-11-25,实测 + 官方文档):无实害——Python `[:200]` 码点截断与 MySQL utf8mb4 字符宽度口径一致(手册 §13.3.1:字符列长度按字符单位解释),200 ≤ 255 恒成立,写入永不触列宽。 + +### D4 `_row` 里「归一化检测」与「实际归一化」是两处独立逻辑,存在漂移空间 + +- **位置**:`apps/api/app/service/acquisition/bad_case_catalog_sync.py:63-70`(检测:`is None` / `len > 200`)对照 `:79` / `:85`(改写:`or "self"` / `[:200]`) +- **现象**:检测表达式与改写表达式分处两段,靠人肉保持同步。对 None 与 `>200` 两者严格一致;对空串 `""` 两者不一致——`"" or "self"` 会归一落库,但 `"" is None` 不判漂移、不记日志。当前该不一致不可达:传输层 `min_length=1` 拒绝空串(探针实测 `string_too_short`)。 +- **问题**:未来若有人放宽传输约束(例如允许空串表达「上游显式空」),只改一处不改另一处,会产生「落库 self 但无归一化日志」或反向的静默漂移;这个同步维护成本要不要现在收口? +- **预判**:风险真实但当前不可达,无实害。可选收口是先算归一值再与原值比较(把两处合成一处),但会牺牲现写法的直读性;m6-17 的 `object_name` / `object_type` 降级(service:53-58、81)一直没有日志,本 PR 的检测已是增强而非欠账。倾向本 PR 不改,约定「放宽传输约束的 PR 必须同时补空串用例」(与 D1 呼应),届时顺手收口;该约定可写进 owning Note 的 Consequences 一句话防遗忘。 +- **结论**:已决(2026-11-25,不改代码):空串被传输层拒绝,检测/改写不一致当前不可达;D1 用例已锁空串拒绝行为;约定未来任何放宽传输约束的 PR 必须补空串用例并同步收口 `_row` 检测与改写逻辑(约定记本文结论栏)。 + +### D5 存量 201–255 字符 title 行在下次 catalog 更新时会被被动截断(检视侧补充) + +- **位置**:`apps/api/app/db/crud/bad_case_catalog_sync.py:25-39`(`_UPDATE_COLUMNS` 含 `title`)、`:265-278`(catalog 自有行 update)、`apps/api/app/service/acquisition/bad_case_catalog_sync.py:85` +- **现象**:修复前旧代码允许 201–255 字符 title 原样落库(列宽 255)。修复后,若这类存量行(origin=catalog)再次进入同步窗口,update 分支会用归一化后的值(截前 200)覆写 title。 +- **问题**:issue 非目标写明「不回填或重写存量行」——这种被动截断是否越界? +- **预判**:不越界,影响面极小:游标只增(crud:286-296 仅在 commit_page 内推进,service:205),已推进过的 id 不会被重扫;只有冷启动(cursor 行不存在)或该 id 恰在未同步窗口内才会触发 update。且「下次同步按当前归一化规则写入」与主动回填是两回事——落库值本就应满足现行规则,与「上游该行本来就是超长 title」一致。无实害,无需行动;记录留档供将来追溯「为什么某行 title 从 230 字符变成 200」。 +- **结论**:已决(2026-11-25,不改代码):被动截断仅影响冷启动或恰在未同步窗口内的存量行(游标只增、已推进 id 不重扫),影响面极小;「下次同步按现行规则写入」与主动回填是两回事,本文留档供将来追溯。 + +## §7 分流表 + +| 发现 | 定性 | 去处 | 状态 | +|---|---|---|---| +| `bad_case_type=""` 形状未测(传输层拒绝行为未钉住) | 测试策略(当前无实害) | 本 PR 补一条参数化(`test_fetch_page_still_rejects_illegal_shapes` 已含空串) | ✅ 已决(2026-11-25,采纳并补用例) | +| 归一化 info 日志逐条记录,极端漂移下单轮可达万级 | 设计(可接受) | 无需行动;owning Note Consequences 已记录 | ✅ 已决(2026-11-25,接受现状不改代码,量级问题再议采样) | +| `title[:200]` 码点截断 vs utf8mb4 字符宽度 | 事实核查 | 证据留档本文 D3 | ✅ 已决(2026-11-25 实测 + MySQL 官方文档:口径一致,无实害) | +| 归一化检测与改写两处逻辑可能漂移 | 可维护性(当前不可达) | 未来放宽传输约束时收口;约定记本文 §6 D4 | ✅ 已决(2026-11-25,不改代码;约定放宽传输约束的 PR 必须补空串用例并收口 `_row`) | +| 存量超长 title 行的被动截断 | 事实确认(无实害) | 本文 D5 留档 | ✅ 已决(2026-11-25,接受现状不改代码) | +| 传输放宽范围(仅 type 可空 + title 去上限) | —— | 12 §3.3「仅有的两处放宽」+ 客户端非法形状 4 例参数化锁定 | ✅ 已决(2026-11-25,67 passed 内验证) | +| null/缺失 type 落 `self`、200 截断规则本身 | —— | 服务测试 5 例 + 参数化 3 边界锁定 | ✅ 已决(2026-11-25) | +| 归一化日志含 `badCaseId` 与字段名 | —— | caplog 3 形状参数化 + 无日志反例锁定 | ✅ 已决(2026-11-25) | +| 12 章文档与实现一致性 | —— | §3.2 映射表/§3.3 放宽条款与代码逐条对照无偏差 | ✅ 已决(2026-11-25 diff 实读) | +| Agent Note 三件套与决策一致性 | —— | Note Decision/Alternatives 与实现及 12 章一致 | ✅ 已决(2026-11-25 中文版实读) | +| 本检视文档 | process | `plans/` 本文 | ✅ 落盘(2026-11-25) | + +## §8 链接 + +- PR:https://github.com/Shadow-Azure/harness-evolution/pull/606(CI run 45558020793,12 checks 全绿) +- Issue:#600 https://github.com/Shadow-Azure/harness-evolution/issues/600 +- owning Note:`.agents/notes/implemented/bug-fix/2026-11-25-bad-case-sync-type-title-normalization.md`(`.en.md` / `.i18n.yaml` 同目录) +- 实现计划:`plans/fullstack-design/12-bad-case-catalog-sync.md` §3.2/§3.3;列宽依据 `plans/fullstack-design/06-database-design.md` §4.1(◻ 转引) +- 既有分层先例:m6-17 Note `.agents/notes/implemented/feature/2026-10-30-bad-case-catalog-sync.md`(object_name/object_type 降级,未逐行读) +- 后续:合并后单独提交闭环 PR,关闭 #600;D1/D4 拍板结论已落 §6 与 §7(D1 补用例、D4 约定记本文结论栏) + +## §9 文件级代码分析 + +### 9.1 `apps/api/app/third_party_api/bad_case_query/models.py`(M) + +职责:上游 bad case 目录查询的传输模型与分页源 Protocol——把「上游响应长什么样」钉成代码。变更形态:M,±3 行两处字段签名 + docstring 一句。 + +关键依赖:`pydantic`(2.14.4,运行时校验库,社区第一方生态的核心件):`Field` 的 `min_length` / `max_length` 对 `str | None` 只作用于非 None 值;`ConfigDict(extra="forbid")` 让多余字段整页拒绝。可把 pydantic 比作海关 X 光机——包裹形状不合规格当场拦下,本 PR 相当于把两种「上游真实会寄」的形状从违禁清单移到放行清单。 + +旧代码(`git show 907d3446:...`): + +```python +class BadCaseItem(BaseModel): + """One upstream bad case shaped like the local bad_cases columns.""" + ... + bad_case_type: str = Field(min_length=1, max_length=16) + ... + title: str = Field(alias="bad_case_title", min_length=1, max_length=255) +``` + +新代码: + +```python +class BadCaseItem(BaseModel): + """One upstream bad case; null type and overlong titles stay for write normalization.""" + ... + bad_case_type: str | None = Field(default=None, min_length=1, max_length=16) + ... + title: str = Field(alias="bad_case_title", min_length=1) +``` + +这在做什么:把「上游数据已满足本地列约束」这个错误假设从模型里去掉——type 可以没有,title 可以很长;非空时的 1–16 长度与非空 title 保留。为什么这么写:`default=None` 让「字段缺失」与「显式 null」殊途同归(探针实测两者都得到 `None`),解析层保持忠实(不改写值),把「怎么落库」留给写入层——这正是 docstring 新句 `stay for write normalization` 的含义。`BadCasePage` 的 `consistent` 校验器与 `limit le=200` 一行未动,页级结构防线原样。 + +实现思路总结:类型层只放宽「形状」约束,语义归一全部下沉写入层;两处放宽与 12 §3.3「仅有的两处放宽」条款逐字对应。 + +检视发现:空串形状仍被拒(main 原样,未测,见 D1);其余无发现。 + +### 9.2 `apps/api/app/service/acquisition/bad_case_catalog_sync.py`(M) + +职责:游标式同步服务——把上游页翻译成本地行并原子落库。变更形态:M,`_row` 函数 +13/−2 行,类主体零变更。 + +关键依赖:标准库 `logging`(结构化 extra 字段);下游 `CatalogCaseRow` 是纯数据类(crud:42-59),`bad_case_type` 字段声明为非可选 `str`——类型系统本身就逼着写入层给出非空值,`or "self"` 正是兑现处。 + +旧代码: + +```python +def _row(item: BadCaseItem, fallback: datetime) -> CatalogCaseRow: + """Map one upstream item to local column names, defaulting timestamps.""" + return CatalogCaseRow( + ... + bad_case_type=item.bad_case_type, + ... + title=item.title, + ... + ) +``` + +新代码: + +```python +def _row(item: BadCaseItem, fallback: datetime) -> CatalogCaseRow: + """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_type=item.bad_case_type or "self", + ... + title=item.title[:200], + ... + ) +``` + +这在做什么:落库前先回答「这条要不要加工」,要则记一笔带 `badCaseId` 与命中字段名的流水,然后统一产出满足本地列约束的行。为什么这么写:`or "self"` 与 `[:200]` 都是无条件表达式,正常数据走过去值不变(`"self" or "self"` == `"self"`,10 字符 `[:200]` 原样),漂移数据被兜住——不需要 if/else 分支,两条规则对显式合法值天然幂等(`test_explicit_bad_case_type_and_short_title_stay_verbatim` 锁定)。检测列表与 200 口径来自归因侧既有预算(attribution.py:436、attribution_executor.py:118 均 `[:200]`),不是新发明。 + +实现思路总结:归一化 = 一条检测(可观测)+ 一条改写(兜底),写进唯一的写入映射函数;页级事务、游标、预算逻辑零接触。 + +检视发现:检测与改写对空串不一致(D4,当前不可达无实害);逐条日志量级(D2,可接受);存量行被动截断(D5,无实害)。 + +### 9.3 `apps/api/tests/m6-16-bad-case-catalog-sync/test_bad_case_query_client.py`(M) + +职责:客户端层契约测试——哪些上游形状放行、哪些仍整页拒绝。变更形态:M,+88 行(新增 2 个放行用例 + 2 组参数化),既有用例零改动。 + +新增代码(形状): + +```python +@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.""" + ... + assert page.items[0].bad_case_type is None + +async def test_fetch_page_allows_overlong_title() -> None: + """The transport keeps a 300-character title verbatim; truncation happens at write.""" + ... + assert len(page.items[0].title) == 300 + +@pytest.mark.parametrize("overrides", [ + {"bad_case_session_id": ""}, + {"bad_case_session_id": "s" * 37}, + {"bad_case_type": "x" * 17}, + {"bad_case_title": ""}, +]) +async def test_fetch_page_still_rejects_illegal_shapes(overrides) -> None: + """Only the null-type and overlong-title shapes were relaxed; the rest stays strict.""" +``` + +这在做什么:放行侧断言「解析成功且值保真」(null 就是 None,300 就是 300——写入前的忠实是写入归一的前提);拒绝侧用参数化把「没被放宽的形状」逐个钉死,防止未来有人顺手多放宽一处。为什么这么写:`_parse` 的失败语义是整页收敛为一个错误码,所以拒绝侧只断言 `BAD_CASE_QUERY_INVALID_RESPONSE`,不深究 pydantic 具体哪条规则报错——那是模型层的实现细节。 + +实现思路总结:放行/拒绝两个方向对称覆盖,放宽范围被测试边界显式圈定。 + +检视发现:非法形状列表无空串 type(D1,拍板补用例,见 §6);其余无发现。 + +### 9.4 `apps/api/tests/m6-16-bad-case-catalog-sync/test_catalog_sync_service.py`(M) + +职责:服务层落库行为测试——归一化规则、日志、显式值幂等。变更形态:M,+118/−2(`_item` helper 加 `bad_case_type` 参数,新增 5 组用例)。 + +旧代码(helper): + +```python +def _item(case_id: int, *, title: str | None = None, object_name: ..., ...) -> BadCaseItem: + return BadCaseItem( + ... + bad_case_type="self", + ... + ) +``` + +新代码(helper + 关键用例,形状): + +```python +def _item(case_id: int, *, title=None, bad_case_type: str | None = "self", ...): + ... + +async def test_null_bad_case_type_falls_back_to_self(database) -> None: + """A null upstream type lands as self so type-scoped counts keep the row.""" + ... + assert row["bad_case_type"] == "self" + +@pytest.mark.parametrize("upstream_length", [200, 201, 300]) +async def test_title_is_verbatim_up_to_200_and_truncated_beyond(database, upstream_length): + ... + assert (await _titles(database))["1"] == title[:200] + +@pytest.mark.parametrize( + ("bad_case_type", "title_length", "fields"), + [(None, 300, "bad_case_type,title"), (None, 10, "bad_case_type"), ("self", 300, "title")], +) +async def test_normalization_logs_bad_case_id_and_hit_fields(database, ..., caplog): + ... + assert [getattr(r, "badCaseId", None) for r in records] == [1] + assert [getattr(r, "fields", None) for r in records] == [fields] +``` + +这在做什么:落库断言直接查 SQLite 行(`_row_by_id`),不经过任何 mock——「截前 200」是数据库里真实存的值;日志断言用 caplog 过滤本模块记录名,逐字段核对 extra;三形状参数化同时覆盖「双命中」「仅 type」「仅 title」,无日志反例(`test_verbatim_rows_emit_no_normalization_log`)保证「命中才记」。为什么这么写:这组测试的目标是规则本身而非翻页机制(翻页已有既有用例),所以每例都最小化——单条数据、单次 run。 + +实现思路总结:规则三要素(兜底值、边界值、日志内容)各由一组参数化钉住,显式值幂等单列一组。 + +检视发现:无空串 type 的服务层用例(与 D1 同源,传输层已拒,服务层无需重复覆盖,倾向只补客户端一条);其余无发现。 + +### 9.5 `plans/fullstack-design/12-bad-case-catalog-sync.md`(M) + +职责:第 12 章设计文档——同步的数据契约与校验语义。变更形态:M,+4/−2 行,§3.2 映射表与 §3.3 条款各一处。 + +旧代码(§3.2 映射表节选): + +```markdown +| `bad_case_title` | `bad_cases.title` | 唯一改名映射 | +``` + +新代码: + +```markdown +| `bad_case_type` | `bad_cases.bad_case_type` | null 或缺失时取 `self`;显式值原样写入,非空仍限 1–16 字符 | +| `bad_case_title` | `bad_cases.title` | 唯一改名映射;超过 200 字符截断为前 200 字符,200 字符以内原样保留 | + +null/缺失 type 落 `self` 与 title 超 200 截前 200 都是写入映射(`_row`)的归一化规则,不在解析层改写任何值;……命中归一化时记录一条含 `badCaseId` 与命中字段名的 info 日志,用于区分上游漂移与本地逻辑错误。 +``` + +§3.3 同步补一句「这是传输模型仅有的两处放宽;其余……仍整页拒绝」。 + +这在做什么:把两条归一化规则与放宽边界写进契约文档,映射表行、放宽条款、实现代码三处口径一致。为什么这么写:12 章是同步链路的实现依据(issue 明确「实现冲突时以第 12 章为准」),规则落在文档里,后续检视与实现才有对照基准。 + +实现思路总结:文档增量与代码增量一一对应,无多余条款。 + +检视发现:无发现(diff 实读逐条对照一致)。 + +### 9.6 Agent Note 三件套(A,成组折叠) + +职责:决策记录——为什么归一化放写入映射、title 截断为什么有损但可接受、列宽为什么仍 255。变更形态:A×3(中文 29 行 + 英文对照 + i18n 哈希),四段骨架 `Problem / Decision / Alternatives considered / Consequences`。 + +关键内容(中文版实读):Problem 段如实记录「200 口径当时在代码里并不存在,实测的截断阈值就是列宽 255」这一事实底座;Decision 段与代码逐字对应;Alternatives 段否掉 5 个方案(做进传输模型 / 维持严格等上游 / 跳过坏行 / 按 255 截 / 收列宽加迁移),每个都给了可复用的拒绝理由;Consequences 段承认「标题截断是有损的:被截内容无法回捞」并解释可接受原因。这不是复述代码的 Note——「为什么放写入层不改解析层」与「有损但可接受」两个判断只在这里。 + +检视发现:中文版与实现一致;英文版与 i18n.yaml 未逐行读(◻,由 lint:docs 双语配对门禁与 CI docs-flow 兜底)。 + +## 附:检视侧实测记录 + +- 探针环境:`apps/api/.venv`,pydantic 2.14.4,Python 3.14.3,Windows 本机;形状×7 全部通过 `BadCaseItem.model_validate` 直测(结果见 §1 验证基线行)。 +- 聚焦测试:`pnpm test:api -- tests/m6-16-bad-case-catalog-sync` → 67 passed(179.01s),含 coordinator/repository/status-api/migration 未变更用例。 +- CI:`gh pr view 606 --json statusCheckRollup` → 12/12 SUCCESS。 +- MySQL 官方文档:[8.0 手册 §13.3.1 String Data Type Syntax](https://docs.oracle.com/cd/E17952_01/mysql-8.0-en/string-type-syntax.html)——「MySQL interprets length specifications in character units」;dev.mysql.com 原站 403,经 docs.oracle.com 镜像取证。 diff --git a/plans/fullstack-design/12-bad-case-catalog-sync.md b/plans/fullstack-design/12-bad-case-catalog-sync.md index e515235a..1f0726d7 100644 --- a/plans/fullstack-design/12-bad-case-catalog-sync.md +++ b/plans/fullstack-design/12-bad-case-catalog-sync.md @@ -108,14 +108,18 @@ Accept: application/json | 接口字段 | 表列 | 处理 | |---|---|---| | `bad_case_id` | `bad_cases.bad_case_id` | 接口是整数,落库转十进制字符串 | -| `bad_case_title` | `bad_cases.title` | 唯一改名映射 | +| `bad_case_type` | `bad_cases.bad_case_type` | null 或缺失时取 `self`;显式值原样写入,非空仍限 1–16 字符 | +| `bad_case_title` | `bad_cases.title` | 唯一改名映射;超过 200 字符截断为前 200 字符,200 字符以内原样保留 | | `object_name` | `bad_cases.object_name` | 为空时:`source` 为 `code_reivew` / `code_review` 取 `code-review`;否则取 `source`;`source` 为空取 `unknown` | | `object_type` | `bad_cases.object_type` | 为空时取 `skill` | | `created_at` / `updated_at` | 同名 | 可选;存在时解析 ISO-8601 带时区时间并按原值写入,缺失时用本次同步时间兜底 | +null/缺失 type 落 `self` 与 title 超 200 截前 200 都是写入映射(`_row`)的归一化规则,不在解析层改写任何值;为承接上游真实形状,传输模型仅放宽这两个字段——`bad_case_type` 允许 null 或缺失、`title` 只保留非空约束——命中归一化时记录一条含 `badCaseId` 与命中字段名的 info 日志,用于区分上游漂移与本地逻辑错误。 + ### 3.3 校验、错误与串行 - 严格模型:`extra="forbid"`,缺必填字段、类型不符、id 非递增、页大小超限、`total < len(items)` 都记为 `BAD_CASE_QUERY_INVALID_RESPONSE`。 +- `bad_case_type` 可为 null 或缺失、`title` 不设长度上限(归一化见 §3.2),这是传输模型仅有的两处放宽;其余字段校验、`extra="forbid"` 与页级结构校验不变,任何其他非法形状仍整页记为 `BAD_CASE_QUERY_INVALID_RESPONSE`。 - 时间戳字段可以缺失:`bad_cases.created_at` / `updated_at` 是 NOT NULL,缺失时用本次同步时间兜底,不判非法;存在但不是带时区 ISO-8601 才算响应非法。 - 4xx 不重试;401/403 → `BAD_CASE_QUERY_UNAUTHORIZED`;429/5xx/超时按配置重试;重试耗尽 → `BAD_CASE_QUERY_TIMEOUT` / `BAD_CASE_QUERY_REQUEST_FAILED`。 - `BadCaseCatalogQuerySource` 内部用一把 `asyncio.Lock` 包住每次请求;即使未来有第二个调用方,也不会并发。