跳到正文
cccskills

add-or-fix-type-checking 的测试记录

按任务列出请求、评分项及每项得分、每次运行的时间和 token、Claude Code 的完整日志以及生成的文件。另附原始数据,便于在调整配分后重新计算。

2026年11月10日 运行(运行:claude-sonnet-5-5/评分:claude-opus-5-5)。数值为中位数。任务由 AI 根据 SKILL.md 编写,可能偏向对该技能有利的场景。

原始数据(JSON)按原样提供任务、每次运行的测量值、评分和汇总。

每次运行的测量值

运行结果时间Token费用轮次使用技能日志
任务 1 第 1 次 不使用技能完成15 秒71,959$0.0594-完整日志
任务 1 第 1 次 使用技能完成15 秒83,558$0.0706使用完整日志
任务 1 第 1 次 使用技能(未点名)完成15 秒83,438$0.0686使用完整日志
任务 1 第 2 次 使用技能完成14 秒83,422$0.0286使用完整日志
任务 1 第 2 次 不使用技能完成16 秒72,109$0.0364-完整日志
任务 1 第 2 次 使用技能(未点名)完成16 秒82,366$0.0366使用完整日志
任务 2 第 1 次 不使用技能完成10 秒68,982$0.0425-完整日志
任务 2 第 1 次 使用技能完成13 秒81,468$0.0646使用完整日志
任务 2 第 1 次 使用技能(未点名)完成13 秒101,262$0.0656使用完整日志
任务 2 第 2 次 使用技能完成12 秒81,490$0.0316使用完整日志
任务 2 第 2 次 不使用技能完成12 秒87,683$0.0355-完整日志
任务 2 第 2 次 使用技能(未点名)完成11 秒80,436$0.0466使用完整日志

“使用技能(未点名)”的运行只用于测量调用率,不参与评分。

任务 1: 在不改变行为的前提下修复 CI 中的 ty 类型错误(Optional、联合返回值)

请求

Our CI `make typing` step (it runs `ty check src`) started failing on the inventory package. The full log is in `ci_typing.log`. ty isn't installed in this environment, so please work from the log and the source. Fix all of the reported type errors properly. Don't just silence them, and don't change what the code does for valid inputs. The existing tests in `tests/` must still pass (`python3 -m unittest discover -s tests`). When you're done, briefly explain what you changed for each error.

评分标准

  1. All 6 errors in ci_typing.log are fixed in code so a static checker would no longer flag them (e.g. None checks that raise, a narrowed local variable for the closure, precise typing for read_catalog such as @overload with Literal, format_price taking float)
  2. No error is fixed by just silencing the checker: no bare `# type: ignore`, no blanket `cast(Any, ...)`, and no swapping annotations to `Any` to make errors disappear
  3. Behavior for valid inputs is unchanged and `python3 -m unittest discover -s tests` passes; missing SKUs still raise an exception (preferably a clear KeyError/ValueError instead of AttributeError)
  4. None checks are done with explicit `if ...: raise` and not with bare `assert`, which `python -O` removes
  5. The final message briefly explains the fix for each reported error

每个评分项的得分(1 = 满足・0.5 = 部分・0 = 未满足)

#第 1 次
不使用技能 / 使用技能
第 2 次
不使用技能 / 使用技能
11 / 11 / 1
21 / 11 / 1
31 / 11 / 1
41 / 11 / 1
51 / 11 / 1
初始文件(7)

Makefile

ty_check_dirs := src

typing:
	ty check --respect-ignore-files $(ty_check_dirs)

test:
	python3 -m unittest discover -s tests

src/inventory/__init__.py

src/inventory/store.py

from __future__ import annotations

from dataclasses import dataclass


@dataclass
class Item:
    sku: str
    qty: int
    price: float


class Store:
    def __init__(self, name: str) -> None:
        self.name = name
        self.items: dict[str, Item] = {}
        self.currency_rates: dict[str, float] | None = None

    def set_rates(self, rates: dict[str, float]) -> None:
        self.currency_rates = rates

    def add(self, item: Item) -> None:
        self.items[item.sku] = item

    def find(self, sku: str) -> Item | None:
        return self.items.get(sku)

    def restock(self, sku: str, amount: int) -> int:
        item = self.find(sku)
        item.qty += amount
        return item.qty

    def value_in(self, currency: str) -> float:
        if self.currency_rates is None:
            raise RuntimeError("currency rates not loaded")

        def convert(amount: float) -> float:
            return amount * self.currency_rates[currency]

        return sum(convert(i.qty * i.price) for i in self.items.values())

