Coverage for src/copytrading_engine/parsing/diagnostics.py: 100%
32 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""Safe validation metadata: retain rules and schema paths, never provider payloads."""
3from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError
5from copytrading_engine.shared.reading import PostReading
8def _contract_names(schema: object) -> set[str]:
9 """Every field name and tag in the reading contract: schema words, never post text."""
10 names: set[str] = set()
11 if isinstance(schema, dict):
12 names.update(schema.get("properties", {}))
13 names.update(schema.get("discriminator", {}).get("mapping", {}))
14 if isinstance(schema.get("const"), str):
15 names.add(schema["const"])
16 for value in schema.values():
17 names |= _contract_names(value)
18 elif isinstance(schema, list):
19 for value in schema:
20 names |= _contract_names(value)
21 return names
24FIELDS = frozenset({"reading"} | _contract_names(TypeAdapter(PostReading).json_schema()))
27class ValidationIssue(BaseModel):
28 model_config = ConfigDict(frozen=True, extra="forbid")
29 path: str
30 code: str
33def _from_reading(loc: tuple[int | str, ...]) -> tuple[int | str, ...]:
34 """A path from the reading on: the reader's answer wraps it in its output's own envelope
35 (the chat-or-reading choice, ADR-0012), which says nothing about what was wrong."""
36 return loc[loc.index("reading") :] if "reading" in loc else loc
39def validation_issues(error: Exception) -> tuple[ValidationIssue, ...]:
40 """PydanticAI wraps validation failures; inspect causes without serializing exceptions. A
41 reading check's failure (a GroundingError) carries its rule and path, so a post the reader
42 could not read twice says which check it failed."""
43 seen: set[int] = set()
44 current: BaseException | None = error
45 while current is not None and id(current) not in seen:
46 seen.add(id(current))
47 issue = getattr(current, "issue", None)
48 if isinstance(issue, ValidationIssue):
49 return (issue,)
50 if isinstance(current, ValidationError):
51 return tuple(
52 ValidationIssue(
53 path=".".join(
54 str(part) if isinstance(part, int) or part in FIELDS else "<extra>"
55 for part in _from_reading(item["loc"])
56 )
57 or "<root>",
58 code=item["type"],
59 )
60 for item in current.errors(
61 include_input=False, include_context=False, include_url=False
62 )[:10]
63 )
64 current = current.__cause__ or current.__context__
65 return ()