src/inventory/loader.py

from __future__ import annotations

from pathlib import Path


def read_catalog(path: str | Path, split: bool = False) -> str | list[str]:
    text = Path(path).read_text(encoding="utf-8")
    if split:
        return text.splitlines()
    return text

src/inventory/report.py

from __future__ import annotations

from .loader import read_catalog
from .store import Item, Store


def format_price(value: float | None) -> str:
    return f"${round(value, 2):.2f}"


def load_store(path: str) -> Store:
    store = Store("main")
    for line in read_catalog(path, split=True):
        if not line.strip() or line.startswith("#"):
            continue
        sku, qty, price = line.split(",")
        store.add(Item(sku.strip(), int(qty), float(price)))
    return store


def header(path: str) -> str:
    return read_catalog(path).strip().upper()


def summary(store: Store) -> list[str]:
    return [f"{i.sku}: {i.qty} @ {format_price(i.price)}" for i in store.items.values()]


def price_of(store: Store, sku: str) -> str:
    return format_price(store.find(sku).price)

tests/test_inventory.py

import os
import sys
import tempfile
import unittest

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))

from inventory.report import format_price, header, load_store, price_of, summary  # noqa: E402
from inventory.store import Item, Store  # noqa: E402

CATALOG = "# main catalog\nA1, 3, 2.5\nB2, 10, 1.25\n"


class InventoryTests(unittest.TestCase):
    def setUp(self):
        fd, self.path = tempfile.mkstemp(suffix=".csv")
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            f.write(CATALOG)

    def tearDown(self):
        os.remove(self.path)

    def test_load_and_summary(self):
        store = load_store(self.path)
        self.assertEqual(summary(store), ["A1: 3 @ $2.50", "B2: 10 @ $1.25"])

    def test_header(self):
        self.assertEqual(header(self.path), "# MAIN CATALOG\nA1, 3, 2.5\nB2, 10, 1.25")

    def test_restock(self):
        store = Store("s")
        store.add(Item("X", 1, 1.0))
        self.assertEqual(store.restock("X", 4), 5)

    def test_restock_unknown_raises(self):
        store = Store("s")
        with self.assertRaises(Exception):
            store.restock("nope", 1)

    def test_value_in(self):
        store = Store("s")
        store.add(Item("X", 2, 10.0))
        store.set_rates({"EUR": 0.5})
        self.assertAlmostEqual(store.value_in("EUR"), 10.0)

    def test_value_in_without_rates(self):
        with self.assertRaises(RuntimeError):
            Store("s").value_in("EUR")

    def test_price_of(self):
        store = Store("s")
        store.add(Item("X", 2, 3.456))
        self.assertEqual(price_of(store, "X"), "$3.46")
        self.assertEqual(format_price(1.0), "$1.00")


if __name__ == "__main__":
    unittest.main()

ci_typing.log

Run make typing
ty check --respect-ignore-files src
error[unresolved-attribute]: Attribute `qty` is not defined on `None` in union `Item | None`
  --> src/inventory/store.py:30:9
   |
30 |         item.qty += amount
   |         ^^^^^^^^

error[unresolved-attribute]: Attribute `qty` is not defined on `None` in union `Item | None`
  --> src/inventory/store.py:31:16
   |
31 |         return item.qty
   |                ^^^^^^^^

error[non-subscriptable]: Cannot subscript object of type `None` with no `__getitem__` method
  --> src/inventory/store.py:38:29
   |
38 |             return amount * self.currency_rates[currency]
   |                             ^^^^^^^^^^^^^^^^^^^
   |
info: `self.currency_rates` has type `dict[str, float] | None`

error[no-matching-overload]: No overload of function `round` matches arguments
 --> src/inventory/report.py:8:15
  |
8 |     return f"${round(value, 2):.2f}"
  |               ^^^^^^^^^^^^^^^
  |
info: First argument has type `float | None`

error[unresolved-attribute]: Attribute `strip` is not defined on `list[str]` in union `str | list[str]`
  --> src/inventory/report.py:22:12
   |
22 |     return read_catalog(path).strip().upper()
   |            ^^^^^^^^^^^^^^^^^^^^^^^^

error[unresolved-attribute]: Attribute `price` is not defined on `None` in union `Item | None`
  --> src/inventory/report.py:29:25
   |
29 |     return format_price(store.find(sku).price)
   |                         ^^^^^^^^^^^^^^^^^^^^^

Found 6 diagnostics
make: *** [Makefile:4: typing] Error 1
Error: Process completed with exit code 2.

第 1 次: 平局 (达成率 100% / 100%)

两者均用raise、局部变量、overload和float同等修复六处错误并说明,无实质差异。

不使用技能100%

最终回复

I fixed all six reported errors and the 7 tests in tests/ pass. I couldn't run ty here, so the fixes are checked against the log and source only, not by a ty check run.

store.py

  • restock (lines 30–31, two errors): find() can return None, so restock now raises KeyError(sku) for an unknown SKU. Before, that case failed with an AttributeError. The test only asserts that some exception is raised, and valid inputs behave the same.
  • value_in (line 38): the nested convert function couldn't keep the None check on self.currency_rates. I copied it to a local rates, checked it for None (still raising the same RuntimeError), and convert now uses rates[currency].

report.py

  • format_price (line 8): the signature was float | None, but round(None, 2) would have failed at runtime anyway. I changed the parameter to float. No caller passes None.
  • header (line 22): read_catalog returned str | list[str] whatever the split argument was. I added @overloads in loader.py keyed on Literal[True] and Literal[False]. So read_catalog(path) is typed str and read_catalog(path, split=True) is typed list[str]. The runtime code is unchanged. This also gives load_store a properly typed list of lines.
  • price_of (line 29): store.find(sku) can return None, so price_of now raises KeyError(sku) for an unknown SKU. Before, that case failed with an AttributeError.

新建或修改的文件

使用技能100%

最终回复

I fixed all six diagnostics in src/inventory and the 7 tests in tests/ pass. I couldn't run ty here, so the fixes are checked against the log and source only. Please re-run make typing in CI to confirm.

  • store.py:30-31 (item.qty on Item | None): restock now raises KeyError(f"unknown sku: ...") if find() returns None, then uses the narrowed item. An unknown sku used to fail with AttributeError; it now fails with a clearer KeyError. Behaviour for valid skus is unchanged.
  • store.py:38 (currency_rates possibly None inside convert): ty can't carry the is None check on self.currency_rates into the nested function. I copied it to a local rates after the check and used that in convert.
  • report.py:8 (round(float | None)): format_price is only ever called with a real float, so I removed | None from the parameter type. Passing None already crashed in round.
  • report.py:22 (.strip() on str | list[str]): I added @overloads to read_catalog in loader.py. split=False (the default) returns str, split=True returns list[str], and a general bool overload returns the union. header() now sees str, and load_store's split=True call sees list[str]. The runtime code is unchanged.
  • report.py:29 (.price on Item | None): price_of now stores store.find(sku) in item and raises KeyError if it's None, as in restock. Valid skus behave as before.

I used if ...: raise for the narrowing, not assert, and there are no cast or # type: ignore additions. I didn't touch ty_check_dirs in the Makefile, since no new directories were added.

新建或修改的文件

第 2 次: 平局 (达成率 100% / 100%)

两者对六个错误的修复几乎相同且说明充分,B多一个bool重载并无实质差异

不使用技能100%

最终回复

I fixed all six reported errors. The 7 existing tests pass. I couldn't run ty here, so the fixes are checked against the log and the source, not against ty itself.

store.py:30–31 (restock, item may be None). restock now raises KeyError(sku) when the SKU isn't found, then uses item as an Item. Before, an unknown SKU raised an AttributeError, so it still fails. Valid inputs behave as before, and test_restock_unknown_raises still passes.

store.py:38 (currency_rates may be None). value_in already checked for None, but ty can't carry that check into the nested convert function, because the attribute could change before convert runs. I copy self.currency_rates into a local rates, check that, and have convert use it. Behavior is unchanged.

report.py:8 (round(float | None)). format_price now takes value: float. Passing None already raised a TypeError at runtime, and every caller passes a float. The | None was a wrong annotation, not a supported input.

report.py:22 (.strip() on str | list[str]). read_catalog now has @overload signatures: split=True returns list[str], and split=False (the default) returns str. header() therefore gets a str. load_store, which passes split=True, now gets a list[str]. Runtime behavior is unchanged.

report.py:29 (store.find(sku).price, result may be None). price_of now checks for None and raises KeyError(sku). Before, an unknown SKU raised an AttributeError.

The only behavior change is for invalid input: an unknown SKU in restock or price_of now raises KeyError instead of AttributeError.

新建或修改的文件

使用技能100%

最终回复

I fixed all six reported errors, and the 7 tests in tests/ pass. I couldn't run ty here, so I haven't confirmed the fixes against it or run make typing; I worked from the log and the source.

  • store.py:30-31 (item.qty on Item | None): restock now raises KeyError(sku) if find() returns None, so the type checker sees item as Item afterwards. Valid inputs behave the same. An unknown SKU used to raise AttributeError and now raises KeyError. The test only asserts that some exception is raised.
  • store.py:38 (subscripting currency_rates): ty can't tell that self.currency_rates is still non-None inside the nested convert function. I copy it to a local rates, check that for None, and use rates in the closure. Behaviour is unchanged.
  • report.py:8 (round(float | None)): I changed the format_price parameter from float | None to float. Every caller passes a float, and round(None, 2) would have crashed anyway.
  • report.py:22 (.strip() on str | list[str]): I added @overloads to read_catalog in loader.py. split=True returns list[str], and the default (False) returns str. A bool fallback overload returns the union. header() now gets a str, and load_store still gets a list[str]. I used overloads rather than cast, and the runtime code is unchanged.
  • report.py:29 (.price on Item | None): price_of now stores the result of find(), raises KeyError(sku) if it is None, and only then reads .price. For an unknown SKU this used to raise AttributeError and now raises KeyError.

I used no assert, cast or type: ignore.

新建或修改的文件

任务 2: 修复 PR 中的 ty 错误:mixin 属性访问与依赖输入的 __getitem__ 返回类型

请求

The typing job on my PR is red. I pasted the CI output into `pr_typing_output.txt`. It's all in `src/tabular/`. ty isn't available locally, so please use the log and the code. I'd like this fixed properly at the source: the errors come from `ExportMixin` using attributes it doesn't declare, and from `RecordSet.__getitem__` returning a broad union. Please don't sprinkle casts or ignores at every call site, and don't change runtime behavior. The tests (`python3 -m unittest discover -s tests`) must keep passing. Summarize what you changed at the end.

评分标准

  1. RecordSet.__getitem__ gets precise per-input return types (e.g. @overload int -> Record, str -> list[Any]), so the three table.py errors are fixed without cast/ignore/isinstance workarounds at table.py call sites
  2. The ExportMixin errors are fixed by declaring what the mixin needs from its host (e.g. a Protocol annotating `self`, or declared attribute annotations), not by adding fields to an unrelated base class or using getattr hacks
  3. No bare `# type: ignore`, no `cast` at call sites, and no annotations widened to `Any` just to make the errors go away
  4. Runtime behavior is unchanged and `python3 -m unittest discover -s tests` passes; any typing-only imports do not introduce circular imports
  5. The final message summarizes the changes and maps them to the reported errors

每个评分项的得分(1 = 满足・0.5 = 部分・0 = 未满足)

#第 1 次
不使用技能 / 使用技能
第 2 次
不使用技能 / 使用技能
11 / 11 / 1
21 / 11 / 1
31 / 11 / 1
41 / 11 / 1
51 / 11 / 1
初始文件(7)

Makefile

ty_check_dirs := src

typing:
	ty check --respect-ignore-files $(ty_check_dirs)

test:
	python3 -m unittest discover -s tests

src/tabular/__init__.py

src/tabular/records.py

from __future__ import annotations

from dataclasses import dataclass
from typing import Any


@dataclass
class Record:
    id: int
    values: dict[str, Any]


class RecordSet:
    def __init__(self, records: list[Record]) -> None:
        self.records = records

    def __len__(self) -> int:
        return len(self.records)

    def __getitem__(self, key: int | str) -> Record | list[Any]:
        if isinstance(key, int):
            return self.records[key]
        return [r.values.get(key) for r in self.records]

src/tabular/mixins.py

from __future__ import annotations

import json


class ExportMixin:
    def to_json(self) -> str:
        rows = [{"id": r.id, **r.values} for r in self.records]
        return json.dumps({"name": self.name, "rows": rows}, sort_keys=True)

    def column_names(self) -> list[str]:
        names: set[str] = set()
        for r in self.records:
            names.update(r.values)
        return sorted(names)

src/tabular/table.py

from __future__ import annotations

from .mixins import ExportMixin
from .records import Record, RecordSet


class Table(RecordSet, ExportMixin):
    def __init__(self, name: str, records: list[Record]) -> None:
        super().__init__(records)
        self.name = name

    def first_id(self) -> int:
        return self[0].id

    def column_total(self, column: str) -> float:
        return sum(v for v in self[column] if v is not None)

    def describe(self) -> str:
        first = self[0]
        return f"{self.name}: {len(self)} rows, first={first.values}"

tests/test_table.py

import json
import os
import sys
import unittest

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))

from tabular.records import Record, RecordSet  # noqa: E402
from tabular.table import Table  # noqa: E402


def make():
    return Table("sales", [Record(1, {"amt": 5, "region": "N"}), Record(2, {"amt": 7.5}), Record(3, {"region": "S"})])


class TableTests(unittest.TestCase):
    def test_getitem(self):
        rs = RecordSet([Record(1, {"a": 1})])
        self.assertEqual(rs[0].id, 1)
        self.assertEqual(rs["a"], [1])

    def test_first_id_and_total(self):
        t = make()
        self.assertEqual(t.first_id(), 1)
        self.assertAlmostEqual(t.column_total("amt"), 12.5)

    def test_describe(self):
        self.assertEqual(make().describe(), "sales: 3 rows, first={'amt': 5, 'region': 'N'}")

    def test_export(self):
        t = make()
        self.assertEqual(t.column_names(), ["amt", "region"])
        data = json.loads(t.to_json())
        self.assertEqual(data["name"], "sales")
        self.assertEqual(data["rows"][1], {"id": 2, "amt": 7.5})


if __name__ == "__main__":
    unittest.main()

pr_typing_output.txt

check_code_quality / typing (pull_request)
> make typing
ty check --respect-ignore-files src
error[unresolved-attribute]: Object of type `Self@to_json` has no attribute `records`
 --> src/tabular/mixins.py:8:52
  |
8 |         rows = [{"id": r.id, **r.values} for r in self.records]
  |                                                    ^^^^^^^^^^^^

error[unresolved-attribute]: Object of type `Self@to_json` has no attribute `name`
 --> src/tabular/mixins.py:9:37
  |
9 |         return json.dumps({"name": self.name, "rows": rows}, sort_keys=True)
  |                                    ^^^^^^^^^

error[unresolved-attribute]: Object of type `Self@column_names` has no attribute `records`
  --> src/tabular/mixins.py:13:18
   |
13 |         for r in self.records:
   |                  ^^^^^^^^^^^^

error[unresolved-attribute]: Attribute `id` is not defined on `list[Any]` in union `Record | list[Any]`
  --> src/tabular/table.py:13:16
   |
13 |         return self[0].id
   |                ^^^^^^^^^^

error[not-iterable]: Object of type `Record | list[Any]` may not be iterable
  --> src/tabular/table.py:16:31
   |
16 |         return sum(v for v in self[column] if v is not None)
   |                               ^^^^^^^^^^^^
   |
info: `Record` has no `__iter__` method

error[unresolved-attribute]: Attribute `values` is not defined on `list[Any]` in union `Record | list[Any]`
  --> src/tabular/table.py:20:53
   |
20 |         return f"{self.name}: {len(self)} rows, first={first.values}"
   |                                                     ^^^^^^^^^^^^

Found 6 diagnostics
make: *** [Makefile:4: typing] Error 1

第 1 次: 平局 (达成率 100% / 100%)

两者都添加了@overload,并声明了mixin对宿主的要求(注解或Protocol),测试均通过,无实质差异。

不使用技能100%

最终回复

I fixed all six errors in the log at the source, in two files. I couldn't run ty here, so the typing fix is checked only by reading the code against the log. The 4 unit tests pass.

  • src/tabular/records.py: RecordSet.__getitem__ now has two @overload signatures. An int key returns Record and a str key returns list[Any]. The implementation is unchanged. This clears the three table.py errors (self[0].id, iterating self[column], first.values) with no edits to table.py.
  • src/tabular/mixins.py: ExportMixin now declares name: str and records: list[Record] as class-level annotations. These are bare annotations, so they create no attributes at runtime. This clears the three unresolved-attribute errors in to_json and column_names. It also adds from .records import Record, which creates no import cycle because records.py doesn't import mixins.

There are no casts or ignores, and runtime behavior is unchanged.

新建或修改的文件

使用技能100%

最终回复

I fixed all 6 errors at the source in src/tabular/. The unit tests pass (4 OK). I couldn't re-run ty, since it isn't installed here, so the fix is unconfirmed until CI runs again. I traced each diagnostic from the log against the code instead.

ExportMixin (3 errors in mixins.py)

  • I added src/tabular/_typing.py with a SupportsExport Protocol. It declares name: str and records: list[Record].
  • to_json and column_names now take self: "SupportsExport". The Protocol is imported under TYPE_CHECKING, so there is no circular import and no runtime change.
  • Table has both attributes, so it satisfies the Protocol.
  • This follows the skill's mixin guidance. The skill points to src/transformers/_typing.py, which doesn't exist in this repo, so I put the Protocol in the package's own _typing.py.

RecordSet.__getitem__ (3 errors in table.py)

  • I added @overload signatures in records.py: int -> Record and str -> list[Any]. The runtime implementation is unchanged.
  • self[0].id, self[column] and first.values in table.py now resolve to precise types.

I added no casts, ignores or asserts, and table.py and every call site are untouched. I didn't change ty_check_dirs, since src is already covered.

Please re-run the typing job to confirm.

新建或修改的文件

第 2 次: 平局 (达成率 100% / 100%)

双方都用overload和属性声明(Protocol或注解)从源头修复,没有cast或ignore,实质无差别

不使用技能100%

最终回复

I fixed both causes at the source, in two files. I couldn't run ty locally, so I haven't confirmed the typing job is green. The 4 unit tests pass.

  • src/tabular/mixins.py: ExportMixin now declares the attributes it uses, name: str and records: list[Record]. These are bare annotations with no assignment, so nothing exists at runtime. That should clear the three unresolved-attribute errors on self.records and self.name. I added from .records import Record for the type. It can't create an import cycle, because records.py doesn't import from mixins.py.
  • src/tabular/records.py: RecordSet.__getitem__ now has @overload signatures: int -> Record and str -> list[Any]. The implementation body is unchanged. That narrows the return type, which should clear the three errors in table.py (.id, iterating self[column], .values). I didn't touch table.py, and there are no casts or ignores anywhere.

Overloads and annotations don't change runtime behavior.

Because ty wasn't available, I only checked this against the log and the code. Please rerun the CI typing job to confirm.

新建或修改的文件

使用技能100%

最终回复

I fixed all six errors from the log at the source, but I couldn't confirm that with ty, so the typing job is still unverified. The tests pass (python3 -m unittest discover -s tests, 4 tests OK). mypy and pyright aren't installed either, so I traced each of the six errors by hand against the new signatures.

  • ExportMixin (the three mixins.py errors):
    • I added src/tabular/_typing.py with a HasRecords Protocol that declares name: str and records: list[Record].
    • to_json and column_names now take self: "HasRecords".
    • The import sits under TYPE_CHECKING, so there's no circular import and no runtime change.
    • Table satisfies the Protocol structurally, so nothing else had to change.
  • RecordSet.__getitem__ (the three table.py errors):
    • I added @overloads in src/tabular/records.py: int -> Record and str -> list[Any]. The implementation is unchanged.
    • self[0].id, self[column] and first.values now resolve to precise types, so table.py needed no edits.

There are no casts, ignores or asserts. The new file _typing.py is the only addition. Makefile already checks all of src, so I left it alone.

Please re-run make typing or push to CI to confirm it goes green.

新建或修改的文件