Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
refactor: dataclasses cleanup — off-wire @dataclass removals, NamedTuple upgrades, frozen DispatchOptions (#949)
Louis Choquel659fd9b5423a
diff --git a/TODOS.md b/TODOS.mdindex 2d875bbcc..ddb0dcfb4 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,181 +1,307 @@-# Implementation Plan — `feature/API-readiness-4`+# Data-Class Best-Practices Refactor — Working Ledger (`refactor/Dataclasses`)-Pipelex-side cleanup branch picking up the upstream tail of the API error-handling endeavour. The API consumer (`pipelex-api`, branch `feature/Adapt-to-pipelex-update-3`) has shipped through Phases 0-5 plus Phase A0 / A1 and is at a "finalize" moment; what remains for the API to fully discharge that endeavour is a handful of upstream-pipelex items. **This branch is those items.**+Give every data holder the right shape. Eradicate every stdlib `@dataclass` (HARD RULE 1) — but replace it with whichever form fits the site, NOT uniformly with `BaseModel`.----+**On the Temporal wire:** `BaseModel` or (after Phase 0) a pydantic dataclass — the two forms `BaseModelPayloadConverter` routes through kajson with type preservation.-## Cold-start reading order+**Off the wire, choose per-site** (this is the premise — pydantic dataclass is a first-class option here, often the lowest-churn one):-Read in this order to understand why this branch exists at all:+- **`NamedTuple`** — a small fixed immutable record replacing a bare tuple. Also the only safe form when a field is a bare `@runtime_checkable` Protocol / arbitrary non-pydantic type, because it skips validation (no `arbitrary_types_allowed` dance). Avoid when the type is returned in a union alongside a real `tuple` (a NamedTuple *is* a tuple → ambiguous `isinstance`).+- **pydantic dataclass** (`from pydantic.dataclasses import dataclass`) — a validated record that wants to keep dataclass idioms (`field(default_factory=...)`, computed `@property`, `frozen=`) with **minimal churn** (often just swap the decorator import). Wire-legal since Phase 0. **Use it ONLY for internal records that are constructed + field-read and never serialized.** A pydantic dataclass has no `.model_dump()` / `.model_validate()` methods — and "does this ever need serializing/dumping?" is the *deciding* question, not an afterthought: **if it ever needs dumping, make it a `BaseModel` from the start — do NOT reach for `TypeAdapter`.** Needing `TypeAdapter` means the wrong shape was picked; keep `TypeAdapter` out of the codebase entirely.+- **frozen `BaseModel`** — an immutable validated value object that needs the full model API (`model_dump`, validators, discriminated unions) OR sits in a layer that is uniformly `BaseModel` (e.g. `pipelex/builder/`), OR must stay type-distinct from a sibling `tuple` in a union return.+- **plain mutable `BaseModel`** — genuinely mutated in place AND wants the model API / layer-consistency; otherwise a non-frozen pydantic dataclass is the lighter choice for in-place-mutated records.-1. `wip/error-handling/README.md` — current state of error handling across pipelex; the high-level map.-2. `wip/error-handling/archive-todos-api-readiness-2.md` — the prior ledger (formerly the repo-root `TODOS.md`, archived 2026-05-28). This branch is the successor.-3. `../pipelex-api/wip/pipelex-changes.md` Stage 7 (items #10-#15) — the **authoritative per-item context** for five of the items on this branch. Each item there has a *What / Why / Where / How* writeup with empirical reproductions against the pinned pipelex. Do not re-derive that context here; consume it from there.-4. `../pipelex-api/TODOS.md` "Deferred / next-track work" → "Upstream-pipelex follow-ups" — names the same items at the API end, in the consumer's voice. Useful sanity check.-5. `wip/console-targets-and-agent-cli-stdout.md` and `wip/structured-logging/kickoff.md` — relevant background for the **webhook-delivery logging** item below; see the sequencing note in that section before starting.+Phase 0 is the foundation: generalize the Temporal converter (and kajson, in `../kajson`) so pydantic dataclasses are wire-legal, relaxing the "must be BaseModel on the wire" constraint. It is purely additive — no current wire type is a pydantic dataclass, so no existing payload changes. Everything after Phase 0 is off-wire and chosen per-site.-The `test_failed_webhook_log_includes_request_id_when_set` regression test already landed on the base (`feature/API-readiness-2`, commit `74b68bd7`) and is present in the working tree — do **not** re-add it. `git log feature/API-readiness-2..HEAD --oneline` shows this branch adds only planning docs on top of that base. Everything below is what to implement.+This ledger supersedes the completed `feature/API-readiness-4` ledger (archived to `wip/error-handling/archive-todos-api-readiness-4.md` on 2026-05-29). The original free-form plan that seeded this ledger was at `wip/data-class-best-practices-plan.md` (now removed; this file replaces it).----## What this branch is NOT+## Cold-start reading order-- Not the structured-logging refactor. That has its own kick-off doc and its own future branch (`refactor/structured-logging` or similar — see `wip/structured-logging/kickoff.md`).-- Not webhook signing. That's the cross-repo lockstep track owned by `wip/security/webhook-signing.md`.-- Not a `dev` merge train. If `dev` has moved, treat that as a separate prep step, not part of this plan.+A fresh session should read, in order:----+1. **This file, top to bottom.** It is the single source of truth for what to do and what's done.+2. **The "Session log" at the bottom** — the most recent entry is the handoff note from the last session: what landed, decisions taken, open questions, and the exact next action.+3. **`pipelex/temporal/temporal_data_converter.py`** — the converter being generalized in Phase 0. Read `BaseModelPayloadConverter.to_payload` / `from_payload`.+4. **`../kajson/kajson/json_decoder.py`** (`_apply_decoder_strategies`, ~line 196) and **`json_encoder.py`** (`default`, ~line 107) — the kajson dispatch Phase 0 extends.+5. The per-item detail sections below carry the *why* for each conversion; trust them but re-confirm any path/line reference against the current tree before editing (the off-wire audit was originally taken against a sibling `refactor/Paths` worktree).-## Items+----Six concrete items, all flagged in `pipelex-changes.md` Stage 7 or surfaced by the API-side `TODOS.md`. None blocks any API release on its own; together they discharge the upstream tail of the error-handling endeavour and let the API drop a small number of follow-up catches and workarounds.+## How to use this ledger++- **Checkboxes** track progress. Flip `[ ]` → `[x]` the moment a task lands (with its verification green), and append a one-line result (what changed + where) right under it. Do not batch.+- **Checkpoints are HARD STOPS.** When you reach a `🛑 HARD STOP` marker you MUST end the session after completing the context-save protocol below — do not roll into the next phase in the same session. They sit at natural handoff points where a coherent unit has landed and context has grown enough to warrant a fresh start.+- **Context-save protocol** (run at every hard stop, before ending the session):+ 1. Flip all completed checkboxes and write their one-line results.+ 2. Append a new **Session log** entry (template at the bottom): date, what landed, decisions taken, open questions, current code state (clean? mid-edit?), and the single exact next action for the next session.+ 3. Record any deviation from this plan inline in the relevant item, with the reason.+ 4. Confirm the tree is in a clean, committed (or clearly-described) state — the next session must be able to cold-start with zero memory of this one.+- **Verification commands** (run as noted per phase; never skip on a hard stop):+ - `make agent-check` — after every code change.+ - `make tb` — after any change touching boot/config/import paths.+ - `.venv/bin/pytest tests/integration/pipelex/temporal/` — after any change in `pipelex/temporal/` or the converter/kajson.+ - `make agent-test` — full suite, at the final gate.-Sequencing inside this branch is flexible — every item is independent except where called out. Suggested order is "smallest first to build momentum, then the two bigger ones."+----### 1. `ErrorDomain.is_input` (and siblings) — `@property` helpers on the enum+## Safety boundary — wire types must be BaseModel or pydantic dataclass++These types cross the Temporal wire directly or transitively. After Phase 0, each MUST be a `BaseModel` **or** a pydantic dataclass — the two forms `BaseModelPayloadConverter` routes through kajson with type preservation. A `NamedTuple`, stdlib dataclass, or arbitrary class here falls through to Temporal's stock JSON path and silently corrupts distributed execution or hard-fails deserialization.++**Every type on this list currently is, and should remain, a `BaseModel`.** They rely on machinery pydantic dataclasses don't provide as cleanly — discriminated unions, model validators, `model_dump`, the dynamic-class `__kajson_class_source__` mechanism. Phase 0 widens what is *legal* on the wire; it does NOT motivate converting anything already here. Do not convert these to pydantic dataclasses just because Phase 0 makes it possible.++- `PipeRunArg` (`pipelex/temporal/tprl_pipe/pipe_run_arg.py`) — direct argument of `WfPipeRun.run`. Already `BaseModel`.+- `PipeJob` (`pipelex/pipe_run/pipe_job.py`) — argument of `WfPipeRouter.run`; field of `PipeRunArg`.+- `PipeOutput` (`pipelex/core/pipes/pipe_output.py`) — return of both router workflows; field of `DeliveryActivityArg`.+- `DeliveryAssignment` (`pipelex/pipe_run/delivery_assignment.py`) — field of `PipeRunArg` and `DeliveryActivityArg`.+- `DeliveryActivityArg` (`pipelex/temporal/tprl_pipe/act_deliver.py`) — argument of `act_deliver`.+- `DeliveryStatus` (StrEnum, `pipelex/pipe_run/delivery_assignment.py`) — enclosed in `DeliveryActivityArg`; the StrEnum is fine, keep the enclosing type a `BaseModel`.+- `ErrorReport` (`pipelex/base_exceptions.py`) — field of `DeliveryActivityArg`.+- `AssembleGraphArg` (`pipelex/temporal/tprl_pipe/act_assemble_graph.py`) — argument of `act_assemble_graph`.+- `GraphSpec` (`pipelex/graph/graphspec.py`) — return of `act_assemble_graph`; field of `PipeOutput`.+- `PipelineRef` (`pipelex/graph/graphspec.py`) — embedded in the returned `GraphSpec`.+- `FlushTraceEventsArg` (`pipelex/temporal/tprl_pipe/act_flush_trace_events.py`) — argument of `act_flush_trace_events`.+- `JobMetadata` (`pipelex/pipeline/job_metadata.py`) — field of `PipeJob`.+- `GraphContext` (confirm path: `grep -rn "class GraphContext" pipelex/`) — field of `JobMetadata`, transitively on `PipeJob`.+- `WorkingMemory` (`pipelex/core/memory/working_memory.py`) — field of `PipeJob` and `PipeOutput`.+- `PipeRunParams` (`pipelex/core/pipes/pipe_run_params.py`) — field of `PipeJob`.+- `PipeAbstract` + all concrete pipe subclasses (`pipelex/core/pipes/pipe_abstract.py`; confirm) — the `pipe` field of `PipeJob`.+- `LibraryCrate` (confirm path: `grep -rn "class LibraryCrate" pipelex/`) — field of `PipeJob`.+- `Stuff` (`pipelex/core/stuffs/stuff.py`) — contained in `WorkingMemory`.+- `StuffContent` + the entire discriminated-union hierarchy (`pipelex/core/stuffs/stuff_content.py`): `TextContent`, `ImageContent`, `PdfContent`, `ListContent`, `StructuredContent`, `HtmlContent`, `NumberContent`, etc.+- `ImageContent` — return element of content-gen activities (`list[ImageContent]`).+- `PageContent` (confirm exact file) — return element of a content-gen activity (`list[PageContent]`).+- Page-view content payload(s) — returned by the render-page-views activity, embedded in `PageContent.page_view`. Confirm exact class name(s) by reading the activity return annotation and the `PageContent.page_view` field BEFORE touching anything nearby; highest-risk list-element serialization spot.+- `TraceEvent` + subtypes (`pipelex/tracing/...`) — element type of `FlushTraceEventsArg.events`. Confirm via the `events` annotation and `BufferingEventLog.drain` return type.-- [x] **Status:** Done (2026-05-28). Two pieces landed in `pipelex/base_exceptions.py`: (a) `ErrorDomain.is_input` as an exhaustive-`match` `@property` (the enum-level single source of truth), and (b) a module-level `error_domain_is_input(error_domain: ErrorDomain | str | None) -> bool` that coerces the serialized form and delegates to the property — paralleling the existing `error_domain_to_http_status(...)`. The function is the one the API actually consumes: both API call sites hold `error_domain` as `str | None` (`ErrorReport.error_domain` is typed `str | None`; the problem-document dict value is a plain str), so the bare `report.error_domain.is_input` the spec sketched would not type-check. Covered by `tests/unit/pipelex/exceptions/test_error_domain.py::TestErrorDomain` (`test_is_input` + `test_error_domain_is_input`). Only `is_input` landed — `is_config` / `is_runtime` deferred until a need surfaces. The API consumes this via the editable local dependency on this worktree (no PyPI pin bump needed); the API-side switch off `== ErrorDomain.INPUT` at `api/exception_handlers.py:204,253` is being made now.-**Authoritative spec:** `../pipelex-api/wip/pipelex-changes.md` item #14.-**Where:** `pipelex/base_exceptions.py` — the `ErrorDomain` `StrEnum`.+----Add `@property` helpers (`is_input`, and `is_config` / `is_runtime` as needs surface) so callers read state via `report.error_domain.is_input` instead of `report.error_domain == ErrorDomain.INPUT`. This is the canonical project remediation for single-state enum checks (see `python-standards.md`) — call sites stay one-liners, the enumeration lives in one place.+## Pre-flight — freeze the boundary (do before any edit)-**Sequence first:** every other item benefits from being able to use the helper at call sites it touches. Trivial change; ~20 lines + a test. The API-side `archive-todos-api-readiness-2.md` Phase 3 review Q9 left two call sites in `api/exception_handlers.py` deliberately on `== ErrorDomain.INPUT` waiting for this; one follow-up commit there will switch them once this lands.+- [x] Re-confirm the wire layer is clean: `grep -rn "@dataclass\|NamedTuple" pipelex/temporal/` returns nothing.+ - Result: only two matches, both off-wire and slated for later phases — `config_temporal.py:366` (`DispatchOptions`, Phase 5) and `tprl/namespace_check.py:50` (`RegistrationFailure`, Phase 4). No *wire* type is a dataclass/NamedTuple.+- [x] Resolve every "confirm path" entry in the safety boundary above (`GraphContext`, `LibraryCrate`, `PipeAbstract`, `PageContent`, page-view payload, `TraceEvent`) and pin the paths.+ - Result (all `BaseModel`): `GraphContext`=`pipelex/graph/graph_context.py:12`; `LibraryCrate`=`pipelex/libraries/library_crate.py:11`; `PipeAbstract`=`pipelex/core/pipes/pipe_abstract.py:46`; `PageContent`=`pipelex/core/stuffs/page_content.py:13` (StructuredContent); page-view payload = `PageContent.page_view: ImageContent | None` (line 15) → already-listed `ImageContent`; `TraceEvent`=`pipelex/tracing/trace_events.py:34`.----### 2. `EnvVarNotFoundError` should carry `error_domain = ErrorDomain.CONFIG`+## Phase 0 — Generalize the converter (+ kajson) to accept pydantic dataclasses-- [x] **Status:** Done (2026-05-28). Added `error_domain = ErrorDomain.CONFIG` as a class attribute on `EnvVarNotFoundError` in `pipelex/system/exceptions.py`, so its rendered `ErrorReport` / RFC 7807 problem document classifies as a config-domain failure (an operator sets the missing env var, not the caller). HTTP status is unchanged — both `None` and `CONFIG` map to 500. Covered by `tests/unit/pipelex/exceptions/test_class_level_metadata.py::TestClassLevelMetadata::test_error_domain` (new `env_var_not_found` parametrize case). The API consumes this via the editable local dependency on this worktree.-**Authoritative spec:** `../pipelex-api/wip/pipelex-changes.md` item #10.-**Where:** `pipelex/system/exceptions.py` (note: moved here from `pipelex/system/environment.py` during the Phase 6 import-path moves the API already adapted to — the spec doc still names the old path).+Goal: stop the converter from being the sole arbiter of domain-model shape. Today `BaseModelPayloadConverter` routes only `BaseModel` / `Optional[BaseModel]` / `list[BaseModel]` through kajson; everything else falls through to Temporal's stock JSON. Phase 0 widens that to pydantic dataclasses (and `Optional` / `list` of them). Scope is pydantic dataclasses ONLY — `NamedTuple` stays out (kajson flattens it to a bare JSON array, losing field names + type), stdlib dataclasses stay out (HARD RULE 1 eradicates them), arbitrary classes stay out (unsafe `__dict__`-replace path).-Today `EnvVarNotFoundError` is domain-less (it's a `ToolError`; neither parent sets `error_domain`). A missing required env var is the textbook `CONFIG`-domain failure — an operator, not the caller, fixes it. Add `error_domain = ErrorDomain.CONFIG` as a ClassVar so the rendered `ErrorReport` / RFC 7807 problem document classifies correctly. HTTP status is unaffected (both `None` and `CONFIG` map to 500).+### Layer 1 — kajson (`../kajson`, editable via this worktree's `uv.lock`)-This is the upstream half of the "original bug" the entire endeavour started from — a deployment that forgot to set `COMPLETION_CALLBACK_SECRET`. The API already classifies its own config faults as `CONFIG`; this brings pipelex-authored ones into alignment.-----+kajson v0.5.0 has no dataclass support and no dataclass tests. A pydantic dataclass currently only survives via the untested generic catch-all: encode via `__dict__` (`json_encoder.py` ~160), decode via `the_class(**the_dict)` (`json_decoder.py` ~293). The decode path is fragile — if validation raises there, the next line swallows it (`except Exception: pass`) and falls through to the unsafe `obj.__dict__ = the_dict` path, then to returning a raw dict. Silent corruption instead of a loud error.-### 3. `parse_concept_spec` should validate `structure` shape before iterating+- [x] **0.1** Add an explicit pydantic-dataclass branch in `_apply_decoder_strategies` (after the `Enum` / `BaseModel` branches, before the generic constructor), using `pydantic.dataclasses.is_pydantic_dataclass`. Reconstruct via the dataclass' pydantic validator (validates), and on `ValidationError` raise `KajsonDecoderError` loudly with dict context — mirroring the existing `BaseModel` branch (~line 265). No silent fall-through.+ - Result: added `is_pydantic_dataclass` import + the branch in `../kajson/kajson/json_decoder.py` (`return the_class(**the_dict)`, `except ValidationError → raise KajsonDecoderError(...) from exc`). Confirmed the prior behavior was silent corruption (bad dataclass payload returned a raw `dict`); now raises loudly.+- [x] **0.2** Add kajson round-trip tests in `../kajson/tests`: pydantic dataclass with (a) nested `BaseModel` field, (b) `Optional` field, (c) `list` of pydantic dataclasses, (d) `timedelta` field, (e) a subclass (type preservation); plus a negative test that a bad payload raises `KajsonDecoderError` (not silent corruption). Lock encode-via-`__dict__` with an explicit assertion rather than relying on the catch-all.+ - Result: `../kajson/tests/unit/test_pydantic_dataclass.py` (7 tests, all cases above + encode-via-`__dict__` metadata assertion + negative test). The negative test was the TDD red (DID NOT RAISE before 0.1, green after). Full kajson suite green (257 passed, 1 skipped); kajson `make agent-check` clean.+ - Follow-up from code review: the timedelta round-trip initially needed a band-aid (an earlier suite test, `test_json_encoder`, clears the process-global codec registry without restoring). Fixed the **root cause** instead — `test_json_encoder.py` / `test_json_decoder.py` autouse fixtures now snapshot the registry and restore it on teardown — and removed the band-aid. The new dataclass tests are order-independent without re-registering anything.+- [x] **0.3** Bump kajson version in `../kajson/pyproject.toml` + add a CHANGELOG entry (genuine new capability, benefits all kajson users).+ - Result: `0.5.0` → `0.6.0` + dated CHANGELOG entry. kajson is on its own `feature/Support-more-types` branch (versioned-only CHANGELOG convention — no `[Unreleased]`). Editable install means the pipelex venv serves the live source; installed metadata stays `0.5.0`, so the pipelex `kajson==0.5.0` pin is still satisfied. **Do NOT run `uv lock`/`uv sync` in this worktree until the pin is bumped** — the `==0.5.0` exact pin would conflict with the editable `0.6.0`. Pin bump stays bundled with the PyPI publish at the release gate (below).-- [x] **Status:** Done (2026-05-28). Two parsing functions now shape-validate raw caller input before iterating, raising typed `INPUT`-domain errors instead of leaking bare `AttributeError`/`TypeError`/`ValueError`. (a) `parse_concept_spec` (`concept_ops.py`) rejects a non-mapping `structure` and any field value that is neither a description string nor a field-spec mapping, raising `ConceptSpecError`. (b) `parse_pipe_spec` (`pipe_ops.py`) rejects a non-list `steps`/`branches` or a non-mapping entry within them, raising the new `PipeSpecError`; the raw-iterate logic moved into a shared `_normalize_sub_pipe_list(...)` helper. Both error classes now carry `error_domain = ErrorDomain.INPUT` + `_authors_caller_facing_message = True` — `ConceptSpecError` (`builder/concept/exceptions.py`) gained the domain (it was previously domain-less); `PipeSpecError` is new (`builder/pipe/exceptions.py`). Docstrings on both functions now list every exception actually raised. Covered by new cases in `tests/unit/pipelex/builder/operations/test_parse_concept_spec.py` and `test_parse_pipe_spec.py` (typed-error + INPUT-domain assertions). Verified end-to-end through both consumers: `pipelex-agent concept`/`pipe` now emit `{"error_type": "ConceptSpecError"|"PipeSpecError", "error_domain": "input"}` instead of a bug-looking bare type. Error doc pages regenerated (`pipelex-dev generate-error-pages`) — added `pipe-spec-error.md`, refreshed `concept-spec-error.md`; the run also picked up two pre-existing stale pages unrelated to this item (`env-var-not-found-error.md` from item #2, and a missing `async-execution-not-enabled-error.md`). The API consumes this via the editable local dependency on this worktree; the API-side narrow `/build/concept` + `/build/pipe` route catches are API-side follow-ups, not this branch.-**Authoritative spec:** `../pipelex-api/wip/pipelex-changes.md` item #11.-**Where:** `pipelex/builder/operations/concept_ops.py` — the `parse_concept_spec(...)` function.+### Layer 2 — the converter (`pipelex/temporal/temporal_data_converter.py`)-The function iterates `spec_data["structure"]` before calling `ConceptSpec.model_validate(...)`. Non-dict `structure`, or fields that are neither string nor dict, leak bare `AttributeError` / `TypeError` (undocumented; the docstring only declares `ValidationError`). Empirical reproductions live in the spec doc.+Widen two predicates; leave the `BaseModel` path byte-identical.-Fix is upstream shape validation — either raise a typed `PipelexInputError`-equivalent, or a `pydantic.ValidationError` via a thin `model_validate(...)` over the raw input shape before the iteration. Update the docstring to list every exception actually raised.+- [x] **0.4** `to_payload` (~line 56): factor `_is_kajson_wire_value(value) -> bool` = `isinstance(value, BaseModel) or is_pydantic_dataclass(type(value))`; route both single-value and first-element-of-list cases through kajson when it holds. `BaseModel` check first (hot-path short-circuit). The `__kajson_class_source__` lookup stays (it's `None` for dataclasses — harmless).+ - Result: added `_is_kajson_wire_value(value: object)` + extracted `_kajson_to_payload(value, source_type_holder)` (shared by the scalar and list branches) + `_first_kajson_list_element` (list probe). BaseModel path is byte-identical (locked by the 0.6 regression guard). **Type-checking deviation:** the original relied on inline `isinstance` narrowing; the predicate is non-narrowing, so to keep pyright-strict `reportUnknownArgumentType` happy I typed the value predicate param as `object` (so `type(value)` is `type[object]`, not `type[Unknown]`) and kept `value` explicitly `Any` at call sites.+- [x] **0.5** `from_payload` (~line 138): factor `_is_kajson_type(tp) -> bool` = `BaseModel` subclass **or** `is_pydantic_dataclass(tp)`; reuse it in all three hint checks (scalar, `Optional`, `list`). `_restore_class_source` only fires when `class_source_code is not None` (BaseModel-only), so dataclasses correctly skip it.+ - Result: added `_is_kajson_type(type_hint)`, generalized `_unwrap_optional_base_model` → `_unwrap_optional_kajson_type`, and reused `_is_kajson_type` in all three checks (scalar, Optional, list). `is_pydantic_dataclass` is runtime-safe on non-class hints (returns `False`), so the inner `Optional`/`list` args need no guard. One `cast("Any", type_hint)` collapses the post-`isinstance` `Any | type[Unknown]` for the typed probe.-The API today cannot safely catch these at the route — `AttributeError` / `TypeError` are also the types a real programming bug would raise, so a route-level catch would mask genuine bugs. Once this lands, the API's `/build/concept` route gets a narrow, typed catch.+Perf note: adds one cheap `is_pydantic_dataclass()` check per conversion, behind the `BaseModel` short-circuit. Negligible; no benchmark needed (changes no existing payload).-While here: sweep `pipelex/builder/operations/*.py` for the same pattern (raw-iterate-then-validate). `parse_pipe_spec` has it too — it iterates `spec_data["steps"]` / `spec_data["branches"]` and calls `dict(step)` on each entry before `model_validate`, so a non-list `steps` / `branches` or non-mapping entries leak bare `TypeError` / `ValueError` ahead of validation. Route those through the same narrow shape-validation path before iterating. (The bad-`pipe_type` `ValueError` is a separate, already-documented case — that one is narrow enough to leave.)+### Test perimeter (three layers — most safety-critical seam)----+- [x] **0.6** Converter unit round-trip: call `to_payload` / `from_payload` directly for a pydantic dataclass and for `Optional[...]` / `list[...]` hints; assert value + concrete type survive. **Regression guard:** assert a `BaseModel` payload is byte-identical to before (the untouched path).+ - Result: `tests/integration/pipelex/temporal/data_converter/test_data_conv_dataclass.py` — scalar / `X | None` / `list[X]` dataclass round-trips (concrete type + nested BaseModel preserved) + a byte-identical guard for a plain BaseModel (metadata == `{encoding}`, data == `kajson.dumps(model)`). 8 tests in the dir pass.+- [x] **0.7** Temporal integration round-trip: a `@workflow.defn` / `@activity.defn` taking and returning a pydantic dataclass, exercised through the in-process test server (`tests/integration/pipelex/temporal/`).+ - Result: `tests/integration/pipelex/temporal/test_wf_dataclass_roundtrip.py` — `WfEchoDataclassPayload` forwards a `@pydantic_dataclass` (with nested BaseModel + `timedelta` fields) through an activity via `WorkflowEnvironment.start_local` + `Worker`; asserts type preserved end-to-end. Green. Broader temporal integration suite (non-inference) re-run clean: 136 passed, 4 pre-existing xdist-race xpass, no regressions.-### 4. `LocalStorageProvider` should wrap raw `OSError` as a `StorageLocalError`+### Cross-repo wiring-- [x] **Status:** Done (2026-05-28). Added `StorageLocalError(StorageError)` (with `_declared_title = "Local storage error"`) to `pipelex/tools/storage/exceptions.py`, paralleling `StorageS3Error` / `StorageGcpError`. Both filesystem methods in `local_storage_provider.py` now wrap raw `OSError`: `_store` wraps the `mkdir` + `aiofiles.open(...).write(...)` block (`ENOSPC` / `EACCES` / `EROFS` / `FileExistsError` / `EIO` → `StorageLocalError`); `_load_with_metadata` wraps the `aiofiles.open(...).read()` call, with an explicit `except FileNotFoundError` branch first that routes the TOCTOU window (file removed between the `exists()` check and the open) to `StorageFileNotFoundError`, so "file not found" stays the same typed error regardless of timing, and a generic `except OSError` → `StorageLocalError` for the rest (`PermissionError` / `IsADirectoryError` / `EIO`). `public_url` does no filesystem I/O, so it's untouched. Docstrings updated to list `StorageLocalError`. Covered by three new cases in `tests/unit/pipelex/tools/storage/test_local_storage_provider.py` (store→`FileExistsError` via blocker file, load→`IsADirectoryError` via dir-at-key, load→TOCTOU `FileNotFoundError` via `aiofiles.open` monkeypatch) — each asserts the typed wrapper and `__cause__` is an `OSError`. Error doc page generated (`pipelex-dev generate-error-pages`) — added `storage-local-error.md`, refreshed `index.md`; no incidental stale pages this run. The API consumes this via the editable local dependency on this worktree; the API-side narrow storage-route catches are API-side follow-ups, not this branch.-**Authoritative spec:** `../pipelex-api/wip/pipelex-changes.md` item #12.-**Where:** `pipelex/tools/storage/local_storage_provider.py` — `_store` and `_load_with_metadata`.+This worktree's `uv.lock` pins kajson as `{ editable = "../kajson" }` (confirmed) — changes in `../kajson` are picked up live, no publish needed for dev/test. `pipelex/pyproject.toml` still declares `kajson==0.5.0`; that specifier only bites at pipelex release time.-Today, `ENOSPC` / `EACCES` / `EROFS` / `EIO` / `FileExistsError` / TOCTOU window after `file_path.exists()` all escape as raw `OSError`. Add a narrow `try/except OSError as exc: raise StorageLocalError(msg) from exc` around the filesystem calls — mirroring the wrapping already done by `S3StorageProvider` / `GcpStorageProvider`. Empirical reproductions are in the spec doc.+- [x] **0.8** After 0.4/0.5 land, update the "Safety boundary" heading wording in this file from "must be BaseModel" framing to the now-true "BaseModel or pydantic dataclass" (already drafted above — just confirm it matches what shipped).+ - Result: confirmed — the heading and body wording ("each MUST be a `BaseModel` **or** a pydantic dataclass — the two forms `BaseModelPayloadConverter` routes through kajson") matches what shipped (`_is_kajson_wire_value` / `_is_kajson_type` route both forms through kajson). No edit needed.+- [x] **0.9** Verify the editable kajson install survives any `uv sync` run during this phase (re-check `uv.lock` line for `editable = "../kajson"`).+ - Result: `uv.lock` still pins `source = { editable = "../kajson" }` (line 1972); no `uv lock`/`uv sync` was run. Verified the pipelex worktree's `.venv` serves the live kajson source (imports the new decode branch; bad payload raises `KajsonDecoderError`) with installed metadata still `0.5.0`. **Caveat:** a `uv lock` regeneration WOULD now conflict (editable `0.6.0` vs `kajson==0.5.0` pin) — defer until the release-gate pin bump.-**Decision:** Add a new `StorageLocalError(StorageError)` to `pipelex/tools/storage/exceptions.py`, paralleling `StorageS3Error` / `StorageGcpError` (with a `_declared_title = "Local storage error"`). Keeps per-backend differentiation consistent across the storage abstraction.+**Verify Phase 0:** kajson dataclass tests green · converter unit round-trip green (incl. BaseModel-unchanged regression guard) · `.venv/bin/pytest tests/integration/pipelex/temporal/` green · `make agent-check` + `make tb` clean.-Pair-test with item #5 (S3) — both deliver on the same storage-abstraction contract; same review can cover both.+> 🛑 **HARD STOP 1 — Converter generalized.** Foundation in place across two repos; wire rule is now "BaseModel or pydantic dataclass." Run the context-save protocol and END THE SESSION. The off-wire refactor (Phases 1–5) builds on top without depending on Phase 0's internals, so a fresh session can pick up cleanly. **Release-gate to record (not dev-blocking):** publish the new kajson to PyPI + bump the `kajson==` pin in `pipelex/pyproject.toml` before pipelex ships a release depending on the new feature.----### 5. `S3StorageProvider` should catch the full `BotoCoreError` hierarchy+## Phase 1 — ~~Capture perf baseline~~ → DROPPED after review (no production code changes either way)-- [x] **Status:** Done (2026-05-28). All three methods in `s3_storage_provider.py` now wrap the entire `BotoCoreError` hierarchy instead of only `NoCredentialsError` / `EndpointConnectionError`. In `_load_with_metadata` and `_store` the final `except (NoCredentialsError, EndpointConnectionError)` branch was broadened to `except BotoCoreError as exc: raise StorageS3Error(f"S3 backend error for key '{key}': {type(exc).__name__}") from exc`, sitting after the `ClientError` *sibling* branch (kept separate — `ClientError` is not a `BotoCoreError` subclass, verified empirically) and after the two service-specific `client.exceptions.NoSuchKey` / `NoSuchBucket` branches (unchanged). This closes the real-world leak: `ReadTimeoutError` / `ConnectTimeoutError` / `ConnectionClosedError` / `PartialCredentialsError` / `CredentialRetrievalError` / `ProxyConnectionError` (all `BotoCoreError` subclasses) previously escaped unwrapped; the most likely one, `ReadTimeoutError` on a slow/transient transfer, now surfaces as a typed `StorageS3Error`. `public_url`'s presign fallback widened from `except ClientError` → `except (BotoCoreError, ClientError)`, preserving the existing "if signing fails, serve the unsigned public URL" semantics for transport failures too. Per the decision, **no new sub-error class** — wrapping stays on the existing `StorageS3Error`, so no doc page work (generator confirms 0 drift: `Written: 0 · Unchanged: 245`). Covered by three new cases in `tests/unit/pipelex/tools/storage/test_s3_storage_provider.py` (`test_load_read_timeout_error_raises_s3_error`, `test_store_read_timeout_error_raises_s3_error`, `test_public_url_falls_back_to_public_url_on_botocore_error`); the three pre-existing `NoCredentialsError` / `EndpointConnectionError` tests were updated to assert the new message (`type(exc).__name__` in the text) and that `__cause__` is a `BotoCoreError`. The lower-priority `_get_session()`-outside-the-try side issue (a `BotoCoreError` from boto's own session-startup path could still escape) is left as-is — flag in the PR, don't gate on it. The API consumes this via the editable local dependency on this worktree; the API-side narrow storage-route catches are API-side follow-ups, not this branch.-**Authoritative spec:** `../pipelex-api/wip/pipelex-changes.md` item #13.-**Where:** `pipelex/tools/storage/s3_storage_provider.py` — `_load_with_metadata`, `_store`, and `public_url`.+**The whole perf-measurement effort (this phase + Phase 6's perf diff) was BUILT, then DROPPED on review (user decision, 2026-05-29).** The harness (`tests/perf/test_dataclass_forms_bench.py` + `tests/perf/baselines/dataclass_refactor_pre.json`) was deleted.-The provider catches only three `BotoCoreError` subclasses (`NoCredentialsError`, `EndpointConnectionError`) plus `ClientError` (which is a *sibling*, not a subclass, of `BotoCoreError`). Every other `BotoCoreError` subclass — `ReadTimeoutError`, `ConnectTimeoutError`, `ConnectionClosedError`, `PartialCredentialsError`, `CredentialRetrievalError`, `ProxyConnectionError`, … — escapes unwrapped. `ReadTimeoutError` is the most likely real-world leak (transient AWS networking).+Why it measured nothing useful:-Fix: broaden each `except` block from `(NoCredentialsError, EndpointConnectionError)` to `BotoCoreError`, keeping the `ClientError` branch as a separate sibling `except`. The two service-specific branches at the top (`NoSuchKey`, `NoSuchBucket`) stay. `public_url`'s `try/except ClientError → return public URL` fallback should likely widen the same way.+- It benchmarked **synthetic stand-ins**, not the real classes. The `DispatchOptions*` stand-ins matched the real field shape, but the "wire anchor" was a fake type that timed pydantic's native `model_dump_json`/`model_validate_json` — **NOT** the real Temporal wire path (`BaseModelPayloadConverter` → kajson with type-preservation metadata). So the one number meant to guard "no wire type got heavier" never touched the actual wire code.+- The costs are **negligible in context**: the only conversion that could plausibly regress is `DispatchOptions` (one build per activity dispatch, ~360ns form-delta) — dwarfed by the 10²–10³ ms network round-trip of the activity it configures.+- **None of the Phase 2/3/4 conversions sit on a hot path** (build-time, per-usage-event, dev-CLI, template-prep, worker-boot), so their construction speed never shows up in real behavior.-**Decision:** Keep wrapping as the existing `StorageS3Error(StorageError)` — no new sub-error class needed for the broadened catch. (Symmetric to item #4's `StorageLocalError` addition.)+Consequence for the `DispatchOptions` form decision (Phase 5): it now rests on **reasoning** (per-dispatch cost is negligible vs the network round-trip), not measurement — no perf data is needed to accept frozen `BaseModel`.-Lower-priority side issue noted in the spec doc: `_get_session()` runs outside every method's try block. Mention in the PR but don't gate on it.+- [x] **1.1 / 1.2** — built the harness + captured the pre-change baseline, then **removed both** per the review above.----### 6. Webhook-delivery SSRF DNS recheck+## Phase 2 — NamedTuple upgrades (off-wire bare-tuple returns, lowest risk)-- [x] **Status:** Done (2026-05-28). Greenfield `pipelex/tools/network/` package now closes the DNS-rebinding gap at webhook-delivery time. Three modules: (a) `host_rules.py` — `is_disallowed_ip(host)` (**deny-by-default**: `not addr.is_global`, so private/loopback/link-local — incl. `169.254.169.254` — /CGNAT `100.64/10`/shared/documentation/benchmarking/unspecified are all refused in one predicate, plus explicit `is_multicast`/`is_reserved` because `ipaddress` marks the `224.0.0.0/4` and `64:ff9b::/96` NAT64 ranges as `is_global`) + `is_disallowed_host(host)` (empty / known internal hostname `localhost`·`metadata`·`metadata.google.internal` / literal disallowed IP) — this is the single source of truth, and it is **stricter than the API's current enumerate-the-bad-ranges `_is_disallowed_host`** (the deny-by-default form closes a CGNAT leak the API check has; the API inherits the tightening when it re-points at this helper); (b) `exceptions.py` — `SsrfBlockedError(SecurityError)` with `error_domain = ErrorDomain.INPUT` (destination is caller-supplied — fixable by providing a public URL) and `_authors_caller_facing_message = True` (message names only the caller's own hostname, never the resolved private IP, so STRICT disclosure cannot confirm internal topology); (c) `ssrf_guard.py` — `SsrfGuardedTransport(httpx.AsyncHTTPTransport)` whose `resolve_to_allowed_ip(host, port)` short-circuits literal-disallowed hosts, resolves via `loop.getaddrinfo` (→ `socket.getaddrinfo`, monkeypatch-able), refuses if **any** resolved IP is disallowed (a mixed public/private resolution is itself a rebinding signal), maps a genuine `socket.gaierror` → `httpcore.ConnectError` (so a real DNS failure keeps its normal `httpx.ConnectError` → `WebhookDeliveryError` path), and connects to the **first vetted IP** (a literal → `getaddrinfo` does no DNS, so no rebind can slip between the check and the socket). **Seam choice:** on pinned `httpx` 0.28.1 / `httpcore` 1.0.9 there is no public `network_backend` kwarg and no resolver/DNS hook (event hooks are request/response only), so the guard wraps the connection pool's `_network_backend` in place via a custom `httpcore.AsyncNetworkBackend` (`SsrfGuardedBackend`). This intercepts only the TCP connect — TLS SNI / cert verification and the `Host` header keep using the origin **hostname** automatically, because `httpcore._async.connection.AsyncHTTPConnection._connect` derives `server_hostname` from the origin, not from what `connect_tcp` dials. One private-attr touch (`self._pool._network_backend`) carries the repo's established `# noqa: SLF001 # pyright: ignore[reportPrivateUsage]`. `delivery_executor._notify_webhook` now builds `httpx.AsyncClient(transport=SsrfGuardedTransport())`; `SsrfBlockedError` — a `SecurityError` — is deliberately **not** re-wrapped as `WebhookDeliveryError`, so it propagates and the delivery aborts loudly (security signals must not be swallowed by the domain-level `except httpx.RequestError`). Covered by `tests/unit/pipelex/tools/network/test_host_rules.py` (`TestHostRules` — literal-IP + hostname classification), `test_ssrf_guard.py` (`TestSsrfGuard` — public/private/literal/mixed/`gaierror` resolution + a real `httpx.AsyncClient` driven through the guarded transport aborting before any socket), and an end-to-end `test_webhook_aborts_on_dns_rebind_to_private_ip` in `tests/unit/pipelex/pipe_run/test_delivery_executor.py` (`execute()` aborts with `SsrfBlockedError` via a `socket.getaddrinfo` monkeypatch returning `169.254.169.254` — no live network). Error doc page generated (`pipelex-dev generate-error-pages`): `docs/errors/ssrf-blocked-error.md` + a one-line index refresh under `SecurityError`. `make agent-check` clean (pyright 0, mypy 0, ruff/plxt clean); targeted unit + integration-pipes suites green. **Naming deviation:** named `SsrfBlockedError` (generic — the transport guards any caller-supplied outbound URL, not only webhooks) rather than the spec's tentative `WebhookDeliverySsrfBlocked`, per the "(or whatever the typed error ends up named)" latitude; it still lives in `pipelex/tools/network/exceptions.py` per the error-location convention (not co-located with the helper). **API-side migration note:** the API doc says `from pipelex.tools.network import is_disallowed_host`, but `__init__.py` is kept empty per the no-re-export-in-`__init__` rule — the real import path is `from pipelex.tools.network.host_rules import is_disallowed_host`. **Tradeoffs to flag in the PR:** (1) the guard connects to the first vetted IP, forgoing httpx/anyio happy-eyeballs multi-IP fallback for webhooks (acceptable — pinning to a vetted IP is the whole point); (2) an egress allowlist / proxy at the deploy layer stays out of scope. The API-side narrow catch + re-point of `_is_disallowed_host` is an API-side follow-up, not this branch.-**Where:** `pipelex/pipe_run/delivery_executor.py` — wherever the webhook HTTP client (`httpx`) actually fires.+Verified-to-exist bare-tuple returns where named fields prevent positional swaps. All off the wire, already-typed, no validation needed → NamedTuple (not pydantic dataclass). Replace `from typing import Tuple` annotations; keep `NamedTuple` defs module-local next to the function (or shared where two siblings return the same shape).-The API's `api/schemas/models.py::_is_disallowed_host` only blocks literal private / loopback / metadata IPs **at request time**. A callback URL like `https://attacker.example/cb` passes API-side validation while its DNS record can resolve to `169.254.169.254` / `127.0.0.0/8` / `10.0.0.0/8` when the worker later fires the webhook. The fix belongs at delivery time:+- [x] **2.1** `_handle_basic_blueprint` (~line 336) + `_handle_refines` (~line 377) in `pipelex/core/concepts/concept_factory.py` — both return `(structure_class_name, refine_string)` with `refine_string: str | None`. Define ONE shared NamedTuple (e.g. `StructureNameAndRefine`) and reuse for both.+ - Result: added module-level `class StructureNameAndRefine(NamedTuple)` with `structure_class_name: str`, `refine_string: str | None`. Both methods now return it (6 return sites wrapped: 4 in `_handle_basic_blueprint`, 2 in `_handle_refines`). `_handle_refines`'s refine widened from `str` → `str | None` (its sole caller passes straight to `Concept.refines: str | None`, so type-safe). All 3 call sites use positional unpacking — unchanged. Confirmed `Concept.refines` is `str | None`.+- [x] **2.2** `split_cross_package_ref` (~line 197) in `pipelex/core/qualified_ref.py` — `(alias, remainder)`. Define e.g. `CrossPackageRef(alias, remainder)`. All call sites (`qualified_ref.py`, `core/domains/validation.py`, `core/concepts/concept_factory.py`, `core/concepts/validation.py`, `libraries/library.py`, `libraries/library_manager.py`, `libraries/pipe/pipe_library.py`, `libraries/concept/concept_library.py`) destructure into two locals — none relies on plain-tuple `len`/concat or passes the tuple onto a wire path. Safe.+ - Result: added module-level `class CrossPackageRef(NamedTuple)` with `alias: str`, `remainder: str`; `split_cross_package_ref` now returns `CrossPackageRef(alias=..., remainder=...)`. Re-grepped ALL 12 current call sites (the plan's list was close but I verified against the live tree) — every one uses positional 2-tuple unpacking (`alias, remainder = ...` or `_, remainder = ...`), so none changed. Core+pipes suite green (1323 passed).+- [x] **2.3** ~~`_get_is_prod_and_runtime_mode` in `pipelex/system/runtime_manager.py`~~ — **DOES NOT EXIST in current tree (skipped).** There is no `runtime_manager.py`; runtime mode lives in `pipelex/system/runtime.py` and is now fully **property-based** on a `RuntimeManager(BaseModel)` (`is_unit_testing`, `is_ci_testing`, `environment`, `run_mode` props) — no `(is_prod, runtime_mode)` tuple helper anywhere (grep-confirmed). The stale audit predates that refactor. Nothing to convert.+- [x] **2.4** ~~`_find_project_root` in `pipelex/config_manager.py`~~ — **DOES NOT EXIST in current tree (skipped).** `config_manager.py` is now `pipelex/system/configuration/config_loader.py` (`config_manager = ConfigLoader()`); its `find_project_root(start_dir) -> Path | None` returns just `Path | None` — the `found_root_marker` bool was dropped in the refactor, so there is no `(Path, bool)` tuple to convert (grep-confirmed no such tuple anywhere).-- A custom `httpx` transport / `httpcore` network backend whose connect step resolves the host, checks every resolved IP against the same private-host rule, and refuses to open the socket to a private / metadata destination. Note: on the pinned `httpx` 0.28.1, `AsyncHTTPTransport` exposes **no** resolver hook, and event hooks are `request` / `response` only — neither fires after DNS but before payload send — so a plain event hook cannot close the DNS-rebinding gap.-- Or an explicit resolve-and-connect flow: resolve the hostname (`socket.getaddrinfo`), validate each candidate IP against the rule, then connect to a vetted IP while preserving the original `Host` header / SNI — so a rebind between validation and send is impossible.-- Plus optionally an egress allowlist / proxy at the deploy layer (out of scope here — flag in the PR description so the deploy team sees it).+**Verify:** `make agent-check`; `make tb` (runtime_manager / config_manager touch boot paths). Temporal suite not required (nothing near the wire).+ - Result: `make agent-check` clean (pyright 0/0, mypy 1932 files); `make tb` 2 passed; targeted `tests/unit|integration/pipelex/core/` + `tests/integration/pipelex/pipes/` → 1323 passed, 1 xfailed (pre-existing known-bug marker).-The literal-host check on the API side stays as a cheap first line of defense.+----**Test fixture:** synthesize a webhook URL whose DNS resolves to a private IP (use a `socket.getaddrinfo`-style monkeypatch or a test resolver). Confirm the delivery aborts with a typed error (likely a new `WebhookDeliverySsrfBlocked` or similar) rather than completing the request.+## Phase 3 — Off-wire stdlib dataclass removals (no wire, no hot-path concern)-**Decision — rule placement.** Create a new `pipelex/tools/network/` package (greenfield — no `network` module exists today under `pipelex/tools/`) and put the rule in `pipelex.tools.network.is_disallowed_host(...)`. The API-side `_is_disallowed_host` in `pipelex-api/api/schemas/models.py` gets re-pointed at this helper, so the CIDR set lives in one place. Follow the error-location convention: `pipelex/tools/network/exceptions.py` for `WebhookDeliverySsrfBlocked` (or whatever the typed error ends up named) — do not co-locate the error with the helper.+HARD RULE 1: every stdlib `@dataclass` must go. These four are off-wire and not perf-critical. Form chosen per-site per the form-selection guide at the top of this file — **including pydantic dataclass**, which for records already written in dataclass style (`field(default_factory=...)` + computed `@property`) is the lowest-churn replacement (just swap the decorator import).----+- [x] **3.1** `_EventLogContext` — `pipelex/reporting/reporting_manager.py` → **NamedTuple**. Fields `event_log: EventLogProtocol`, `workflow_id`, `pipeline_run_id`. Private manager state in `ReportingManager._event_log_contexts`, set wholesale + popped, never field-mutated, never serialized. `event_log` is a bare `@runtime_checkable` Protocol instance stored as-is. NamedTuple avoids needing `arbitrary_types_allowed`.+ - Result: `@dataclass\nclass _EventLogContext` → `class _EventLogContext(NamedTuple)`; removed the now-unused `from dataclasses import dataclass`. Confirmed all uses are kwargs-construction (line ~90), dict store/pop, and attribute reads (`context.event_log.next_sequence()`, `.pipeline_run_id`, `.workflow_id`, `.event_log.emit(...)`) — no field mutation. Reporting unit suite green.+- [x] **3.2** `ErrorPagesReport` — `pipelex/errors/error_pages_generator.py` → **frozen `BaseModel`**. Four `list[Path]` fields via `Field(default_factory=list)` + a computed `total` `@property`. ~~Single full-kwargs construction, no in-place `.append` on instances → frozen holds.~~ `Path` serializes natively in pydantic v2; the computed-property + default_factory pattern argues for BaseModel over NamedTuple.+ - Result (FINAL, after 2nd review pass): **frozen pydantic dataclass** (`@pydantic.dataclasses.dataclass(frozen=True)`, `field(default_factory=list[Path])` ×4 + the `total` `@property`). This is the near-zero-diff replacement of the original `@dataclass(frozen=True)` — just swapped `from dataclasses import dataclass` → `from pydantic.dataclasses import dataclass` (kept `from dataclasses import field`). It's a dev-tool report with no model-API need, so a pydantic dataclass fits better than `BaseModel` (which I'd used in the first pass — reverted). **DEVIATION from plan rationale (still applies):** the plan claimed "single full-kwargs construction, no in-place `.append`" — STALE: it's built empty (`ErrorPagesReport()`) then **appended in place** (`_commit_page`/`_remove_orphans`). `frozen=True` (stdlib dataclass, pydantic dataclass, AND BaseModel) blocks attribute *reassignment*, NOT list mutation — `.append` works under all. Errors suite + type_uri-uniqueness test green (318 passed in the errors+jinja2+templating run).+- [x] **3.3** `CustomClassInfo` — `pipelex/builder/runner_code.py` → **frozen `BaseModel`**. Scalar fields (`class_name`, `domain_code`, `concept_code`) + two computed `@property` (`module_name`, `import_statement`). Builder/codegen artifact, never mutated, never a Temporal arg/return. `builder/CLAUDE.md` says the builder layer is uniformly pydantic; the properties make NamedTuple awkward.+ - Result: `@dataclass` → `class CustomClassInfo(BaseModel)` with `model_config = ConfigDict(frozen=True)`; both properties kept; removed `from dataclasses import dataclass`. Confirmed all uses are kwargs-construction (line ~116) + attribute reads + use as `dict[str, CustomClassInfo]` values — no field mutation, no instance hashing relied upon (frozen makes it hashable anyway, a superset). Builder suite green.+- [x] **3.4** `VariableReference` — `pipelex/tools/jinja2/jinja2_required_variables.py` → **mutable (non-frozen) `BaseModel`** with `filters: list[str] = Field(default_factory=list)`. CRITICAL: it is MUTATED IN PLACE — `_collect_variable_references` does `references[full_path].filters.append(filter_name)` on re-seen variables. In-place mutation rules out NamedTuple and any frozen form. Do NOT freeze it. (low-medium risk: preserve the append-after-construction contract.)+ - Result (FINAL, after 2nd review pass): **non-frozen pydantic dataclass** (`@pydantic.dataclasses.dataclass`, `path: str` + `filters: list[str] = field(default_factory=list[str])`). Near-zero-diff replacement of the original `@dataclass` — swapped `from dataclasses import dataclass` → `from pydantic.dataclasses import dataclass` (kept `field`), and used `list[str]` as the factory so no `# pyright: ignore` is needed (the original had one). Chosen over `BaseModel` (first pass — reverted): it's mutated in place and has no model-API need, so a pydantic dataclass is the lighter, more idiomatic fit. Confirmed the in-place `.filters.append(...)` works (pydantic dataclasses don't validate on attribute access/mutation, only on init). jinja2 var-ref unit tests + templating pipeline green.-### 7. Structured `event=webhook_delivery` / `event=webhook_failure` logging — **DEFERRED to structured-logging refactor**+**Verify:** `make agent-check` after each; `make tb` after the group.+ - Result: `make agent-check` clean (pyright 0/0, mypy 1932 files); `make tb` 2 passed; targeted `builder` + `tools` + `errors` + `reporting` suites → 1676 passed, 1 pre-existing skip.-- [x] **Status:** Closed-by-deferral on this branch (2026-05-28). Re-scoped onto the `refactor/structured-logging` branch.-**Where (for the deferral):** `wip/structured-logging/kickoff.md` "What good looks like" — event-name emission now in scope.+----The lines this item would have touched (`pipelex/pipe_run/delivery_executor.py` around 239 / 243 / 280 / 282 / 285) are exactly the lines the structured-logging refactor lists as deletion targets (`request_id_suffix` pattern, kwarg threading from commits `ceb018b5` / `07f9cce9`). Doing a narrow event-name pass on this branch would touch those lines twice.+## Phase 4 — Temporal-adjacent stdlib removal (low risk)-**Follow-up actions when the structured-logging branch starts:**+- [x] **4.1** `RegistrationFailure` — `pipelex/temporal/tprl/namespace_check.py` (~line 50) → **NamedTuple**. Fields `namespace: str`, `missing: tuple[str, ...]`, `rpc_error_message: str`. Off-wire admin plumbing — produced by `ensure_required_search_attributes_registered` at worker boot/setup, consumed only by `pipelex/cli/commands/setup_temporal_namespace_cmd.py` to format a runbook; never an `@activity.defn` return nor a wire field. **Implementer note:** a NamedTuple is also a `tuple`, so all consumers must keep discriminating the `RegistrationFailure | tuple[str, ...]` return via `isinstance(x, RegistrationFailure)` (CLI already does, ~line 148), never `isinstance(x, tuple)`.+ - Result: `@dataclass(frozen=True)` → **frozen `BaseModel`** (`model_config = ConfigDict(frozen=True)`). **DEVIATION from the plan's NamedTuple target — deliberately chose BaseModel over NamedTuple here** (decided on review, 2026-05-29): the return type is a union `RegistrationFailure | tuple[str, ...]`, and a NamedTuple IS a tuple, so a NamedTuple form makes BOTH arms tuples and leans entirely on every caller using `isinstance(x, RegistrationFailure)`. A `BaseModel` is **not** a tuple, so it stays cleanly type-distinct from the `tuple[str, ...]` success arm — strictly safer for this union. Its fields (`str`, `tuple[str, ...]`, `str`) are all pydantic-native, so NO `arbitrary_types_allowed` is needed. (A frozen *pydantic dataclass* would also have worked and been an even smaller diff — noted as the minimal-churn alternative.) Verified all consumers: 3 discrimination sites use `isinstance(..., RegistrationFailure)` (`setup_temporal_namespace_cmd.py:148`, `test_ensure_search_attributes_registered.py:117/140`, `integration/.../conftest.py:156`); none uses `isinstance(x, tuple)`; field access is `.namespace`/`.missing`/`.rpc_error_message`; construction is kwargs. Temporal unit+integration + setup-namespace CLI tests green (452 passed, 4 pre-existing xpass).-- Emit `event=webhook_delivery` / `event=webhook_failure` (and `event=storage_delivery` / `event=storage_failure` for symmetry) as structured fields once the new `log.info(msg, **fields)` surface lands. Document this in the kickoff doc's destination shape.-- Re-target the API-side TODO in `../pipelex-api/TODOS.md` "Deferred / next-track work" → "Upstream-pipelex follow-ups" from this branch onto the structured-logging branch.+**Verify:** `make agent-check`; `make tb`; `.venv/bin/pytest tests/integration/pipelex/temporal/`.+ - Result: `make agent-check` clean; `make tb` 2 passed; `tests/unit/pipelex/temporal/` + `tests/integration/pipelex/temporal/` → 445 passed, 4 xpassed (the documented pre-existing xdist class-registration race flakes — passes in isolation; no regressions). No stray temporal processes after the run.-The API-side T6 test (`pipelex-api/tests/unit/test_webhook_recovery.py`) pins error-rendering consistency, not event names, so the API is not blocked on event-name emission.+> 🛑 **HARD STOP 2 — All mechanical off-wire work done.** NamedTuple upgrades + four off-wire stdlib removals + the temporal-adjacent one have landed; the only remaining conversion is the reviewed `DispatchOptions`, which needs a without-temporal-extra import check that's cleanest in a fresh session. Run the context-save protocol and END THE SESSION.----## Out of scope (for this branch — recorded so they don't drift back in)+## Phase 5 — The reviewed item: `DispatchOptions` (needs human-review gate)-- **Structured-logging refactor.** Its own branch and PR. See `wip/structured-logging/kickoff.md`.-- **Webhook signing.** Cross-repo, lockstep. See `wip/security/webhook-signing.md`.-- **Item #15 — kajson crafted-marker exceptions.** Target repo is `kajson`, **not** `pipelex`. Belongs on a separate kajson PR. Spec lives at `../pipelex-api/wip/pipelex-changes.md` item #15; the API has a workaround in place (`_decode_body`'s widened catch tuple). Re-target there if Louis wants this on the same release train.-- **Console targets / agent CLI stdout discipline.** Independent track — `wip/console-targets-and-agent-cli-stdout.md`. Already landed in part on `fix/Log-target`.-- **Kajson untrusted-deserialization design pass.** Separate track at `../pipelex-api/wip/security/kajson-untrusted-deserialization.md` (workspace-level concern, needs `pipelex-app` + `pipelex-api-deploy` in the room).-- **API-side `pipe_code` / `pipeline_run_id` log enrichment.** Done in `pipelex-api`, not here.-- **API-side `RecursionError` in `_decode_body`.** Done in `pipelex-api`, not here.-- **API-side JSON log sink.** Done in `pipelex-api`, not here.+`DispatchOptions` — `pipelex/temporal/config_temporal.py` (~line 366) → **frozen `BaseModel`** with `model_config = ConfigDict(arbitrary_types_allowed=True)`. Off-wire (built only inside `WorkerConfig.resolve_dispatch`, immediately consumed by splatting `to_execute_kwargs()` into `workflow.execute_activity(...)`; never a workflow/activity arg/return, never a wire field). Holds a live `temporalio` `RetryPolicy` (non-JSON, `TYPE_CHECKING` forward ref) + the `to_execute_kwargs()` behavior method → `arbitrary_types_allowed` required, `frozen` matches the build-once-read-only lifecycle. NamedTuple/pydantic dataclass are wrong (the method + arbitrary SDK field; and a pydantic dataclass hits the SAME class-def-time annotation-resolution risk as BaseModel — Phase 0 does not change this).----+**Load-bearing invariant (the gate):** the module must import without `temporalio` installed. `temporalio` is imported only under `TYPE_CHECKING` and lazily inside `make_retry_policy`; `retry_policy: "RetryPolicy"` is a forward ref. A pydantic model builds a validator at class-def time and may try to resolve that annotation, risking pulling `temporalio` into the plain import path.-## Verification (when items land)+- [x] **5.1** GATE: verify the `temporalio`-not-installed import path — run `make tb` on an environment WITHOUT the temporal extra and confirm import + config-load succeed. Keep `RetryPolicy` under `TYPE_CHECKING` (or typed `Any`).+ - Result: **this worktree HAS the temporal extra**, so `make tb` here can't exercise the no-extra path (the prior session flagged exactly this). Used a **subprocess import-block** instead (a `sys.meta_path` finder that raises `ModuleNotFoundError` for `temporalio*`), then imported `config_temporal` and built `DispatchOptions` + the `Temporal` config submodels in that blocked interpreter — all green. **Key finding (the gate's real risk, now characterized):** a bare forward ref `retry_policy: "RetryPolicy"` (TYPE_CHECKING-only, no runtime binding) IMPORTS fine (pydantic *defers* the unresolved schema) but raises `PydanticUserError` the moment a `DispatchOptions` is **constructed** without the extra. Mitigation: an `else: RetryPolicy = Any` branch on the `TYPE_CHECKING` guard binds the annotation to `Any` at runtime, so the field needs no resolution and no `temporalio` — type-checkers still see the real `RetryPolicy`. Locked with a NEW permanent regression test `tests/unit/pipelex/temporal/test_dispatch_options_no_temporalio.py` (subprocess, temporalio blocked) — complements the existing AST scan in `test_config_temporal_optional_dep.py`, which would NOT catch a revert to a bare forward ref (it adds no import statement).+- [x] **5.2** Convert `DispatchOptions` to frozen `BaseModel(arbitrary_types_allowed=True)`, preserving `to_execute_kwargs()`. If the import-clean path proves infeasible, FALL BACK to a NamedTuple with `timedelta | None` fields + the `to_execute_kwargs` method (still off-wire-legal) — record the decision in the Session log.+ - Result: converted to a **frozen pydantic dataclass** (`@pydantic.dataclasses.dataclass(frozen=True)`), `to_execute_kwargs()` + field order unchanged, dropped `from dataclasses import dataclass` → `from pydantic.dataclasses import dataclass`. **DEVIATION 1 — `arbitrary_types_allowed` NOT needed (plan wording superseded):** with the `else: RetryPolicy = Any` binding the `retry_policy` field resolves to `Any` at runtime (no `isinstance`/arbitrary-type handling), so `frozen=True` alone suffices — `arbitrary_types_allowed=True` would be dead config. **DEVIATION 2 — final form is a frozen pydantic dataclass, NOT the plan's frozen `BaseModel`:** this went through TWO gate passes. (a) I first recommended pydantic dataclass; at the review gate the **user initially chose frozen `BaseModel`**, which I implemented (agent-check + full suite green on that form). (b) The user then observed the deciding point: **a frozen `BaseModel` needs the SAME `else: RetryPolicy = Any` binding** (both forms build a validator at class-def time), so BaseModel buys nothing on the import axis — and once the `else:` cost is unavoidable, the lower-churn pydantic dataclass (keep the decorator, no base-class change, no `model_config`) is the net win, and it fits the form guide's off-wire/never-serialized criterion exactly. **Switched to frozen pydantic dataclass.** Empirically reconfirmed import + construct under blocked `temporalio` (`is_pydantic_dataclass(DispatchOptions) == True`; frozen enforced via `FrozenInstanceError`). No NamedTuple fallback — the import-clean path is fully feasible. Behavior preserved: `test_resolve_dispatch.py` still builds real `RetryPolicy` objects and reads `.non_retryable_error_types` off them (14 targeted tests green incl. the new no-temporalio + AST optional-dep tests).-- `make c` + `make t` clean on every commit.-- For items #1-#5: add unit tests that pin the new behavior; the API-side test suite (`pipelex-api` with this branch pinned via the `[tool.uv.sources]` git rev) should also still pass — bump the pin and run `make c && make tp` over there as part of the PR.-- For item #6 (SSRF): integration-style test using a mock resolver. No live network.-- For item #7: depends on the sequencing decision.+**Verify:** `make agent-check`; `make tb`; `.venv/bin/pytest tests/integration/pipelex/temporal/`.----## Pin coordination with `pipelex-api`+## Phase 6 — Final gate-`pipelex-api/pyproject.toml` has a temporary `[tool.uv.sources]` git-rev pin pointing at this repo. When this branch reaches a shippable point:+(Perf-diff steps removed — the harness was dropped in Phase 1; the `DispatchOptions` form decision rests on reasoning, not measurement.)-1. Bump that `rev` to this branch's HEAD; run `make c && make tp` in `pipelex-api`.-2. Update the API-side `TODOS.md` "Deferred / next-track work" → "Upstream-pipelex follow-ups" — strike through the items that landed; keep the rest.-3. Update `../pipelex-api/wip/pipelex-changes.md` Stage 7 tracking table — flip the items' status.+- [x] **6.1** Final gate: **no stdlib `@dataclass` decorator** — `grep -rn "from dataclasses import" pipelex/ | grep -w dataclass` returns nothing (currently flags only `config_temporal.py`, cleared by Phase 5). **NOTE:** plain `from dataclasses import field` is ALLOWED and expected — the pydantic dataclasses (`error_pages_generator.py`, `jinja2_required_variables.py`) use `dataclasses.field(default_factory=...)` for their defaults; that helper is not a stdlib `@dataclass`, so do NOT grep for the bare `"from dataclasses import"` string (it false-positives on `field`). Then: full `make agent-check` · full `.venv/bin/pytest tests/integration/pipelex/temporal/` · `make agent-test`.+ - Result: `grep -rn "from dataclasses import" pipelex/ | grep -w dataclass` → **NONE** (HARD RULE 1 satisfied). Only `from dataclasses import field` remains (in `jinja2_required_variables.py` + `error_pages_generator.py`, the Phase 3 pydantic dataclasses) — allowed. `make agent-check` clean (ruff + plxt pass, **pyright 0/0**, **mypy 1930 files Success**) · `make tb` 2 passed · `tests/unit/pipelex/temporal/` + `tests/integration/pipelex/temporal/` → **419 passed, 4 xpassed** (the documented pre-existing pytest-xdist class-registration race flakes; pass in isolation), no stray temporal processes · **`make agent-test` full suite green (exit 0)**.+- [x] **6.2** Record the release-time follow-up (still pending): publish new kajson to PyPI + bump the `kajson==` pin in `pipelex/pyproject.toml`.+ - Result: **recorded, still pending (not dev-blocking).** kajson is bumped to `0.6.0` on its `feature/Support-more-types` branch and consumed editable from `../kajson` (live source serves the venv; installed metadata stays `0.5.0`, so the pipelex `kajson==0.5.0` pin holds). Release gate = publish kajson `0.6.0` to PyPI **then** bump the `kajson==` pin in `pipelex/pyproject.toml` to match, before pipelex ships a release that depends on the new pydantic-dataclass wire support. **Do NOT run `uv lock`/`uv sync` in this worktree until that pin bump** — the editable `0.6.0` would conflict with the `==0.5.0` pin.-The eventual end-state — flipping the API back to a PyPI floor (`pipelex>=<next-release>`) — is Louis-gated cross-repo release coordination; not part of this branch.+> 🛑 **HARD STOP 3 — Done.** Converter + kajson generalized (wire rule now BaseModel-or-pydantic-dataclass), all stdlib dataclasses removed, NamedTuple upgrades landed, temporal suite green, denylist types never converted away from BaseModel. Run the context-save protocol; final Session log entry records the Phase 0 test results, the `DispatchOptions` import-invariant outcome, and the pending release-gate.----## Decisions taken (2026-05-28)+## Leave-as-is (do NOT convert) — confirmed correct already-The open questions from the original cold-start session have been resolved. Recording here so they don't get re-litigated:+- `_ThinkingParams` — `pipelex/plugins/anthropic/anthropic_llm_worker.py` — a legitimate pydantic dataclass; off-wire, built+consumed within a single `_gen_text` call. Right tool already. (No longer the *only* pydantic dataclass — `ErrorPagesReport` (3.2), `VariableReference` (3.4), and `DispatchOptions` (5.2) joined it.)+- `ResultFile` (`pipelex/pipe_run/delivery_executor.py`), `SupportCheck` (`pipelex/cogt/img_gen/img_gen_param_support.py`), `StoredData` (`pipelex/tools/storage/storage_provider_abstract.py`), `PipeJobComponents` (`pipelex/pipe_run/pipe_job_factory.py`) — existing off-wire NamedTuples, all correct. (`PipeJobComponents` is a local unpack container for building `PipeJob`; anything embedded INTO `PipeJob` must still be wire-legal.)+- `iter_model_fields` (`pipelex/tools/misc/model_utils.py`, `pipelex/tools/typing/field_helpers.py`) and `items` (`pipelex/tools/misc/func_registry.py`) — keep as plain `Iterator[Tuple[...]]` (`dict.items()` convention). Best follow-up (separate refactor) is consolidating the two duplicate `iter_model_fields`, not changing their data form.+- `generate_from_structure_blueprint` (`pipelex/core/concepts/structure_generation/generator.py` ~line 78) — `(class_code, generated_class)`; one element is a live `type`. Firmly off-wire (a `type` can't round-trip the converter). NamedTuple would be harmless polish but optional — leave unless doing a broader codegen cleanup.++## Rejected — stale candidates that do NOT exist (do not re-propose)++Verified absent by full-tree grep + directory listing. Listed so a future session doesn't re-derive them: `pipelex/cli/run_helpers.py` (`execute_method_and_output`, `_resolve_inputs_and_memory`); `pipelex/cli/ui_helpers.py` (`prompt_for_methods_and_output`); `pipelex/cli/blueprint_writer.py` (the four `_write_*_stub_file`); the entire `pipelex/pipe_operators/ocr/` path; `pipe_func._resolve_content_generator_and_func_name`; `pipe_img_gen_factory._resolve_blueprint_and_factory`; `pipe_llm_blueprint._split_prompt_template`; `pipe_llm_factory._resolve_prompt_template_and_target`; `toml_utils.load_toml_from_path_and_get_content`; `template_provider_abstract._provide_template_text_and_source`; `file_utils._split_filepath_into_components(_with_extension)`; `hub.get_pipelex_hub_and_pipe_router`; `sub_pipe._resolve_condition_expression`; `library_manager.get_library_paths`; `concept_native.NativeConceptClassNamePair`; `concept_factory._parse_concept_string`; `stuff_factory.make_from_str` (returns a single `Stuff`, misdescribed); the removed `pipelex/cocktail/` directory (`_detect_action_type_and_agent`, `_parse_command_line`). The nearest real shape to the gone `blueprint_writer` is `structures_cmd._generate_structures_for_inline` returning `list[tuple[str, str]]` — a weak list-element case, separately scoped; do not fold the non-existent functions into it.++----1. **Item #7 sequencing — DEFERRED to structured-logging refactor.** See item #7 above. The lines it would have touched are explicit deletion targets in `wip/structured-logging/kickoff.md`. Doing the narrow event-name pass now means touching them twice.-2. **Item #6 SSRF rule placement — SHARED HELPER.** Create `pipelex/tools/network/` (greenfield) with `is_disallowed_host(...)`. The pipelex-api side re-points its `_is_disallowed_host` at this helper. Single source of truth for the disallowed CIDR set. See item #6 above for the error-location convention note.-3. **Items #4 / #5 error class shape — NEW `StorageLocalError(StorageError)`.** Mirrors the established per-backend pattern (`StorageS3Error` / `StorageGcpError` with `_declared_title`). Item #5 keeps wrapping as the existing `StorageS3Error`.-4. **`dev` merge — NOT NEEDED.** `git log feature/API-readiness-2..origin/dev --oneline` returns 0 commits. `dev` is not ahead.+## Session log (newest first)++Append one entry per session, especially at every hard stop. Template:++```+### YYYY-MM-DD — <phase / what this session covered>+- Landed: <checkboxes flipped + one-line results>+- Decisions: <any choice taken, with reason>+- Open questions: <anything unresolved for the next session>+- Code state: <clean & committed? mid-edit? which files dirty?>+- NEXT ACTION: <the single exact thing the next session should do first>+```++### 2026-05-29 — Phase 5 (`DispatchOptions`) + Phase 6 final gate complete — 🛑 HARD STOP 3 reached (refactor DONE)+- Landed: **5.1, 5.2, 6.1, 6.2** flipped with per-item results above. HARD RULE 1 fully satisfied — **zero stdlib `@dataclass` decorators remain in `pipelex/`**. Files touched this session:+ - `pipelex/temporal/config_temporal.py` — `DispatchOptions` `@dataclass` → **frozen pydantic dataclass** (`@pydantic.dataclasses.dataclass(frozen=True)`); added `else: RetryPolicy = Any` runtime binding on the `TYPE_CHECKING` guard; swapped `from dataclasses import dataclass` → `from pydantic.dataclasses import dataclass`.+ - `tests/unit/pipelex/temporal/test_dispatch_options_no_temporalio.py` — **NEW** runtime regression test (subprocess with `temporalio` blocked → import + construct `DispatchOptions`).+ - `TODOS.md` — this update.+- Decisions / deviations:+ - **Form decision: frozen pydantic dataclass, settled over two gate passes.** (a) I recommended a frozen pydantic dataclass (lowest churn from the stdlib `@dataclass`; matches the form guide rewritten last session; the plan's BaseModel-over-pydantic-dataclass reasons don't hold — identical import risk, methods fine on pydantic dataclasses). At the review gate the **user first chose frozen `BaseModel`**, which I implemented and verified (agent-check + full suite green). (b) The user then nailed the deciding point: **a frozen `BaseModel` needs the SAME `else: RetryPolicy = Any` binding**, so it has no import-axis advantage — and with the `else:` cost unavoidable, the lower-churn pydantic dataclass is the net win. **Switched to frozen pydantic dataclass** and re-verified end-to-end. Lesson for the form guide: when an arbitrary-SDK field forces an `else: Any` binding regardless, that cost is NOT a reason to prefer BaseModel — churn + the never-serialized criterion decide, both favoring the pydantic dataclass.+ - **`arbitrary_types_allowed` proved unnecessary** (plan said `BaseModel(arbitrary_types_allowed=True)`). With `else: RetryPolicy = Any`, the `retry_policy` field resolves to `Any` at runtime → no arbitrary-type handling needed; `@dataclass(frozen=True)` alone. Adding `arbitrary_types_allowed` would be dead config, so it was omitted.+ - **The real import invariant, characterized:** a bare forward ref imports (pydantic defers the schema) but raises `PydanticUserError` on *construction* without the extra. `DispatchOptions` is only ever constructed inside `resolve_dispatch` (which already requires `temporalio`), so even a bare ref wouldn't break a real no-extra deployment — but the `else: Any` binding makes import+construct robust regardless, and the new subprocess test locks it.+ - **No fallback to NamedTuple** — the import-clean frozen-BaseModel path is fully feasible (proven by the subprocess gate), so 5.2's fallback clause didn't fire.+ - **Inline-LSP noise reconfirmed:** during editing the inline pyright emitted `temporalio.* could not be resolved` on `config_temporal.py` + a STALE `"dataclass" is not defined` at a pre-edit line number. Authoritative `make agent-check` pyright = **0 errors**; grep confirmed zero `@dataclass`. Trust `make agent-check`, not the inline stream (as the prior sessions noted).+- Verification (all green): `make agent-check` (ruff+plxt clean, pyright 0/0, mypy 1930 files) · `make tb` 2 passed · temporal unit+integration 419 passed / 4 pre-existing xdist xpass / no stray procs · targeted 14-test slice (new no-temporalio + AST optional-dep + resolve_dispatch) green · **`make agent-test` full suite exit 0**.+- Open questions / carry-forward: **the deferred release gate (6.2) is the only thing left** — publish kajson `0.6.0` to PyPI + bump the `kajson==` pin in `pipelex/pyproject.toml`; until then do NOT run `uv lock`/`uv sync` in this worktree (editable `0.6.0` vs `==0.5.0` pin conflict). This is a release-time action, not part of the refactor.+- Code state: **COMMITTED + PUSHED** — commit `326d3232` on `refactor/Dataclasses` (tracks `origin/refactor/Dataclasses`), working tree clean. 3 files: `pipelex/temporal/config_temporal.py`, new `tests/unit/pipelex/temporal/test_dispatch_options_no_temporalio.py`, + this `TODOS.md`. `uv.lock` untouched. A post-implementation code-review pass (self + independent reviewer) fixed two doc-accuracy issues before the commit: the new test's stale "frozen Pydantic `BaseModel`" docstring → "frozen Pydantic dataclass", and trimmed the `DispatchOptions` docstring's BaseModel-vs-dataclass rationale (it lives here in the ledger, not in code). (This `TODOS.md` cold-start update lands as a small follow-up commit after `326d3232`.)+- NEXT ACTION: HARD STOP 3 — the data-class refactor is **DONE** (converter + kajson generalized, all stdlib dataclasses removed, NamedTuple upgrades + per-site forms landed, full suite green). The only remaining item is the release-time kajson PyPI publish + pin bump (6.2), to be done when pipelex cuts a release depending on the new wire support — not a dev task. END THE SESSION.++### 2026-05-29 — Phases 1–4 complete (NamedTuple upgrades + off-wire stdlib removals; perf harness built then dropped) — 🛑 HARD STOP 2 reached+- **POST-REVIEW ADJUSTMENTS (same session, after the user reviewed the work):** (1) **Perf harness DROPPED** — `tests/perf/` deleted entirely. It measured nothing realistic (synthetic stand-ins; the wire-anchor never used the real kajson converter path; costs negligible vs network-bound activities; nothing on a hot path). Phase 1 & Phase 6's perf-diff are struck; the `DispatchOptions` form decision now rests on reasoning. (2) **4.1 `RegistrationFailure` switched NamedTuple → frozen `BaseModel`** — a NamedTuple IS a tuple, which collides with the `tuple[str, ...]` success arm of its union return; a BaseModel stays type-distinct. (3) **2nd review pass — premise update + 3.2/3.4 → pydantic dataclass.** The user clarified the premise: the goal is the *right per-site shape*, and a **pydantic dataclass** (wire-legal since Phase 0) is a first-class off-wire option, often the lowest-churn one. Rewrote the top-of-file form-selection guide accordingly, then converted **3.2 `ErrorPagesReport` → frozen pydantic dataclass** and **3.4 `VariableReference` → non-frozen pydantic dataclass** (both near-zero-diff: keep `field(default_factory=...)` + properties, just swap the decorator import). Kept 3.1 NamedTuple (Protocol field), 3.3 BaseModel (uniform builder layer), 4.1 BaseModel (type-distinct from tuple). agent-check clean (pyright 0/0, mypy 1929); errors+jinja2+templating 318 passed; temporal + setup-namespace 452 passed/4 pre-existing xpass.+- Landed: **2.1, 2.2, 3.1, 3.2, 3.3, 3.4, 4.1** flipped with per-item results above. **1.1/1.2 built-then-dropped** (see above). **2.3 and 2.4 skipped — target code no longer exists in the current tree** (see deviations). Files touched (final state):+ - **Phase 2 (NamedTuple):** `pipelex/core/concepts/concept_factory.py` (+`StructureNameAndRefine`), `pipelex/core/qualified_ref.py` (+`CrossPackageRef`).+ - **Phase 3 (off-wire stdlib removals):** `pipelex/reporting/reporting_manager.py` (`_EventLogContext`→NamedTuple), `pipelex/errors/error_pages_generator.py` (`ErrorPagesReport`→frozen BaseModel), `pipelex/builder/runner_code.py` (`CustomClassInfo`→frozen BaseModel), `pipelex/tools/jinja2/jinja2_required_variables.py` (`VariableReference`→mutable BaseModel).+ - **Phase 4 (temporal-adjacent):** `pipelex/temporal/tprl/namespace_check.py` (`RegistrationFailure`→**frozen BaseModel**, post-review).+ - **Final per-site forms:** 3.1 `_EventLogContext`→NamedTuple · 3.2 `ErrorPagesReport`→**frozen pydantic dataclass** · 3.3 `CustomClassInfo`→frozen BaseModel · 3.4 `VariableReference`→**pydantic dataclass** · 4.1 `RegistrationFailure`→frozen BaseModel · 2.1/2.2→NamedTuple.+- Decisions / deviations:+ - **2.3 / 2.4 do not exist (the audit was stale — taken against the sibling `refactor/Paths` worktree).** `runtime_manager.py` is gone; runtime mode is now property-based in `pipelex/system/runtime.py`. `config_manager.py` is now `pipelex/system/configuration/config_loader.py` and its `find_project_root() -> Path | None` already dropped the `found_root_marker` bool. Both grep-confirmed absent — nothing to convert, so both checkboxes are marked done-by-absence (struck through inline).+ - **3.2 `ErrorPagesReport` — plan rationale was stale; final form is frozen pydantic dataclass.** Plan said "single full-kwargs construction, no in-place `.append`"; actually it's built empty and `.append`-ed in place. `frozen=True` blocks attribute *reassignment*, not list mutation, under stdlib-dataclass / pydantic-dataclass / BaseModel alike — so all three are behavior-equivalent for the append pattern. Final choice (2nd review pass): frozen **pydantic dataclass** — lowest churn (kept `field(default_factory=list[Path])`) and no model-API need.+ - **4.1 `RegistrationFailure` implementer-note verified, not assumed:** re-grepped all consumers; every discrimination is `isinstance(x, RegistrationFailure)`, none is `isinstance(x, tuple)`; success path returns plain tuples (never NamedTuple-subclass instances) so discrimination stays exact.+ - **Only ONE stdlib dataclass remains in `pipelex/`:** `pipelex/temporal/config_temporal.py` (`DispatchOptions`, Phase 5) — grep-confirmed. HARD RULE 1 is one conversion away from satisfied.+ - **Inline LSP noise (informational):** throughout, the editor's inline pyright kept emitting `temporalio.*` "could not be resolved" / "type unknown" diagnostics on temporal files I touched (and the Phase 0 files). That inline checker lacks the temporal extra; the authoritative `make agent-check` pyright resolves `temporalio` and reports **0 errors**. One round of jinja2 diagnostics was also stale (referenced pre-edit line numbers) — verified the file by re-reading; conversion was correct. Trust `make agent-check`, not the inline stream.+- Verification (all green): `make agent-check` clean (ruff+plxt, pyright 0/0, mypy 1932 files) · `make tb` 2 passed · core+pipes 1323 passed/1 xfailed (pre-existing) · temporal unit+integration 445 passed/4 xpassed (pre-existing xdist flakes, no stray procs) · builder+tools+errors+reporting 1676 passed/1 pre-existing skip.+- Open questions / carry-forward: (1) **deferred release gate still pending** — publish new kajson `0.6.0` to PyPI + bump `kajson==` pin in `pipelex/pyproject.toml`; do NOT run `uv lock`/`uv sync` in this worktree until then (editable `0.6.0` vs `==0.5.0` pin would conflict). (2) Phase 5 gate 5.1 wants `make tb` on an env WITHOUT the temporal extra — but THIS worktree HAS temporalio installed, so the next session must arrange a no-temporal-extra import check (separate venv, or a targeted import-isolation test) rather than assuming the local env exercises that path.+- Code state: **COMMITTED + PUSHED** — commit `72e1800f` on `refactor/Dataclasses` (tracks `origin/refactor/Dataclasses`), working tree clean. 8 files: `pipelex/core/concepts/concept_factory.py`, `pipelex/core/qualified_ref.py`, `pipelex/reporting/reporting_manager.py`, `pipelex/errors/error_pages_generator.py`, `pipelex/builder/runner_code.py`, `pipelex/tools/jinja2/jinja2_required_variables.py`, `pipelex/temporal/tprl/namespace_check.py`, + this `TODOS.md`. No new files (the `tests/perf/` harness was created then deleted in the same session). `uv.lock` untouched. (This `TODOS.md` cold-start update lands as a small follow-up commit after `72e1800f`.)+- NEXT ACTION: HARD STOP 2 — END THE SESSION. A fresh session starts **Phase 5** — convert `DispatchOptions` in `pipelex/temporal/config_temporal.py` to frozen `BaseModel(arbitrary_types_allowed=True)`. **Do gate 5.1 FIRST:** confirm the module still imports without the `temporalio` extra (RetryPolicy stays under `TYPE_CHECKING`/typed `Any`); this worktree has temporalio installed, so arrange a no-extra import check. If the import-clean path proves infeasible, fall back to the NamedTuple form (5.2) and record it.++### 2026-05-29 — Phase 0 complete (converter + kajson generalized) — 🛑 HARD STOP 1 reached+- Landed: Pre-flight (both boxes) + **0.1–0.9** all flipped with per-item results above. Two-repo change:+ - **kajson** (`../kajson`, branch `feature/Support-more-types`): `json_decoder.py` gained an explicit `is_pydantic_dataclass` decode branch (validates via the dataclass, raises `KajsonDecoderError` loudly instead of silently returning a raw dict); new `tests/unit/test_pydantic_dataclass.py`; version `0.5.0`→`0.6.0` + CHANGELOG entry.+ - **pipelex** (`_data` worktree): `pipelex/temporal/temporal_data_converter.py` widened — `_is_kajson_wire_value` (to_payload, BaseModel-short-circuit first) and `_is_kajson_type` (from_payload scalar/Optional/list) now also accept pydantic dataclasses; BaseModel path byte-identical. New tests: `data_converter/test_data_conv_dataclass.py` (direct converter + byte-identical regression guard) and `test_wf_dataclass_roundtrip.py` (in-process-server round-trip).+- Decisions / deviations:+ - **kajson test isolation (fixed at root after code review):** `test_json_encoder` / `test_json_decoder` autouse fixtures used to `clear_*coders()` on teardown without restoring, wiping kajson's import-time default codecs process-wide. Now they snapshot the registry and restore it on teardown. An initial band-aid (re-registering `timedelta` in the new dataclass test) was removed.+ - **pyright-strict refactor:** replacing the original inline `isinstance` narrowing with non-narrowing bool predicates surfaced `reportUnknownArgumentType` errors (`type(Any)` → `type[Unknown]`). Resolved cleanly: value predicate param typed `object`, list-head probe extracted to an `object`-typed helper, call sites keep `value` explicitly `Any`, and one `cast("Any", type_hint)` collapses the post-`isinstance` union. No `# pyright: ignore` added in the converter.+ - **Version/pin tension (IMPORTANT for next session):** kajson is bumped to `0.6.0` but pipelex still pins `kajson==0.5.0` (editable source serves live code; installed metadata stays `0.5.0`, so the pin holds and the `.venv` works). Running `uv lock`/`uv sync` here would now FAIL (editable `0.6.0` vs `==0.5.0`). The pin bump + PyPI publish remain the deferred release gate.+- Verification (all green): kajson suite 257 passed / 1 skipped + kajson `make agent-check` clean · pipelex `make agent-check` (pyright 0/0, mypy 1929 files) · `make tb` 2 passed · converter+integration round-trips 11 passed · full temporal integration (non-inference) 136 passed, 4 pre-existing xdist-race xpass, no regressions, no stray temporal processes.+- Open questions: none blocking Phase 1. The only live item is the deferred kajson PyPI publish + `kajson==` pin bump (release gate, not dev-blocking).+- Code state: **uncommitted** (per instruction — not committing without explicit ask). Dirty: kajson = `CHANGELOG.md`, `kajson/json_decoder.py`, `pyproject.toml`, new `tests/unit/test_pydantic_dataclass.py`, plus the code-review root-cause fix in `tests/unit/test_json_encoder.py` + `tests/unit/test_json_decoder.py`; pipelex `_data` = `pipelex/temporal/temporal_data_converter.py`, new `tests/integration/pipelex/temporal/data_converter/test_data_conv_dataclass.py`, new `tests/integration/pipelex/temporal/test_wf_dataclass_roundtrip.py`, and this `TODOS.md`. Tree otherwise clean; `uv.lock` untouched.+- NEXT ACTION: HARD STOP 1 — END THE SESSION. A fresh session starts Phase 1 (perf baseline harness at `tests/perf/test_dataclass_forms_bench.py`, task 1.1), which does not depend on Phase 0 internals. Before any `uv` re-lock, remember the version/pin tension above.++### 2026-05-29 — Ledger created (planning only, no code changes)+- Landed: nothing implemented yet. This ledger was created from the former `wip/data-class-best-practices-plan.md` (removed). The previous root ledger (`feature/API-readiness-4`, all complete) was archived to `wip/error-handling/archive-todos-api-readiness-4.md`.+- Decisions: (1) per-site type strategy for the six stdlib dataclasses — NOT a uniform pydantic-dataclass conversion. (2) Generalize the converter + kajson FIRST as Phase 0, scoped to pydantic dataclasses only. (3) kajson is consumed editable from `../kajson` in this worktree, so no PyPI publish needed for dev; publish + pin bump is a release-time gate.+- Open questions: none blocking. The `DispatchOptions` import-without-temporalio invariant (Phase 5) is the one real unknown — gated by 5.1.+- Code state: clean working tree except this ledger + the archived file move. No production code touched.+- NEXT ACTION: start Phase 0 — Pre-flight boundary freeze, then task 0.1 (kajson `is_pydantic_dataclass` decode branch in `../kajson/kajson/json_decoder.py`), TDD: write the kajson round-trip tests (0.2) first.diff --git a/pipelex/builder/runner_code.py b/pipelex/builder/runner_code.pyindex 023fe80c2..54c03f21f 100644--- a/pipelex/builder/runner_code.py+++ b/pipelex/builder/runner_code.py@@ -7,9 +7,10 @@ Main Functions:- generate_runner_code(pipe): Generate complete executable Python script"""-from dataclasses import dataclassfrom typing import Any+from pydantic import BaseModel, ConfigDict+from pipelex.core.concepts.concept import Conceptfrom pipelex.core.concepts.concept_representation_generator import (ConceptRepresentationFormat,@@ -23,10 +24,11 @@ from pipelex.core.pipes.variable_multiplicity import VariableMultiplicityfrom pipelex.tools.misc.string_utils import pascal_case_to_snake_case-@dataclass-class CustomClassInfo:+class CustomClassInfo(BaseModel):"""Information about a custom structure class for import generation."""+ model_config = ConfigDict(frozen=True)+class_name: strdomain_code: strconcept_code: strdiff --git a/pipelex/core/concepts/concept_factory.py b/pipelex/core/concepts/concept_factory.pyindex 4a8885fbd..c2eb9fb75 100644--- a/pipelex/core/concepts/concept_factory.py+++ b/pipelex/core/concepts/concept_factory.py@@ -1,4 +1,4 @@-from typing import cast+from typing import NamedTuple, castfrom kajson.class_registry_abstract import ClassRegistryAbstractfrom pydantic import BaseModel@@ -29,6 +29,11 @@ def _get_class_registry() -> ClassRegistryAbstract:return hub.get_class_registry() # type: ignore[no-any-return]+class StructureNameAndRefine(NamedTuple):+ structure_class_name: str+ refine_string: str | None++class ConceptDeclarationType(StrEnum):"""Enum representing the 5 ways a concept can be declared in MTHDS files.@@ -339,25 +344,24 @@ class ConceptFactory:concept_code: str,domain_code: str,description: str,- ) -> tuple[str, str | None]:- """Handle BASIC_BLUEPRINT declaration type.-- Returns:- Tuple of (structure_class_name, refine_string)- """+ ) -> StructureNameAndRefine:+ """Handle BASIC_BLUEPRINT declaration type."""qualified_class_name = make_qualified_structure_class_name(domain_code, concept_code)# Check if a valid structure class already exists — first by bare concept_code# (for pre-existing Python classes registered under their own name), then by# qualified name (for previously generated dynamic classes)if Concept.is_valid_structure_class(structure_class_name=concept_code):- return concept_code, None+ return StructureNameAndRefine(structure_class_name=concept_code, refine_string=None)if Concept.is_valid_structure_class(structure_class_name=qualified_class_name):- return qualified_class_name, None+ return StructureNameAndRefine(structure_class_name=qualified_class_name, refine_string=None)# Because native concepts have structure class names diffrent than other (with "Content")if concept_code in NativeConceptCode.values_list():- return NativeConceptCode.TEXT.structure_class_name, NativeConceptCode.TEXT.concept_ref+ return StructureNameAndRefine(+ structure_class_name=NativeConceptCode.TEXT.structure_class_name,+ refine_string=NativeConceptCode.TEXT.concept_ref,+ )try:_, the_generated_class = StructureGenerator().generate_from_structure_blueprint(@@ -372,7 +376,7 @@ class ConceptFactory:# Register the generated class_get_class_registry().register_class(the_generated_class)- return qualified_class_name, NativeConceptCode.TEXT.concept_ref+ return StructureNameAndRefine(structure_class_name=qualified_class_name, refine_string=NativeConceptCode.TEXT.concept_ref)@classmethoddef _handle_refines(@@ -380,14 +384,11 @@ class ConceptFactory:blueprint: ConceptBlueprint,concept_code: str,domain_code: str,- ) -> tuple[str, str]:+ ) -> StructureNameAndRefine:"""Handle REFINES declaration type.Concept refines another concept - generate a new class that inherits from the refinedstructure class.-- Returns:- Tuple of (structure_class_name, refine_string)"""if blueprint.refines is None:msg = "Expected refines to be set"@@ -419,7 +420,7 @@ class ConceptFactory:raise ConceptFactoryError(msg) from exc_get_class_registry().register_class(the_generated_class)- return qualified_class_name, current_refine+ return StructureNameAndRefine(structure_class_name=qualified_class_name, refine_string=current_refine)# Get the refined concept's structure class name# For native concepts, the structure class name is "ConceptCode" + "Content" (e.g., TextContent)@@ -451,7 +452,7 @@ class ConceptFactory:# Register the generated class_get_class_registry().register_class(the_generated_class)- return qualified_class_name, current_refine+ return StructureNameAndRefine(structure_class_name=qualified_class_name, refine_string=current_refine)@classmethoddef make_from_blueprint(diff --git a/pipelex/core/qualified_ref.py b/pipelex/core/qualified_ref.pyindex 073275857..c219c9f88 100644--- a/pipelex/core/qualified_ref.py+++ b/pipelex/core/qualified_ref.py@@ -1,3 +1,5 @@+from typing import NamedTuple+from pydantic import BaseModel, ConfigDictfrom pipelex.tools.misc.string_utils import is_pascal_case, is_snake_case@@ -7,6 +9,11 @@ class QualifiedRefError(ValueError):"""Raised when a qualified reference string is invalid."""+class CrossPackageRef(NamedTuple):+ alias: str+ remainder: str++class QualifiedRef(BaseModel):"""A domain-qualified reference to a concept or pipe.@@ -194,14 +201,14 @@ class QualifiedRef(BaseModel):return "->" in raw@staticmethod- def split_cross_package_ref(raw: str) -> tuple[str, str]:+ def split_cross_package_ref(raw: str) -> CrossPackageRef:"""Split a cross-package reference into alias and remainder.Args:raw: The raw reference string like 'alias->domain.pipe_code'Returns:- Tuple of (alias, remainder) where remainder is 'domain.pipe_code'+ CrossPackageRef(alias, remainder) where remainder is 'domain.pipe_code'Raises:QualifiedRefError: If the string does not contain '->'@@ -210,4 +217,4 @@ class QualifiedRef(BaseModel):msg = f"Reference '{raw}' is not a cross-package reference (no '->' found)"raise QualifiedRefError(msg)parts = raw.split("->", maxsplit=1)- return parts[0], parts[1]+ return CrossPackageRef(alias=parts[0], remainder=parts[1])diff --git a/pipelex/errors/error_pages_generator.py b/pipelex/errors/error_pages_generator.pyindex 604515035..434257eb7 100644--- a/pipelex/errors/error_pages_generator.py+++ b/pipelex/errors/error_pages_generator.py@@ -18,10 +18,12 @@ from __future__ import annotationsimport functoolsimport importlibimport sys-from dataclasses import dataclass, field+from dataclasses import fieldfrom pathlib import Pathfrom typing import TYPE_CHECKING+from pydantic.dataclasses import dataclass+import pipelexfrom pipelex.base_exceptions import ErrorDomain, PipelexErrorfrom pipelex.cogt.inference.error_classification import UserAction@@ -175,6 +177,9 @@ class ErrorPagesReport:``removed`` (a previously-generated page no longer maps to a target classand was deleted; pages bearing :data:`AUTHORED_MARKER` are never removedand surface as ``preserved`` instead).++ ``frozen`` only blocks rebinding the fields — the lists are still populated+ in place via ``.append`` by ``_commit_page`` / ``_remove_orphans``."""written: list[Path] = field(default_factory=list[Path])diff --git a/pipelex/reporting/reporting_manager.py b/pipelex/reporting/reporting_manager.pyindex e10765609..c052dbb09 100644--- a/pipelex/reporting/reporting_manager.py+++ b/pipelex/reporting/reporting_manager.py@@ -1,7 +1,7 @@from collections.abc import Sequence-from dataclasses import dataclassfrom datetime import datetime, timezonefrom pathlib import Path+from typing import NamedTuplefrom pydantic import Field, RootModelfrom typing_extensions import override@@ -34,8 +34,7 @@ except ImportError:_BotoClientError = None # type: ignore[assignment, misc]-@dataclass-class _EventLogContext:+class _EventLogContext(NamedTuple):"""Per-workflow/run event log state. Private to ReportingManager."""event_log: EventLogProtocoldiff --git a/pipelex/temporal/config_temporal.py b/pipelex/temporal/config_temporal.pyindex b3c42c495..c80be1475 100644--- a/pipelex/temporal/config_temporal.py+++ b/pipelex/temporal/config_temporal.py@@ -1,9 +1,9 @@import difflib-from dataclasses import dataclassfrom datetime import timedeltafrom typing import TYPE_CHECKING, Annotated, Any, Literal, Unionfrom pydantic import Field, model_validator+from pydantic.dataclasses import dataclassfrom pipelex import logfrom pipelex.system.configuration.config_model import ConfigModel@@ -13,6 +13,14 @@ from pipelex.types import Self, StrEnumif TYPE_CHECKING:from temporalio.common import RetryPolicy+else:+ # Runtime placeholder so Pydantic resolves the ``DispatchOptions.retry_policy``+ # field annotation to ``Any`` (no validation, no isinstance) WITHOUT importing+ # ``temporalio`` — keeping this module importable on installs that skipped the+ # ``temporal`` extra. Type checkers see the real ``RetryPolicy`` above. With a+ # bare forward ref instead, the model imports (deferred schema) but raises+ # ``PydanticUserError`` the moment a ``DispatchOptions`` is constructed.+ RetryPolicy = Any# Names of the five custom search attributes Pipelex knows how to populate.@@ -363,7 +371,7 @@ class WorkerRuntimeProfilesConfig(ConfigModel):return self-@dataclass+@dataclass(frozen=True)class DispatchOptions:"""Resolved per-call dispatch bundle returned by ``WorkerConfig.resolve_dispatch``.@@ -374,14 +382,16 @@ class DispatchOptions:timeouts are likewise omitted when unset so the Temporal SDK applies itsown defaults (rather than ``None``, which the SDK rejects).- Implemented as a dataclass (not a Pydantic BaseModel) so the module can be- imported without ``temporalio`` installed — the ``RetryPolicy`` annotation- is a forward reference resolved only at attribute access.+ Frozen, build-once-read-only: constructed only inside ``resolve_dispatch``,+ immediately splatted via ``to_execute_kwargs``, and never serialized across+ the Temporal wire. ``retry_policy`` is ``Any`` at runtime (see the+ ``RetryPolicy`` binding above) — type checkers still see the real+ ``temporalio`` ``RetryPolicy``."""task_queue: str | Nonestart_to_close_timeout: timedelta- retry_policy: "RetryPolicy"+ retry_policy: RetryPolicyschedule_to_close_timeout: timedelta | None = Noneschedule_to_start_timeout: timedelta | None = Noneheartbeat_timeout: timedelta | None = Nonediff --git a/pipelex/temporal/temporal_data_converter.py b/pipelex/temporal/temporal_data_converter.pyindex 79439ca99..efe5276b1 100644--- a/pipelex/temporal/temporal_data_converter.py+++ b/pipelex/temporal/temporal_data_converter.py@@ -30,6 +30,7 @@ from typing import Any, castfrom kajson import kajsonfrom kajson.class_registry import ClassRegistryfrom pydantic import BaseModel+from pydantic.dataclasses import is_pydantic_dataclassfrom temporalio.api.common.v1 import Payloadfrom temporalio.converter import (CompositePayloadConverter,@@ -52,30 +53,46 @@ class BaseModelPayloadConverter(JSONPlainPayloadConverter):This extends the :py:class:`JSONPlainPayloadConverter` to override :py:meth:`to_payload`."""+ @classmethod+ def _is_kajson_wire_value(cls, value: object) -> bool:+ """A value kajson serializes with type preservation: a BaseModel instance or a pydantic dataclass instance.++ The BaseModel check is first so it short-circuits on the hot path before the pydantic-dataclass probe.+ """+ return isinstance(value, BaseModel) or is_pydantic_dataclass(type(value))++ def _kajson_to_payload(self, value: object, source_type_holder: object) -> Payload:+ """Serialize a kajson wire value (or list of them) to a Payload.++ ``source_type_holder`` is the object whose type may carry a dynamic-class ``__kajson_class_source__``+ (the value itself for a scalar, or the first element for a list). That attribute is absent on pydantic+ dataclasses — only dynamically-built BaseModel classes set it — so the lookup is harmlessly ``None`` there.+ """+ payload_str: str = kajson.dumps(value)+ metadata: dict[str, bytes] = {"encoding": self.encoding.encode()}+ class_source = getattr(type(source_type_holder), "__kajson_class_source__", None)+ if class_source is not None:+ metadata["kajson_class_source"] = class_source.encode()+ return Payload(metadata=metadata, data=payload_str.encode())++ @classmethod+ def _first_kajson_list_element(cls, value: object) -> object | None:+ """Return the first element if value is a non-empty list whose head is a kajson wire value, else None."""+ if not isinstance(value, list):+ return None+ items = cast("list[object]", value)+ if items and cls._is_kajson_wire_value(items[0]):+ return items[0]+ return None+@overridedef to_payload(self, value: Any) -> Payload | None:- if isinstance(value, BaseModel):- payload_str: str = kajson.dumps(value)- metadata: dict[str, bytes] = {"encoding": self.encoding.encode()}- class_source = getattr(type(value), "__kajson_class_source__", None)- if class_source is not None:- metadata["kajson_class_source"] = class_source.encode()- return Payload(- metadata=metadata,- data=payload_str.encode(),- )- elif isinstance(value, list) and value and isinstance(value[0], BaseModel):- list_payload_str: str = kajson.dumps(value)- metadata = {"encoding": self.encoding.encode()}- class_source = getattr(type(value[0]), "__kajson_class_source__", None)- if class_source is not None:- metadata["kajson_class_source"] = class_source.encode()- return Payload(- metadata=metadata,- data=list_payload_str.encode(),- )- else:- return super().to_payload(value)+ if self._is_kajson_wire_value(value):+ return self._kajson_to_payload(value, source_type_holder=value)+ list_head = self._first_kajson_list_element(value)+ if list_head is not None:+ return self._kajson_to_payload(value, source_type_holder=list_head)+ return super().to_payload(value)def _restore_class_source(self, value: BaseModel, class_source_code: str) -> None:value_class = cast("Any", type(value))@@ -112,19 +129,31 @@ class BaseModelPayloadConverter(JSONPlainPayloadConverter):log.verbose(f"unijson_deserialize_payload — pydantic_gizmo: {pydantic_gizmo}")return cast("Any", pydantic_gizmo)- @staticmethod- def _unwrap_optional_base_model(type_hint: type[Any] | None) -> bool:- """Check if type_hint is Optional[BaseModel] / BaseModel | None."""+ @classmethod+ def _is_kajson_type(cls, type_hint: Any) -> bool:+ """A type kajson reconstructs with type preservation: a BaseModel subclass or a pydantic dataclass.++ The inner args of ``Optional`` / ``list`` hints may be typing constructs rather than classes;+ ``is_pydantic_dataclass`` returns ``False`` for those without raising, so no guard is needed.+ """+ if isinstance(type_hint, type) and issubclass(type_hint, BaseModel):+ return True+ # cast collapses the post-isinstance ``Any | type[Unknown]`` back to ``Any`` for the typed probe.+ return is_pydantic_dataclass(cast("Any", type_hint))++ @classmethod+ def _unwrap_optional_kajson_type(cls, type_hint: type[Any] | None) -> bool:+ """Check if type_hint is Optional[X] / X | None where X is a kajson wire type."""if type_hint is None:return Falseargs = getattr(type_hint, "__args__", None)if args is None:return False- # Optional[X] is Union[X, None] — check if any non-None arg is a BaseModel subclass+ # Optional[X] is Union[X, None] — check if any non-None arg is a kajson wire typefor arg in args:if arg is type(None):continue- if isinstance(arg, type) and issubclass(arg, BaseModel):+ if cls._is_kajson_type(arg):return Truereturn False@@ -134,23 +163,23 @@ class BaseModelPayloadConverter(JSONPlainPayloadConverter):payload: Payload,type_hint: type[Any] | None = None,) -> Any:- # BaseModel case- if isinstance(type_hint, type) and issubclass(type_hint, BaseModel): # pyright: ignore[reportUnnecessaryIsInstance]+ # BaseModel / pydantic-dataclass scalar case+ if self._is_kajson_type(type_hint):return self._kajson_deserialize_from_payload(payload=payload)- # Optional[BaseModel] case (e.g. GraphSpec | None)- if self._unwrap_optional_base_model(type_hint):+ # Optional case (e.g. GraphSpec | None)+ if self._unwrap_optional_kajson_type(type_hint):return self._kajson_deserialize_from_payload(payload=payload)- # BaseModel list case+ # list caseorigin = getattr(type_hint, "__origin__", None)args = getattr(type_hint, "__args__", None)log.verbose(f"Type hint origin: {origin}, args: {args}")- if origin is list and args and len(args) == 1 and issubclass(args[0], BaseModel):- log.debug(f"Type hint is a List of BaseModel: {args[0]}")+ if origin is list and args and len(args) == 1 and self._is_kajson_type(args[0]):+ log.debug(f"Type hint is a list of kajson wire type: {args[0]}")return self._kajson_deserialize_from_payload(payload=payload)- log.verbose(f"The type hint '{type_hint}' is neither a subclass of BaseModel nor a List of BaseModel")+ log.verbose(f"The type hint '{type_hint}' is neither a kajson wire type nor a list of kajson wire types")return super().from_payload(payload, type_hint) # pyright: ignore[reportUnknownMemberType]diff --git a/pipelex/temporal/tprl/namespace_check.py b/pipelex/temporal/tprl/namespace_check.pyindex 9b2f25a67..3174b79c1 100644--- a/pipelex/temporal/tprl/namespace_check.py+++ b/pipelex/temporal/tprl/namespace_check.py@@ -27,9 +27,9 @@ Two entry points:"""from collections.abc import Sequence-from dataclasses import dataclassfrom typing import Final+from pydantic import BaseModel, ConfigDictfrom temporalio.api.enums.v1 import IndexedValueTypefrom temporalio.api.operatorservice.v1 import (AddSearchAttributesRequest,@@ -47,15 +47,22 @@ from pipelex.temporal.exceptions import SearchAttributeRegistrationErrorPIPELEX_SETUP_CLI_COMMAND: Final[str] = "pipelex setup-temporal-namespace"-@dataclass(frozen=True)-class RegistrationFailure:+class RegistrationFailure(BaseModel):"""Structured permission-denied outcome from``ensure_required_search_attributes_registered``. The CLI command formatsthis into the fallback runbook so operators whose worker API key lacks``OperatorService.AddSearchAttributes`` permission know which raw``temporal`` / ``tcld`` invocations to run instead.++ Modeled (not a ``NamedTuple``) so it stays type-distinct from the+ ``tuple[str, ...]`` success arm of the+ ``RegistrationFailure | tuple[str, ...]`` return — callers discriminate via+ ``isinstance(x, RegistrationFailure)`` and a plain success tuple must never+ satisfy that check."""+ model_config = ConfigDict(frozen=True)+namespace: strmissing: tuple[str, ...]rpc_error_message: strdiff --git a/pipelex/tools/jinja2/jinja2_required_variables.py b/pipelex/tools/jinja2/jinja2_required_variables.pyindex 40facf1c2..892d6e260 100644--- a/pipelex/tools/jinja2/jinja2_required_variables.py+++ b/pipelex/tools/jinja2/jinja2_required_variables.py@@ -1,10 +1,11 @@-from dataclasses import dataclass, field+from dataclasses import fieldfrom jinja2 import nodesfrom jinja2.exceptions import (TemplateSyntaxError,UndefinedError,)+from pydantic.dataclasses import dataclassfrom pipelex.cogt.templating.template_category import TemplateCategoryfrom pipelex.tools.jinja2.exceptions import Jinja2DetectVariablesError, Jinja2StuffError@@ -16,13 +17,16 @@ from pipelex.tools.misc.string_utils import get_root_from_dotted_pathclass VariableReference:"""Represents a variable reference in a Jinja2 template with its applied filters.+ Mutated in place: ``_collect_variable_references`` does ``.filters.append(...)``+ on re-seen variables, so this is intentionally NOT frozen.+Attributes:path: The full dotted path to the variable (e.g., "document.cover", "pages")filters: List of filter names applied to this variable (e.g., ["with_images", "tag"])"""path: str- filters: list[str] = field(default_factory=list) # pyright: ignore[reportUnknownVariableType]+ filters: list[str] = field(default_factory=list[str])def _build_full_path(node: nodes.Node) -> str | None:diff --git a/pyproject.toml b/pyproject.tomlindex 9b84229e5..9883c0683 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -27,7 +27,7 @@ dependencies = ["instructor>=1.13", # 1.13+ exposes instructor.core; 1.11/1.12 had mypy typing errors"jinja2>=3.1.4","json2html>=1.3.0",- "kajson==0.5.0",+ "kajson==0.6.0","markdown>=3.6","mthds>=0.3.0","networkx>=3.4.2",diff --git a/tests/integration/pipelex/temporal/data_converter/test_data_conv_dataclass.py b/tests/integration/pipelex/temporal/data_converter/test_data_conv_dataclass.pynew file mode 100644index 000000000..c942ea543--- /dev/null+++ b/tests/integration/pipelex/temporal/data_converter/test_data_conv_dataclass.py@@ -0,0 +1,84 @@+"""Direct converter round-trip tests for pydantic dataclasses.++Phase 0 widened ``BaseModelPayloadConverter`` so a pydantic dataclass (and ``Optional`` /+``list`` of them) routes through kajson with type preservation, instead of falling through+to Temporal's stock JSON. These call ``to_payload`` / ``from_payload`` directly and assert+both value and concrete type survive. A regression guard locks the untouched ``BaseModel``+path to byte-identical output.+"""++from datetime import timedelta+from typing import Any, cast++import pytest+from kajson import kajson+from pydantic import BaseModel+from pydantic.dataclasses import dataclass as pydantic_dataclass+from pydantic.dataclasses import is_pydantic_dataclass++from pipelex.temporal.temporal_data_converter import BaseModelPayloadConverter+++class ConvInner(BaseModel):+ label: str+ count: int+++@pydantic_dataclass+class ConvDataclass:+ name: str+ delay: timedelta+ inner: ConvInner+ note: str | None = None+++class ConvPlainModel(BaseModel):+ field_a: str+ field_b: int+++class TestDataConverterForPydanticDataclass:+ def test_scalar_dataclass_roundtrip(self, payload_converter: BaseModelPayloadConverter) -> None:+ original = ConvDataclass(name="x", delay=timedelta(seconds=30), inner=ConvInner(label="L", count=2))+ payload = payload_converter.to_payload(original)+ assert payload+ restored = cast("ConvDataclass", payload_converter.from_payload(payload, type_hint=ConvDataclass))+ assert is_pydantic_dataclass(type(restored))+ assert isinstance(restored.inner, ConvInner)+ assert restored == original++ def test_optional_dataclass_roundtrip(self, payload_converter: BaseModelPayloadConverter) -> None:+ original = ConvDataclass(name="opt", delay=timedelta(seconds=5), inner=ConvInner(label="O", count=1), note="set")+ payload = payload_converter.to_payload(original)+ assert payload+ optional_hint: Any = ConvDataclass | None+ restored = cast("ConvDataclass", payload_converter.from_payload(payload, type_hint=optional_hint))+ assert is_pydantic_dataclass(type(restored))+ assert restored == original++ def test_list_of_dataclass_roundtrip(self, payload_converter: BaseModelPayloadConverter) -> None:+ original = [+ ConvDataclass(name="a", delay=timedelta(seconds=1), inner=ConvInner(label="A", count=1)),+ ConvDataclass(name="b", delay=timedelta(seconds=2), inner=ConvInner(label="B", count=2)),+ ]+ payload = payload_converter.to_payload(original)+ assert payload+ list_hint: Any = list[ConvDataclass]+ restored = cast("list[ConvDataclass]", payload_converter.from_payload(payload, type_hint=list_hint))+ assert all(is_pydantic_dataclass(type(item)) for item in restored)+ assert all(isinstance(item.inner, ConvInner) for item in restored)+ assert restored == original++ def test_base_model_payload_is_byte_identical(self, payload_converter: BaseModelPayloadConverter) -> None:+ # Regression guard: the dataclass widening must leave the BaseModel path byte-identical.+ # A plain BaseModel (no __kajson_class_source__) yields exactly kajson.dumps bytes plus the+ # encoding metadata key — nothing the dataclass branch could perturb.+ model = ConvPlainModel(field_a="hello", field_b=7)+ payload = payload_converter.to_payload(model)+ assert payload+ assert set(payload.metadata.keys()) == {"encoding"}+ assert payload.metadata["encoding"] == payload_converter.encoding.encode()+ assert payload.data == kajson.dumps(model).encode()+ restored = cast("ConvPlainModel", payload_converter.from_payload(payload, type_hint=ConvPlainModel))+ assert restored == modeldiff --git a/tests/integration/pipelex/temporal/test_wf_dataclass_roundtrip.py b/tests/integration/pipelex/temporal/test_wf_dataclass_roundtrip.pynew file mode 100644index 000000000..6fb2bd187--- /dev/null+++ b/tests/integration/pipelex/temporal/test_wf_dataclass_roundtrip.py@@ -0,0 +1,136 @@+"""Integration test: a pydantic dataclass round-trips through Temporal (workflow -> activity -> return).++Phase 0 widened ``BaseModelPayloadConverter`` to route pydantic dataclasses through kajson with+type preservation. This exercises that path end-to-end through the in-process test server: the+dataclass is encoded by the client, decoded by the worker for the activity, re-encoded on return,+and decoded again by the client — every hop driven by the widened converter.+"""++from __future__ import annotations++import uuid+from datetime import timedelta+from typing import TYPE_CHECKING++import pytest+from pydantic import BaseModel+from pydantic.dataclasses import dataclass as pydantic_dataclass+from pydantic.dataclasses import is_pydantic_dataclass+from temporalio import activity, workflow+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from pipelex.pipelex import Pipelex+from pipelex.system.runtime import IntegrationMode, runtime_manager+from pipelex.temporal.temporal_data_converter import make_data_converter++if TYPE_CHECKING:+ from collections.abc import Generator++ from temporalio.client import Client as TemporalClient+++# ---------------------------------------------------------------------------+# Override autouse fixtures from parent conftest — this test manages its own+# Worker and client, and only needs Pipelex initialized for logging/config.+# ---------------------------------------------------------------------------++[email protected](scope="module", autouse=True)+def reset_pipelex_config_fixture() -> Generator[None, None, None]:+ """Initialize Pipelex for logging/config without TemporalTaskManager."""+ Pipelex.make(+ integration_mode=IntegrationMode.CI if runtime_manager.is_ci_testing else IntegrationMode.PYTEST,+ )+ yield+ Pipelex.teardown_if_needed()++[email protected](scope="module", autouse=True)+def boot_temporal(reset_pipelex_config_fixture: None) -> None:+ """No-op override: this test manages its own Worker and client."""+++# ---------------------------------------------------------------------------+# Test model, dataclass, activity, and workflow+# ---------------------------------------------------------------------------+++class DataclassInner(BaseModel):+ """Nested BaseModel field, to prove type preservation survives inside a dataclass."""++ label: str+ count: int+++@pydantic_dataclass+class DataclassPayload:+ """Pydantic dataclass crossing the Temporal wire — the type Phase 0 made wire-legal."""++ name: str+ delay: timedelta+ inner: DataclassInner+ note: str | None = None++[email protected](name="act_echo_dataclass_payload")+async def act_echo_dataclass_payload(payload: DataclassPayload) -> DataclassPayload: # noqa: RUF029+ """Return the dataclass unchanged — exercises decode (arg) then encode (return)."""+ return payload++[email protected](name="wf_echo_dataclass_payload")+class WfEchoDataclassPayload:+ """Forward a pydantic dataclass through an activity and return it."""++ @workflow.run+ async def run(self, payload: DataclassPayload) -> DataclassPayload:+ return await workflow.execute_activity(+ act_echo_dataclass_payload,+ payload,+ start_to_close_timeout=timedelta(seconds=30),+ )+++# ---------------------------------------------------------------------------+# Test+# ---------------------------------------------------------------------------++[email protected](loop_scope="class")+class TestPydanticDataclassTemporalRoundTrip:+ async def test_pydantic_dataclass_survives_temporal_roundtrip(self) -> None:+ """A pydantic dataclass round-trips through workflow -> activity -> return with type preserved."""+ original = DataclassPayload(+ name="widget",+ delay=timedelta(seconds=45),+ inner=DataclassInner(label="L", count=3),+ note="hello",+ )++ task_queue = str(uuid.uuid4())+ converter = make_data_converter()++ async with await WorkflowEnvironment.start_local(data_converter=converter) as env: # pyright: ignore[reportUnknownMemberType]+ temporal_client: TemporalClient = env.client+ async with Worker(+ temporal_client,+ task_queue=task_queue,+ workflows=[WfEchoDataclassPayload],+ activities=[act_echo_dataclass_payload],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ result: DataclassPayload = await temporal_client.execute_workflow( # pyright: ignore[reportUnknownMemberType]+ WfEchoDataclassPayload.run,+ original,+ id=f"wf-dataclass-roundtrip-{uuid.uuid4().hex[:8]}",+ task_queue=task_queue,+ )++ assert is_pydantic_dataclass(type(result))+ assert isinstance(result.inner, DataclassInner)+ assert result.inner.label == "L"+ assert result.inner.count == 3+ assert result.delay == timedelta(seconds=45)+ assert result.note == "hello"+ assert result == originaldiff --git a/tests/unit/pipelex/temporal/test_dispatch_options_no_temporalio.py b/tests/unit/pipelex/temporal/test_dispatch_options_no_temporalio.pynew file mode 100644index 000000000..95ce3927b--- /dev/null+++ b/tests/unit/pipelex/temporal/test_dispatch_options_no_temporalio.py@@ -0,0 +1,85 @@+"""Regression: ``DispatchOptions`` (a frozen Pydantic dataclass) MUST be+importable AND constructible without ``temporalio`` installed.++``temporalio`` is in ``[project.optional-dependencies].temporal``;+``pipelex.system.configuration.configs`` imports ``config_temporal`` unconditionally.+The ``retry_policy`` field is annotated ``RetryPolicy`` (a ``temporalio`` type),+which is bound to ``Any`` at runtime via the ``else`` branch of the+``TYPE_CHECKING`` guard. Without that runtime binding the dataclass carries an+unresolved forward ref: it would still import (Pydantic defers the schema) but+raise ``PydanticUserError`` the moment a ``DispatchOptions`` is constructed on an+install lacking the ``temporal`` extra.++The sibling ``test_config_temporal_optional_dep.py`` AST-scans for module-level+``temporalio`` imports; it does NOT catch a regression to a bare forward ref+(which adds no import statement). This runtime check is the complement: it+exercises the actual class-definition + construction path with ``temporalio``+made unavailable, in a fresh subprocess so the block precedes any import.+"""++import subprocess # noqa: S404+import sys+import textwrap++_NO_TEMPORALIO_SCRIPT = textwrap.dedent(+ """+ import sys+ import importlib.abc+++ class _Blocker(importlib.abc.MetaPathFinder):+ def find_spec(self, name, path, target=None):+ if name == "temporalio" or name.startswith("temporalio."):+ raise ModuleNotFoundError(f"No module named {name!r} (blocked by test)")+ return None+++ sys.meta_path.insert(0, _Blocker())++ # Sanity: the block is actually in force.+ try:+ import temporalio # noqa: F401++ raise AssertionError("temporalio import was NOT blocked")+ except ModuleNotFoundError:+ pass++ from datetime import timedelta++ from pipelex.temporal.config_temporal import DispatchOptions++ # Construct + read back through to_execute_kwargs. retry_policy is Any at+ # runtime, so an arbitrary sentinel stands in for the temporalio RetryPolicy.+ dispatch = DispatchOptions(+ task_queue=None,+ start_to_close_timeout=timedelta(seconds=5),+ retry_policy=object(),+ heartbeat_timeout=timedelta(seconds=2),+ )+ kwargs = dispatch.to_execute_kwargs()+ assert "task_queue" not in kwargs, kwargs+ assert kwargs["start_to_close_timeout"] == timedelta(seconds=5), kwargs+ assert kwargs["heartbeat_timeout"] == timedelta(seconds=2), kwargs+ assert "retry_policy" in kwargs, kwargs++ print("NO_TEMPORALIO_OK")+ """+)+++class TestDispatchOptionsNoTemporalio:+ def test_import_and_construct_without_temporalio(self) -> None:+ """Fresh interpreter with ``temporalio`` blocked: importing+ ``config_temporal`` and constructing a ``DispatchOptions`` must both+ succeed (the load-bearing optional-dependency invariant).+ """+ result = subprocess.run( # noqa: S603+ [sys.executable, "-c", _NO_TEMPORALIO_SCRIPT],+ capture_output=True,+ text=True,+ check=False,+ )+ assert result.returncode == 0, (+ f"DispatchOptions could not be imported/constructed without temporalio.\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}"+ )+ assert "NO_TEMPORALIO_OK" in result.stdout, result.stdoutdiff --git a/uv.lock b/uv.lockindex 9c2b3507d..ac32b7bfb 100644--- a/uv.lock+++ b/uv.lock@@ -1968,14 +1968,14 @@ wheels = [[[package]]name = "kajson"-version = "0.5.0"+version = "0.6.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "pydantic" },]-sdist = { url = "https://files.pythonhosted.org/packages/91/9c/28a44cc51f328fe1076ea2114b6b7791ef49c54c24a07f11f86f83438da0/kajson-0.5.0.tar.gz", hash = "sha256:029b6a1b60ea28ec95b6f614656d1e48600e27c1f27a39c6e5681cd721854f64", size = 21969, upload-time = "2026-05-04T12:20:12.734Z" }+sdist = { url = "https://files.pythonhosted.org/packages/8d/54/83c3b00f270c39037b699398e42e16837ef1109c8af47ac668fe3c14a817/kajson-0.6.0.tar.gz", hash = "sha256:7544a544e6f135f129015c9475ff2cc0a7fc8e76d6eea1d8d37f2e438ab4d936", size = 22567, upload-time = "2026-05-30T19:06:08.084Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/2e/f4/6460fb07535ef71f87416e1d603f7eaaa9d2970161bec3e37fe08af74b45/kajson-0.5.0-py3-none-any.whl", hash = "sha256:53334fd7122e470ee560255eb5a8390b5ad60ea99bc0d6b75122b323379b553a", size = 28398, upload-time = "2026-05-04T12:20:11.202Z" },+ { url = "https://files.pythonhosted.org/packages/e9/fb/e325ef3bd84f2d40286a09fe78447a0a20e3a6ec12ce28e0d4ecc8bce620/kajson-0.6.0-py3-none-any.whl", hash = "sha256:77ddb0e12b274479ced061d84da091a250fdeb3f4dd7444ae0c6ca929ba73431", size = 29024, upload-time = "2026-05-30T19:06:06.645Z" },][[package]]@@ -3792,7 +3792,7 @@ requires-dist = [{ name = "instructor", extras = ["google-genai"], marker = "extra == 'google-genai'" },{ name = "jinja2", specifier = ">=3.1.4" },{ name = "json2html", specifier = ">=1.3.0" },- { name = "kajson", specifier = "==0.5.0" },+ { name = "kajson", specifier = "==0.6.0" },{ name = "linkup-sdk", marker = "extra == 'linkup'", specifier = ">=0.12.0" },{ name = "lxml", marker = "extra == 'docling'", specifier = ">=6.1.0" },{ name = "markdown", specifier = ">=3.6" },diff --git a/wip/dataclass-refactor-story.html b/wip/dataclass-refactor-story.htmlnew file mode 100644index 000000000..c566009fb--- /dev/null+++ b/wip/dataclass-refactor-story.html@@ -0,0 +1,335 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<meta name="viewport" content="width=device-width, initial-scale=1.0">+<title>Data-Class Refactor — result & the Temporal converter change</title>+<style>+ :root {+ --bg: #0f1117;+ --panel: #181b24;+ --panel-2: #1f2330;+ --ink: #e8eaf0;+ --muted: #9aa3b6;+ --line: #2c3142;+ --accent: #6ea8fe;+ --green: #5fd38f;+ --amber: #f0c060;+ --red: #f08a8a;+ --violet: #b08cf0;+ --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;+ }+ * { box-sizing: border-box; }+ body {+ margin: 0; background: var(--bg); color: var(--ink);+ font: 16px/1.62 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;+ -webkit-font-smoothing: antialiased;+ }+ .wrap { max-width: 940px; margin: 0 auto; padding: 52px 28px 110px; }+ header.hero { border-bottom: 1px solid var(--line); padding-bottom: 28px; margin-bottom: 36px; }+ .eyebrow { font: 600 12px/1 var(--mono); letter-spacing: .14em; text-transform: uppercase; color: var(--accent); }+ h1 { font-size: 32px; line-height: 1.18; margin: 14px 0 10px; letter-spacing: -.01em; }+ .sub { color: var(--muted); font-size: 17px; max-width: 720px; }+ .meta { margin-top: 16px; display: flex; flex-wrap: wrap; gap: 8px; }+ .chip { font: 600 12px/1 var(--mono); padding: 6px 10px; border-radius: 999px; background: var(--panel-2); border: 1px solid var(--line); color: var(--muted); }+ h2 { font-size: 21px; margin: 48px 0 14px; letter-spacing: -.01em; padding-left: 12px; border-left: 3px solid var(--accent); }+ h3 { font-size: 15px; margin: 26px 0 8px; color: var(--ink); font-family: var(--mono); }+ p { margin: 11px 0; }+ .muted { color: var(--muted); }+ strong { color: #fff; }+ code { font: 13.5px/1.5 var(--mono); background: var(--panel-2); padding: 1.5px 6px; border-radius: 5px; border: 1px solid var(--line); color: #d7def0; }+ .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 18px 20px; margin: 16px 0; }+ .callout { border-left: 3px solid var(--amber); background: var(--panel); border-radius: 0 10px 10px 0; padding: 13px 17px; margin: 16px 0; }+ .callout.bug { border-left-color: var(--red); }+ .callout.ok { border-left-color: var(--green); }+ .callout.key { border-left-color: var(--accent); }+ .callout .lbl { font: 600 11px/1 var(--mono); letter-spacing: .1em; text-transform: uppercase; color: var(--amber); }+ .callout.bug .lbl { color: var(--red); }+ .callout.ok .lbl { color: var(--green); }+ .callout.key .lbl { color: var(--accent); }+ .callout p { margin: 7px 0 0; }++ table { width: 100%; border-collapse: collapse; margin: 14px 0; font-size: 13.5px; }+ th, td { text-align: left; padding: 9px 11px; border-bottom: 1px solid var(--line); vertical-align: top; }+ th { font: 600 11px/1.3 var(--mono); letter-spacing: .06em; text-transform: uppercase; color: var(--muted); }+ td code { font-size: 12.5px; }+ .tag { font: 600 11px/1 var(--mono); padding: 3px 7px; border-radius: 6px; border: 1px solid var(--line); white-space: nowrap; }+ .tag.nt { color: var(--accent); border-color: #3a4a66; }+ .tag.pd { color: var(--violet); border-color: #4a3a66; }+ .tag.bmf { color: var(--green); border-color: #2f5d44; }+ .tag.bmm { color: var(--amber); border-color: #5d4f2c; }+ .yes { color: var(--green); font-weight: 700; }+ .no { color: var(--red); font-weight: 700; }+ tbody tr:hover { background: var(--panel); }++ .diff { background: #11141c; border: 1px solid var(--line); border-radius: 10px; overflow-x: auto; margin: 13px 0; font: 12.5px/1.7 var(--mono); }+ .diff .fname { padding: 8px 14px; border-bottom: 1px solid var(--line); color: var(--muted); background: var(--panel-2); font-weight: 600; }+ .diff pre { margin: 0; padding: 12px 14px; }+ .diff .add { color: var(--green); display: block; }+ .diff .del { color: var(--red); display: block; }+ .diff .ctx { color: #8b93a7; display: block; }+ .diff .hdr { color: var(--accent); display: block; }++ figure { margin: 20px 0; background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 18px 18px 10px; }+ figure pre.mermaid { background: transparent; border: 0; margin: 0; text-align: center; }+ figure svg { display: block; max-width: 100%; height: auto; margin: 0 auto; }+ figcaption { color: var(--muted); font-size: 12.5px; text-align: center; margin-top: 10px; font-family: var(--mono); }++ ul.tight { margin: 9px 0; padding-left: 22px; }+ ul.tight li { margin: 5px 0; }+ footer { margin-top: 56px; padding-top: 22px; border-top: 1px solid var(--line); color: var(--muted); font-size: 13px; }+</style>+</head>+<body>+<div class="wrap">++<header class="hero">+ <div class="eyebrow">refactor/Dataclasses · for co-developers</div>+ <h1>Data holders got the right shape — and the Temporal wire learned a new one</h1>+ <p class="sub">We removed every stdlib <code>@dataclass</code> from <code>pipelex/</code>, replacing each with the lowest-churn <em>correct</em> form per site instead of blanket <code>BaseModel</code>. The enabling change: the Temporal payload converter now serializes <strong>pydantic dataclasses</strong> with full type preservation, not just <code>BaseModel</code>.</p>+ <div class="meta">+ <span class="chip">refactor/Dataclasses → dev</span>+ <span class="chip">PR #949</span>+ <span class="chip">kajson 0.5.0 → 0.6.0</span>+ <span class="chip">9 prod files · 3 new test suites</span>+ </div>+</header>++<p>Two results to take away:</p>+<ol style="margin:10px 0 0; padding-left:20px">+ <li style="margin:6px 0"><strong>A rule for picking a data-holder shape</strong> (the decision tree below) — use it whenever you add or convert one.</li>+ <li style="margin:6px 0"><strong>A widened Temporal converter</strong> — pydantic dataclasses are now wire-legal, with the existing <code>BaseModel</code> path byte-for-byte unchanged.</li>+</ol>++<h2>Picking a shape</h2>++<p>No stdlib <code>@dataclass</code> survives in <code>pipelex/</code>. The easy fix would be to make everything a <code>BaseModel</code> — we deliberately didn't. We use four forms, picked by which capabilities the site actually needs:</p>++<table>+ <thead><tr><th>Form</th><th>Wire-legal</th><th>Capabilities we leverage</th><th>We use it for</th></tr></thead>+ <tbody>+ <tr>+ <td><span class="tag nt">NamedTuple</span></td>+ <td><span class="no">✗</span></td>+ <td>Named fields, immutable, positional-unpack compatible, and <strong>zero validation</strong> (so it can hold a bare Protocol or arbitrary type), no pydantic overhead.</td>+ <td>Small fixed records replacing bare tuples; holders of a <code>@runtime_checkable</code> Protocol or other non-pydantic field.</td>+ </tr>+ <tr>+ <td><span class="tag pd">pydantic dataclass</span></td>+ <td><span class="yes">✓</span></td>+ <td>Dataclass idioms — <code>field(default_factory=…)</code>, computed <code>@property</code>, <code>frozen=</code> — <strong>plus</strong> validation/coercion on construction. No <code>model_dump</code> / <code>model_validate</code>.</td>+ <td>Internal records that are built + field-read but <strong>never serialized</strong>. Lowest-churn swap from a stdlib <code>@dataclass</code> (just the decorator).</td>+ </tr>+ <tr>+ <td><span class="tag bmf">frozen BaseModel</span></td>+ <td><span class="yes">✓</span></td>+ <td>The full model API (<code>model_dump</code>, validators, discriminated unions), immutability, hashability, and — crucially — being <strong>type-distinct from <code>tuple</code></strong>.</td>+ <td>Immutable value objects that need the model API, sit in a uniformly-<code>BaseModel</code> layer, or must not be mistaken for a tuple in a union.</td>+ </tr>+ <tr>+ <td><span class="tag bmm">mutable BaseModel</span></td>+ <td><span class="yes">✓</span></td>+ <td>The full model API <strong>and</strong> in-place field mutation.</td>+ <td>Objects genuinely mutated in place that also want the model API or layer consistency. (Else a non-frozen pydantic dataclass is lighter.)</td>+ </tr>+ </tbody>+</table>++<p class="muted">The deciding question is the <strong>Wire-legal</strong> column crossed with "does it need the model API / serialization?" — the tree below walks exactly that:</p>++<figure>+<pre class="mermaid">+flowchart TD+ A["A data holder<br/>(stdlib @dataclass or bare tuple)"] --> B{"Crosses the<br/>Temporal wire?"}+ B -- "Yes" --> W["BaseModel or pydantic dataclass<br/>— nothing else is wire-legal —"]+ B -- "No (off-wire)" --> C{"A field is a bare Protocol /<br/>arbitrary non-pydantic type?"}+ C -- "Yes" --> NT["NamedTuple<br/>skips validation, no<br/>arbitrary_types_allowed dance"]+ C -- "No" --> D{"Returned in a union<br/>beside a real tuple?"}+ D -- "Yes" --> BM1["frozen BaseModel<br/>a BaseModel is NOT a tuple →<br/>isinstance stays unambiguous"]+ D -- "No" --> E{"Ever serialized? Needs<br/>model_dump / validators /<br/>discriminated unions?"}+ E -- "Yes" --> BM2["BaseModel<br/>(frozen or mutable)"]+ E -- "No" --> F{"Mutated in place<br/>after construction?"}+ F -- "Yes" --> PDM["pydantic dataclass<br/>(non-frozen)"]+ F -- "No" --> PDF["frozen pydantic dataclass<br/>lowest churn: swap the decorator"]++ classDef wire fill:#1f2330,stroke:#6ea8fe,color:#e8eaf0;+ classDef nt fill:#1f2330,stroke:#6ea8fe,color:#cfe0ff;+ classDef pd fill:#241f33,stroke:#b08cf0,color:#e7dcff;+ classDef bm fill:#1b2a22,stroke:#5fd38f,color:#d8f5e6;+ class W wire; class NT nt; class PDM,PDF pd; class BM1,BM2 bm;+</pre>+<figcaption>"Does this ever need serializing?" is the deciding question. If yes → BaseModel from the start. Never reach for TypeAdapter — needing it means the shape was wrong.</figcaption>+</figure>++<h3>What each type became</h3>+<table>+ <thead><tr><th>Type</th><th>Now</th><th>Why</th></tr></thead>+ <tbody>+ <tr><td><code>CrossPackageRef</code>, <code>StructureNameAndRefine</code></td><td><span class="tag nt">NamedTuple</span></td><td>Bare tuple returns; named fields stop positional swaps. All call sites positional-unpack.</td></tr>+ <tr><td><code>_EventLogContext</code> <span class="muted">(reporting)</span></td><td><span class="tag nt">NamedTuple</span></td><td>Holds a bare <code>@runtime_checkable</code> Protocol — NamedTuple skips validation, so no <code>arbitrary_types_allowed</code>.</td></tr>+ <tr><td><code>VariableReference</code> <span class="muted">(jinja2)</span></td><td><span class="tag pd">pydantic dataclass</span></td><td>Mutated in place (<code>.filters.append(…)</code>) → not frozen, no model API needed.</td></tr>+ <tr><td><code>ErrorPagesReport</code> <span class="muted">(errors)</span></td><td><span class="tag pd">frozen pydantic dataclass</span></td><td>Dev-tool report with <code>field(default_factory=…)</code> + a computed property; never serialized.</td></tr>+ <tr><td><code>CustomClassInfo</code> <span class="muted">(builder)</span></td><td><span class="tag bmf">frozen BaseModel</span></td><td>Lives in the uniformly-<code>BaseModel</code> builder layer.</td></tr>+ <tr><td><code>RegistrationFailure</code> <span class="muted">(temporal admin)</span></td><td><span class="tag bmf">frozen BaseModel</span></td><td>Returned as <code>X | tuple[str, ...]</code> — must stay type-distinct from the tuple arm.</td></tr>+ <tr><td><code>DispatchOptions</code> <span class="muted">(temporal)</span></td><td><span class="tag pd">frozen pydantic dataclass</span></td><td>Build-once-read-only; holds a live <code>RetryPolicy</code> (see the import note below).</td></tr>+ </tbody>+</table>++<h2>The Temporal converter change</h2>++<p><code>pipelex/temporal/temporal_data_converter.py</code> defines <strong><code>BaseModelPayloadConverter</code></strong> — the class Temporal calls to turn every workflow/activity argument and return value into bytes, and back. Pipelex sends selected values through <strong>kajson</strong> instead of Temporal's stock JSON, because kajson stamps each object with its <code>__class__</code> / <code>__module__</code> so the receiver rebuilds the <em>exact</em> Python class. Stock JSON would hand back a plain <code>dict</code> and lose the type.</p>++<p><strong>What changed:</strong> the set of values that take the kajson lane. Before, only <code>BaseModel</code>, <code>Optional[BaseModel]</code>, and <code>list[BaseModel]</code> qualified. Now pydantic dataclasses (and <code>Optional</code> / <code>list</code> of them) qualify too. The <code>BaseModel</code> lane is unchanged.</p>++<figure>+<svg viewBox="0 0 900 300" role="img" aria-label="Converter routing: kajson lane vs stock JSON lane">+ <defs>+ <marker id="a" markerWidth="9" markerHeight="9" refX="6" refY="3" orient="auto"><path d="M0,0 L6,3 L0,6 Z" fill="#9aa3b6"/></marker>+ <marker id="ag" markerWidth="9" markerHeight="9" refX="6" refY="3" orient="auto"><path d="M0,0 L6,3 L0,6 Z" fill="#5fd38f"/></marker>+ </defs>++ <!-- inputs -->+ <rect x="14" y="54" width="176" height="60" rx="9" fill="#1f2330" stroke="#2c3142"/>+ <text x="102" y="78" text-anchor="middle" fill="#9aa3b6" font-family="ui-monospace,Menlo,monospace" font-size="10">SERIALIZE</text>+ <text x="102" y="98" text-anchor="middle" fill="#e8eaf0" font-family="ui-monospace,Menlo,monospace" font-size="11.5">to_payload(value)</text>++ <rect x="14" y="186" width="176" height="60" rx="9" fill="#1f2330" stroke="#2c3142"/>+ <text x="102" y="210" text-anchor="middle" fill="#9aa3b6" font-family="ui-monospace,Menlo,monospace" font-size="10">DESERIALIZE</text>+ <text x="102" y="230" text-anchor="middle" fill="#e8eaf0" font-family="ui-monospace,Menlo,monospace" font-size="11">from_payload(.., type_hint)</text>++ <!-- gate -->+ <rect x="252" y="102" width="220" height="96" rx="11" fill="#181b24" stroke="#6ea8fe"/>+ <text x="362" y="128" text-anchor="middle" fill="#e8eaf0" font-family="ui-monospace,Menlo,monospace" font-size="12" font-weight="700">kajson wire shape?</text>+ <text x="362" y="152" text-anchor="middle" fill="#6ea8fe" font-family="ui-monospace,Menlo,monospace" font-size="10.5">_is_kajson_wire_value(value)</text>+ <text x="362" y="170" text-anchor="middle" fill="#6ea8fe" font-family="ui-monospace,Menlo,monospace" font-size="10.5">_is_kajson_type(type_hint)</text>+ <text x="362" y="188" text-anchor="middle" fill="#9aa3b6" font-family="ui-monospace,Menlo,monospace" font-size="10">BaseModel OR is_pydantic_dataclass</text>++ <line x1="190" y1="84" x2="252" y2="135" stroke="#9aa3b6" stroke-width="1.6" marker-end="url(#a)"/>+ <line x1="190" y1="216" x2="252" y2="165" stroke="#9aa3b6" stroke-width="1.6" marker-end="url(#a)"/>++ <!-- kajson lane -->+ <rect x="560" y="40" width="326" height="104" rx="11" fill="#1b2a22" stroke="#2f5d44"/>+ <text x="576" y="64" fill="#5fd38f" font-family="ui-monospace,Menlo,monospace" font-size="12" font-weight="700">kajson lane — type preserved</text>+ <text x="576" y="84" fill="#cfe0d8" font-family="ui-monospace,Menlo,monospace" font-size="10.5">kajson.dumps / kajson.loads (+ __class__ / __module__ tags)</text>+ <text x="576" y="108" fill="#9aa3b6" font-family="ui-monospace,Menlo,monospace" font-size="10.5">BaseModel · Optional[X] · list[X] (unchanged)</text>+ <text x="576" y="126" font-family="ui-monospace,Menlo,monospace" font-size="10.5"><tspan fill="#b08cf0" font-weight="700">+ pydantic dataclass</tspan><tspan fill="#9aa3b6"> — newly routed here</tspan></text>++ <!-- stock lane -->+ <rect x="560" y="196" width="326" height="68" rx="11" fill="#1a1a1f" stroke="#3a3f4d"/>+ <text x="576" y="222" fill="#cdd5e6" font-family="ui-monospace,Menlo,monospace" font-size="12" font-weight="700">super().to_payload / from_payload</text>+ <text x="576" y="244" fill="#9aa3b6" font-family="ui-monospace,Menlo,monospace" font-size="10.5">Temporal stock JSON — type identity lost (plain dict back)</text>++ <line x1="472" y1="130" x2="560" y2="92" stroke="#5fd38f" stroke-width="1.8" marker-end="url(#ag)"/>+ <text x="516" y="100" text-anchor="middle" fill="#5fd38f" font-family="ui-monospace,Menlo,monospace" font-size="10">wire shape</text>+ <line x1="472" y1="172" x2="560" y2="226" stroke="#9aa3b6" stroke-width="1.6" marker-end="url(#a)"/>+ <text x="514" y="208" text-anchor="middle" fill="#9aa3b6" font-family="ui-monospace,Menlo,monospace" font-size="10">everything else</text>+</svg>+<figcaption>The converter is a router. The only change is the gate: the kajson lane now also admits pydantic dataclasses. Both lanes were already there.</figcaption>+</figure>++<h3>Two directions, two checks</h3>+<p>Serialization holds the actual <em>value</em>; deserialization holds only the declared <em>type hint</em>. So the same question is asked two ways:</p>+<ul class="tight">+ <li><strong><code>to_payload</code></strong> asks <code>_is_kajson_wire_value(value)</code> = <code>isinstance(value, BaseModel) or is_pydantic_dataclass(type(value))</code>.</li>+ <li><strong><code>from_payload</code></strong> asks <code>_is_kajson_type(type_hint)</code> — the same test one level up — and reuses it for the scalar, <code>Optional[X]</code>, and <code>list[X]</code> shapes.</li>+</ul>++<p>The old code inlined the <code>BaseModel</code> checks and <strong>duplicated</strong> the payload/metadata building across the scalar and list branches. We factored that into <code>_kajson_to_payload</code> + <code>_first_kajson_list_element</code>, then added the dataclass arm <em>behind</em> the <code>BaseModel</code> short-circuit so the hot path is untouched:</p>++<div class="diff">+ <div class="fname">temporal_data_converter.py — to_payload (serialize)</div>+<pre><span class="del">- if isinstance(value, BaseModel):</span>+<span class="del">- payload_str = kajson.dumps(value)</span>+<span class="del">- metadata = {"encoding": self.encoding.encode()}</span>+<span class="del">- class_source = getattr(type(value), "__kajson_class_source__", None)</span>+<span class="del">- ... # the same 6 lines, duplicated again below</span>+<span class="del">- elif isinstance(value, list) and value and isinstance(value[0], BaseModel):</span>+<span class="del">- ...</span>+<span class="del">- else:</span>+<span class="del">- return super().to_payload(value)</span>+<span class="add">+ if self._is_kajson_wire_value(value): # scalar: BaseModel or pydantic dataclass</span>+<span class="add">+ return self._kajson_to_payload(value, source_type_holder=value)</span>+<span class="add">+ list_head = self._first_kajson_list_element(value) # list[...] whose head is a wire value</span>+<span class="add">+ if list_head is not None:</span>+<span class="add">+ return self._kajson_to_payload(value, source_type_holder=list_head)</span>+<span class="add">+ return super().to_payload(value) # everything else → stock JSON</span>+</pre>+</div>++<div class="diff">+ <div class="fname">temporal_data_converter.py — the two predicates + from_payload reuse</div>+<pre><span class="add">@classmethod</span>+<span class="add">def _is_kajson_wire_value(cls, value: object) -> bool: # used by to_payload (has the value)</span>+<span class="add"> return isinstance(value, BaseModel) or is_pydantic_dataclass(type(value))</span>++<span class="add">@classmethod</span>+<span class="add">def _is_kajson_type(cls, type_hint: Any) -> bool: # used by from_payload (has the hint)</span>+<span class="add"> if isinstance(type_hint, type) and issubclass(type_hint, BaseModel):</span>+<span class="add"> return True</span>+<span class="add"> return is_pydantic_dataclass(cast("Any", type_hint)) # safe (False) on non-class hints</span>++<span class="ctx"> # from_payload now routes through _is_kajson_type for all three shapes:</span>+<span class="del">- if isinstance(type_hint, type) and issubclass(type_hint, BaseModel): ... # scalar</span>+<span class="del">- if self._unwrap_optional_base_model(type_hint): ... # Optional[BaseModel]</span>+<span class="del">- if origin is list and ... and issubclass(args[0], BaseModel): ... # list[BaseModel]</span>+<span class="add">+ if self._is_kajson_type(type_hint): ... # scalar</span>+<span class="add">+ if self._unwrap_optional_kajson_type(type_hint): ... # Optional[X]</span>+<span class="add">+ if origin is list and ... and self._is_kajson_type(args[0]): ... # list[X]</span>+</pre>+</div>++<div class="callout ok">+ <span class="lbl">Two guarantees</span>+ <p><strong>BaseModel path is byte-identical</strong> — locked by a regression test that asserts a <code>BaseModel</code> payload's metadata and bytes are exactly what the old code produced. And <strong>it's strictly safer</strong>: the old <code>list</code> branch called <code>issubclass(args[0], BaseModel)</code> directly, which <em>raised</em> on a non-class arg like <code>list[list[int]]</code>; <code>_is_kajson_type</code> guards with <code>isinstance(.., type)</code> first.</p>+</div>++<p class="muted">The receiving half is in kajson itself (bumped 0.5.0 → 0.6.0): a new decode branch calls <code>is_pydantic_dataclass(cls)</code> and reconstructs via <code>cls(**data)</code> — running the validator and raising loudly on bad input, instead of the old untested catch-all that silently returned a raw dict.</p>++<h2>Three things worth knowing</h2>++<div class="callout bug">+ <span class="lbl">A NamedTuple is a tuple</span>+ <p><code>RegistrationFailure</code> is returned as <code>RegistrationFailure | tuple[str, ...]</code> and callers do <code>isinstance(x, RegistrationFailure)</code>. A <code>NamedTuple</code> would also satisfy <code>isinstance(x, tuple)</code>, blurring the two arms — so it's a <strong>frozen BaseModel</strong>, which is cleanly not-a-tuple. Whenever a value is returned in a union beside a real tuple, model it.</p>+</div>++<div class="callout key">+ <span class="lbl">DispatchOptions stays importable without temporalio</span>+ <p>It holds a live <code>temporalio</code> <code>RetryPolicy</code>, but <code>temporalio</code> is an optional extra. A bare forward ref imports but blows up (<code>PydanticUserError</code>) on <em>construction</em>. The fix is a runtime placeholder so the field resolves to <code>Any</code> without importing temporalio:</p>+<div class="diff" style="margin-top:10px">+<pre><span class="ctx"> if TYPE_CHECKING:</span>+<span class="ctx"> from temporalio.common import RetryPolicy # type checkers see the real class</span>+<span class="add">+else:</span>+<span class="add">+ RetryPolicy = Any # runtime: no import, no validation</span>+</pre>+</div>+</div>++<div class="callout ok">+ <span class="lbl">Don't convert the wire BaseModels</span>+ <p>The widening makes pydantic dataclasses <em>legal</em> on the wire; it does <strong>not</strong> motivate converting the types already there (<code>PipeJob</code>, <code>PipeOutput</code>, <code>WorkingMemory</code>, <code>Stuff</code>, the <code>StuffContent</code> union, <code>GraphSpec</code>, …). They stay <code>BaseModel</code> — they need discriminated unions, model validators, and the dynamic-class mechanism. A NamedTuple or stdlib dataclass on the wire silently corrupts distributed execution.</p>+</div>++<div class="callout bug">+ <span class="lbl">Release gate (tracked, not dev-blocking)</span>+ <p>kajson <code>0.6.0</code> is pinned via <code>[tool.uv.sources]</code> to a git rev. That section is uv-dev-only — the hatchling build strips it, so a published pipelex wheel would require <code>kajson==0.6.0</code> from PyPI, which isn't there yet. Safe on <code>dev</code> (PyPI publish fires only on <code>main</code> / <code>pre-release/v*</code>). Before any release: publish kajson 0.6.0 to PyPI, drop the git source, confirm it resolves.</p>+</div>++<footer>+ Verified green: <code>make agent-check</code> (Pyright 0/0, Mypy clean) · <code>make tb</code> · the Temporal integration suite (converter round-trips, in-process-server workflow round-trip, no-temporalio subprocess test) · <code>make agent-test</code>. Final gate: zero stdlib <code>@dataclass</code> in <code>pipelex/</code>. Source of truth: <code>TODOS.md</code> on <code>refactor/Dataclasses</code>.+</footer>++</div>++<script type="module">+ import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';+ mermaid.initialize({+ startOnLoad: true, theme: 'dark', securityLevel: 'loose',+ themeVariables: {+ background: '#181b24', primaryColor: '#1f2330', primaryBorderColor: '#2c3142',+ primaryTextColor: '#e8eaf0', lineColor: '#6ea8fe', secondaryColor: '#241f33',+ tertiaryColor: '#11141c', fontFamily: 'ui-monospace, Menlo, Consolas, monospace', fontSize: '13px'+ }+ });+</script>+</body>+</html>diff --git a/wip/error-handling/archive-todos-api-readiness-4.md b/wip/error-handling/archive-todos-api-readiness-4.mdnew file mode 100644index 000000000..2d875bbcc--- /dev/null+++ b/wip/error-handling/archive-todos-api-readiness-4.md@@ -0,0 +1,181 @@+# Implementation Plan — `feature/API-readiness-4`++Pipelex-side cleanup branch picking up the upstream tail of the API error-handling endeavour. The API consumer (`pipelex-api`, branch `feature/Adapt-to-pipelex-update-3`) has shipped through Phases 0-5 plus Phase A0 / A1 and is at a "finalize" moment; what remains for the API to fully discharge that endeavour is a handful of upstream-pipelex items. **This branch is those items.**++---++## Cold-start reading order++Read in this order to understand why this branch exists at all:++1. `wip/error-handling/README.md` — current state of error handling across pipelex; the high-level map.+2. `wip/error-handling/archive-todos-api-readiness-2.md` — the prior ledger (formerly the repo-root `TODOS.md`, archived 2026-05-28). This branch is the successor.+3. `../pipelex-api/wip/pipelex-changes.md` Stage 7 (items #10-#15) — the **authoritative per-item context** for five of the items on this branch. Each item there has a *What / Why / Where / How* writeup with empirical reproductions against the pinned pipelex. Do not re-derive that context here; consume it from there.+4. `../pipelex-api/TODOS.md` "Deferred / next-track work" → "Upstream-pipelex follow-ups" — names the same items at the API end, in the consumer's voice. Useful sanity check.+5. `wip/console-targets-and-agent-cli-stdout.md` and `wip/structured-logging/kickoff.md` — relevant background for the **webhook-delivery logging** item below; see the sequencing note in that section before starting.++The `test_failed_webhook_log_includes_request_id_when_set` regression test already landed on the base (`feature/API-readiness-2`, commit `74b68bd7`) and is present in the working tree — do **not** re-add it. `git log feature/API-readiness-2..HEAD --oneline` shows this branch adds only planning docs on top of that base. Everything below is what to implement.++---++## What this branch is NOT++- Not the structured-logging refactor. That has its own kick-off doc and its own future branch (`refactor/structured-logging` or similar — see `wip/structured-logging/kickoff.md`).+- Not webhook signing. That's the cross-repo lockstep track owned by `wip/security/webhook-signing.md`.+- Not a `dev` merge train. If `dev` has moved, treat that as a separate prep step, not part of this plan.++---++## Items++Six concrete items, all flagged in `pipelex-changes.md` Stage 7 or surfaced by the API-side `TODOS.md`. None blocks any API release on its own; together they discharge the upstream tail of the error-handling endeavour and let the API drop a small number of follow-up catches and workarounds.++Sequencing inside this branch is flexible — every item is independent except where called out. Suggested order is "smallest first to build momentum, then the two bigger ones."++### 1. `ErrorDomain.is_input` (and siblings) — `@property` helpers on the enum++- [x] **Status:** Done (2026-05-28). Two pieces landed in `pipelex/base_exceptions.py`: (a) `ErrorDomain.is_input` as an exhaustive-`match` `@property` (the enum-level single source of truth), and (b) a module-level `error_domain_is_input(error_domain: ErrorDomain | str | None) -> bool` that coerces the serialized form and delegates to the property — paralleling the existing `error_domain_to_http_status(...)`. The function is the one the API actually consumes: both API call sites hold `error_domain` as `str | None` (`ErrorReport.error_domain` is typed `str | None`; the problem-document dict value is a plain str), so the bare `report.error_domain.is_input` the spec sketched would not type-check. Covered by `tests/unit/pipelex/exceptions/test_error_domain.py::TestErrorDomain` (`test_is_input` + `test_error_domain_is_input`). Only `is_input` landed — `is_config` / `is_runtime` deferred until a need surfaces. The API consumes this via the editable local dependency on this worktree (no PyPI pin bump needed); the API-side switch off `== ErrorDomain.INPUT` at `api/exception_handlers.py:204,253` is being made now.+**Authoritative spec:** `../pipelex-api/wip/pipelex-changes.md` item #14.+**Where:** `pipelex/base_exceptions.py` — the `ErrorDomain` `StrEnum`.++Add `@property` helpers (`is_input`, and `is_config` / `is_runtime` as needs surface) so callers read state via `report.error_domain.is_input` instead of `report.error_domain == ErrorDomain.INPUT`. This is the canonical project remediation for single-state enum checks (see `python-standards.md`) — call sites stay one-liners, the enumeration lives in one place.++**Sequence first:** every other item benefits from being able to use the helper at call sites it touches. Trivial change; ~20 lines + a test. The API-side `archive-todos-api-readiness-2.md` Phase 3 review Q9 left two call sites in `api/exception_handlers.py` deliberately on `== ErrorDomain.INPUT` waiting for this; one follow-up commit there will switch them once this lands.++---++### 2. `EnvVarNotFoundError` should carry `error_domain = ErrorDomain.CONFIG`++- [x] **Status:** Done (2026-05-28). Added `error_domain = ErrorDomain.CONFIG` as a class attribute on `EnvVarNotFoundError` in `pipelex/system/exceptions.py`, so its rendered `ErrorReport` / RFC 7807 problem document classifies as a config-domain failure (an operator sets the missing env var, not the caller). HTTP status is unchanged — both `None` and `CONFIG` map to 500. Covered by `tests/unit/pipelex/exceptions/test_class_level_metadata.py::TestClassLevelMetadata::test_error_domain` (new `env_var_not_found` parametrize case). The API consumes this via the editable local dependency on this worktree.+**Authoritative spec:** `../pipelex-api/wip/pipelex-changes.md` item #10.+**Where:** `pipelex/system/exceptions.py` (note: moved here from `pipelex/system/environment.py` during the Phase 6 import-path moves the API already adapted to — the spec doc still names the old path).++Today `EnvVarNotFoundError` is domain-less (it's a `ToolError`; neither parent sets `error_domain`). A missing required env var is the textbook `CONFIG`-domain failure — an operator, not the caller, fixes it. Add `error_domain = ErrorDomain.CONFIG` as a ClassVar so the rendered `ErrorReport` / RFC 7807 problem document classifies correctly. HTTP status is unaffected (both `None` and `CONFIG` map to 500).++This is the upstream half of the "original bug" the entire endeavour started from — a deployment that forgot to set `COMPLETION_CALLBACK_SECRET`. The API already classifies its own config faults as `CONFIG`; this brings pipelex-authored ones into alignment.++---++### 3. `parse_concept_spec` should validate `structure` shape before iterating++- [x] **Status:** Done (2026-05-28). Two parsing functions now shape-validate raw caller input before iterating, raising typed `INPUT`-domain errors instead of leaking bare `AttributeError`/`TypeError`/`ValueError`. (a) `parse_concept_spec` (`concept_ops.py`) rejects a non-mapping `structure` and any field value that is neither a description string nor a field-spec mapping, raising `ConceptSpecError`. (b) `parse_pipe_spec` (`pipe_ops.py`) rejects a non-list `steps`/`branches` or a non-mapping entry within them, raising the new `PipeSpecError`; the raw-iterate logic moved into a shared `_normalize_sub_pipe_list(...)` helper. Both error classes now carry `error_domain = ErrorDomain.INPUT` + `_authors_caller_facing_message = True` — `ConceptSpecError` (`builder/concept/exceptions.py`) gained the domain (it was previously domain-less); `PipeSpecError` is new (`builder/pipe/exceptions.py`). Docstrings on both functions now list every exception actually raised. Covered by new cases in `tests/unit/pipelex/builder/operations/test_parse_concept_spec.py` and `test_parse_pipe_spec.py` (typed-error + INPUT-domain assertions). Verified end-to-end through both consumers: `pipelex-agent concept`/`pipe` now emit `{"error_type": "ConceptSpecError"|"PipeSpecError", "error_domain": "input"}` instead of a bug-looking bare type. Error doc pages regenerated (`pipelex-dev generate-error-pages`) — added `pipe-spec-error.md`, refreshed `concept-spec-error.md`; the run also picked up two pre-existing stale pages unrelated to this item (`env-var-not-found-error.md` from item #2, and a missing `async-execution-not-enabled-error.md`). The API consumes this via the editable local dependency on this worktree; the API-side narrow `/build/concept` + `/build/pipe` route catches are API-side follow-ups, not this branch.+**Authoritative spec:** `../pipelex-api/wip/pipelex-changes.md` item #11.+**Where:** `pipelex/builder/operations/concept_ops.py` — the `parse_concept_spec(...)` function.++The function iterates `spec_data["structure"]` before calling `ConceptSpec.model_validate(...)`. Non-dict `structure`, or fields that are neither string nor dict, leak bare `AttributeError` / `TypeError` (undocumented; the docstring only declares `ValidationError`). Empirical reproductions live in the spec doc.++Fix is upstream shape validation — either raise a typed `PipelexInputError`-equivalent, or a `pydantic.ValidationError` via a thin `model_validate(...)` over the raw input shape before the iteration. Update the docstring to list every exception actually raised.++The API today cannot safely catch these at the route — `AttributeError` / `TypeError` are also the types a real programming bug would raise, so a route-level catch would mask genuine bugs. Once this lands, the API's `/build/concept` route gets a narrow, typed catch.++While here: sweep `pipelex/builder/operations/*.py` for the same pattern (raw-iterate-then-validate). `parse_pipe_spec` has it too — it iterates `spec_data["steps"]` / `spec_data["branches"]` and calls `dict(step)` on each entry before `model_validate`, so a non-list `steps` / `branches` or non-mapping entries leak bare `TypeError` / `ValueError` ahead of validation. Route those through the same narrow shape-validation path before iterating. (The bad-`pipe_type` `ValueError` is a separate, already-documented case — that one is narrow enough to leave.)++---++### 4. `LocalStorageProvider` should wrap raw `OSError` as a `StorageLocalError`++- [x] **Status:** Done (2026-05-28). Added `StorageLocalError(StorageError)` (with `_declared_title = "Local storage error"`) to `pipelex/tools/storage/exceptions.py`, paralleling `StorageS3Error` / `StorageGcpError`. Both filesystem methods in `local_storage_provider.py` now wrap raw `OSError`: `_store` wraps the `mkdir` + `aiofiles.open(...).write(...)` block (`ENOSPC` / `EACCES` / `EROFS` / `FileExistsError` / `EIO` → `StorageLocalError`); `_load_with_metadata` wraps the `aiofiles.open(...).read()` call, with an explicit `except FileNotFoundError` branch first that routes the TOCTOU window (file removed between the `exists()` check and the open) to `StorageFileNotFoundError`, so "file not found" stays the same typed error regardless of timing, and a generic `except OSError` → `StorageLocalError` for the rest (`PermissionError` / `IsADirectoryError` / `EIO`). `public_url` does no filesystem I/O, so it's untouched. Docstrings updated to list `StorageLocalError`. Covered by three new cases in `tests/unit/pipelex/tools/storage/test_local_storage_provider.py` (store→`FileExistsError` via blocker file, load→`IsADirectoryError` via dir-at-key, load→TOCTOU `FileNotFoundError` via `aiofiles.open` monkeypatch) — each asserts the typed wrapper and `__cause__` is an `OSError`. Error doc page generated (`pipelex-dev generate-error-pages`) — added `storage-local-error.md`, refreshed `index.md`; no incidental stale pages this run. The API consumes this via the editable local dependency on this worktree; the API-side narrow storage-route catches are API-side follow-ups, not this branch.+**Authoritative spec:** `../pipelex-api/wip/pipelex-changes.md` item #12.+**Where:** `pipelex/tools/storage/local_storage_provider.py` — `_store` and `_load_with_metadata`.++Today, `ENOSPC` / `EACCES` / `EROFS` / `EIO` / `FileExistsError` / TOCTOU window after `file_path.exists()` all escape as raw `OSError`. Add a narrow `try/except OSError as exc: raise StorageLocalError(msg) from exc` around the filesystem calls — mirroring the wrapping already done by `S3StorageProvider` / `GcpStorageProvider`. Empirical reproductions are in the spec doc.++**Decision:** Add a new `StorageLocalError(StorageError)` to `pipelex/tools/storage/exceptions.py`, paralleling `StorageS3Error` / `StorageGcpError` (with a `_declared_title = "Local storage error"`). Keeps per-backend differentiation consistent across the storage abstraction.++Pair-test with item #5 (S3) — both deliver on the same storage-abstraction contract; same review can cover both.++---++### 5. `S3StorageProvider` should catch the full `BotoCoreError` hierarchy++- [x] **Status:** Done (2026-05-28). All three methods in `s3_storage_provider.py` now wrap the entire `BotoCoreError` hierarchy instead of only `NoCredentialsError` / `EndpointConnectionError`. In `_load_with_metadata` and `_store` the final `except (NoCredentialsError, EndpointConnectionError)` branch was broadened to `except BotoCoreError as exc: raise StorageS3Error(f"S3 backend error for key '{key}': {type(exc).__name__}") from exc`, sitting after the `ClientError` *sibling* branch (kept separate — `ClientError` is not a `BotoCoreError` subclass, verified empirically) and after the two service-specific `client.exceptions.NoSuchKey` / `NoSuchBucket` branches (unchanged). This closes the real-world leak: `ReadTimeoutError` / `ConnectTimeoutError` / `ConnectionClosedError` / `PartialCredentialsError` / `CredentialRetrievalError` / `ProxyConnectionError` (all `BotoCoreError` subclasses) previously escaped unwrapped; the most likely one, `ReadTimeoutError` on a slow/transient transfer, now surfaces as a typed `StorageS3Error`. `public_url`'s presign fallback widened from `except ClientError` → `except (BotoCoreError, ClientError)`, preserving the existing "if signing fails, serve the unsigned public URL" semantics for transport failures too. Per the decision, **no new sub-error class** — wrapping stays on the existing `StorageS3Error`, so no doc page work (generator confirms 0 drift: `Written: 0 · Unchanged: 245`). Covered by three new cases in `tests/unit/pipelex/tools/storage/test_s3_storage_provider.py` (`test_load_read_timeout_error_raises_s3_error`, `test_store_read_timeout_error_raises_s3_error`, `test_public_url_falls_back_to_public_url_on_botocore_error`); the three pre-existing `NoCredentialsError` / `EndpointConnectionError` tests were updated to assert the new message (`type(exc).__name__` in the text) and that `__cause__` is a `BotoCoreError`. The lower-priority `_get_session()`-outside-the-try side issue (a `BotoCoreError` from boto's own session-startup path could still escape) is left as-is — flag in the PR, don't gate on it. The API consumes this via the editable local dependency on this worktree; the API-side narrow storage-route catches are API-side follow-ups, not this branch.+**Authoritative spec:** `../pipelex-api/wip/pipelex-changes.md` item #13.+**Where:** `pipelex/tools/storage/s3_storage_provider.py` — `_load_with_metadata`, `_store`, and `public_url`.++The provider catches only three `BotoCoreError` subclasses (`NoCredentialsError`, `EndpointConnectionError`) plus `ClientError` (which is a *sibling*, not a subclass, of `BotoCoreError`). Every other `BotoCoreError` subclass — `ReadTimeoutError`, `ConnectTimeoutError`, `ConnectionClosedError`, `PartialCredentialsError`, `CredentialRetrievalError`, `ProxyConnectionError`, … — escapes unwrapped. `ReadTimeoutError` is the most likely real-world leak (transient AWS networking).++Fix: broaden each `except` block from `(NoCredentialsError, EndpointConnectionError)` to `BotoCoreError`, keeping the `ClientError` branch as a separate sibling `except`. The two service-specific branches at the top (`NoSuchKey`, `NoSuchBucket`) stay. `public_url`'s `try/except ClientError → return public URL` fallback should likely widen the same way.++**Decision:** Keep wrapping as the existing `StorageS3Error(StorageError)` — no new sub-error class needed for the broadened catch. (Symmetric to item #4's `StorageLocalError` addition.)++Lower-priority side issue noted in the spec doc: `_get_session()` runs outside every method's try block. Mention in the PR but don't gate on it.++---++### 6. Webhook-delivery SSRF DNS recheck++- [x] **Status:** Done (2026-05-28). Greenfield `pipelex/tools/network/` package now closes the DNS-rebinding gap at webhook-delivery time. Three modules: (a) `host_rules.py` — `is_disallowed_ip(host)` (**deny-by-default**: `not addr.is_global`, so private/loopback/link-local — incl. `169.254.169.254` — /CGNAT `100.64/10`/shared/documentation/benchmarking/unspecified are all refused in one predicate, plus explicit `is_multicast`/`is_reserved` because `ipaddress` marks the `224.0.0.0/4` and `64:ff9b::/96` NAT64 ranges as `is_global`) + `is_disallowed_host(host)` (empty / known internal hostname `localhost`·`metadata`·`metadata.google.internal` / literal disallowed IP) — this is the single source of truth, and it is **stricter than the API's current enumerate-the-bad-ranges `_is_disallowed_host`** (the deny-by-default form closes a CGNAT leak the API check has; the API inherits the tightening when it re-points at this helper); (b) `exceptions.py` — `SsrfBlockedError(SecurityError)` with `error_domain = ErrorDomain.INPUT` (destination is caller-supplied — fixable by providing a public URL) and `_authors_caller_facing_message = True` (message names only the caller's own hostname, never the resolved private IP, so STRICT disclosure cannot confirm internal topology); (c) `ssrf_guard.py` — `SsrfGuardedTransport(httpx.AsyncHTTPTransport)` whose `resolve_to_allowed_ip(host, port)` short-circuits literal-disallowed hosts, resolves via `loop.getaddrinfo` (→ `socket.getaddrinfo`, monkeypatch-able), refuses if **any** resolved IP is disallowed (a mixed public/private resolution is itself a rebinding signal), maps a genuine `socket.gaierror` → `httpcore.ConnectError` (so a real DNS failure keeps its normal `httpx.ConnectError` → `WebhookDeliveryError` path), and connects to the **first vetted IP** (a literal → `getaddrinfo` does no DNS, so no rebind can slip between the check and the socket). **Seam choice:** on pinned `httpx` 0.28.1 / `httpcore` 1.0.9 there is no public `network_backend` kwarg and no resolver/DNS hook (event hooks are request/response only), so the guard wraps the connection pool's `_network_backend` in place via a custom `httpcore.AsyncNetworkBackend` (`SsrfGuardedBackend`). This intercepts only the TCP connect — TLS SNI / cert verification and the `Host` header keep using the origin **hostname** automatically, because `httpcore._async.connection.AsyncHTTPConnection._connect` derives `server_hostname` from the origin, not from what `connect_tcp` dials. One private-attr touch (`self._pool._network_backend`) carries the repo's established `# noqa: SLF001 # pyright: ignore[reportPrivateUsage]`. `delivery_executor._notify_webhook` now builds `httpx.AsyncClient(transport=SsrfGuardedTransport())`; `SsrfBlockedError` — a `SecurityError` — is deliberately **not** re-wrapped as `WebhookDeliveryError`, so it propagates and the delivery aborts loudly (security signals must not be swallowed by the domain-level `except httpx.RequestError`). Covered by `tests/unit/pipelex/tools/network/test_host_rules.py` (`TestHostRules` — literal-IP + hostname classification), `test_ssrf_guard.py` (`TestSsrfGuard` — public/private/literal/mixed/`gaierror` resolution + a real `httpx.AsyncClient` driven through the guarded transport aborting before any socket), and an end-to-end `test_webhook_aborts_on_dns_rebind_to_private_ip` in `tests/unit/pipelex/pipe_run/test_delivery_executor.py` (`execute()` aborts with `SsrfBlockedError` via a `socket.getaddrinfo` monkeypatch returning `169.254.169.254` — no live network). Error doc page generated (`pipelex-dev generate-error-pages`): `docs/errors/ssrf-blocked-error.md` + a one-line index refresh under `SecurityError`. `make agent-check` clean (pyright 0, mypy 0, ruff/plxt clean); targeted unit + integration-pipes suites green. **Naming deviation:** named `SsrfBlockedError` (generic — the transport guards any caller-supplied outbound URL, not only webhooks) rather than the spec's tentative `WebhookDeliverySsrfBlocked`, per the "(or whatever the typed error ends up named)" latitude; it still lives in `pipelex/tools/network/exceptions.py` per the error-location convention (not co-located with the helper). **API-side migration note:** the API doc says `from pipelex.tools.network import is_disallowed_host`, but `__init__.py` is kept empty per the no-re-export-in-`__init__` rule — the real import path is `from pipelex.tools.network.host_rules import is_disallowed_host`. **Tradeoffs to flag in the PR:** (1) the guard connects to the first vetted IP, forgoing httpx/anyio happy-eyeballs multi-IP fallback for webhooks (acceptable — pinning to a vetted IP is the whole point); (2) an egress allowlist / proxy at the deploy layer stays out of scope. The API-side narrow catch + re-point of `_is_disallowed_host` is an API-side follow-up, not this branch.+**Where:** `pipelex/pipe_run/delivery_executor.py` — wherever the webhook HTTP client (`httpx`) actually fires.++The API's `api/schemas/models.py::_is_disallowed_host` only blocks literal private / loopback / metadata IPs **at request time**. A callback URL like `https://attacker.example/cb` passes API-side validation while its DNS record can resolve to `169.254.169.254` / `127.0.0.0/8` / `10.0.0.0/8` when the worker later fires the webhook. The fix belongs at delivery time:++- A custom `httpx` transport / `httpcore` network backend whose connect step resolves the host, checks every resolved IP against the same private-host rule, and refuses to open the socket to a private / metadata destination. Note: on the pinned `httpx` 0.28.1, `AsyncHTTPTransport` exposes **no** resolver hook, and event hooks are `request` / `response` only — neither fires after DNS but before payload send — so a plain event hook cannot close the DNS-rebinding gap.+- Or an explicit resolve-and-connect flow: resolve the hostname (`socket.getaddrinfo`), validate each candidate IP against the rule, then connect to a vetted IP while preserving the original `Host` header / SNI — so a rebind between validation and send is impossible.+- Plus optionally an egress allowlist / proxy at the deploy layer (out of scope here — flag in the PR description so the deploy team sees it).++The literal-host check on the API side stays as a cheap first line of defense.++**Test fixture:** synthesize a webhook URL whose DNS resolves to a private IP (use a `socket.getaddrinfo`-style monkeypatch or a test resolver). Confirm the delivery aborts with a typed error (likely a new `WebhookDeliverySsrfBlocked` or similar) rather than completing the request.++**Decision — rule placement.** Create a new `pipelex/tools/network/` package (greenfield — no `network` module exists today under `pipelex/tools/`) and put the rule in `pipelex.tools.network.is_disallowed_host(...)`. The API-side `_is_disallowed_host` in `pipelex-api/api/schemas/models.py` gets re-pointed at this helper, so the CIDR set lives in one place. Follow the error-location convention: `pipelex/tools/network/exceptions.py` for `WebhookDeliverySsrfBlocked` (or whatever the typed error ends up named) — do not co-locate the error with the helper.++---++### 7. Structured `event=webhook_delivery` / `event=webhook_failure` logging — **DEFERRED to structured-logging refactor**++- [x] **Status:** Closed-by-deferral on this branch (2026-05-28). Re-scoped onto the `refactor/structured-logging` branch.+**Where (for the deferral):** `wip/structured-logging/kickoff.md` "What good looks like" — event-name emission now in scope.++The lines this item would have touched (`pipelex/pipe_run/delivery_executor.py` around 239 / 243 / 280 / 282 / 285) are exactly the lines the structured-logging refactor lists as deletion targets (`request_id_suffix` pattern, kwarg threading from commits `ceb018b5` / `07f9cce9`). Doing a narrow event-name pass on this branch would touch those lines twice.++**Follow-up actions when the structured-logging branch starts:**++- Emit `event=webhook_delivery` / `event=webhook_failure` (and `event=storage_delivery` / `event=storage_failure` for symmetry) as structured fields once the new `log.info(msg, **fields)` surface lands. Document this in the kickoff doc's destination shape.+- Re-target the API-side TODO in `../pipelex-api/TODOS.md` "Deferred / next-track work" → "Upstream-pipelex follow-ups" from this branch onto the structured-logging branch.++The API-side T6 test (`pipelex-api/tests/unit/test_webhook_recovery.py`) pins error-rendering consistency, not event names, so the API is not blocked on event-name emission.++---++## Out of scope (for this branch — recorded so they don't drift back in)++- **Structured-logging refactor.** Its own branch and PR. See `wip/structured-logging/kickoff.md`.+- **Webhook signing.** Cross-repo, lockstep. See `wip/security/webhook-signing.md`.+- **Item #15 — kajson crafted-marker exceptions.** Target repo is `kajson`, **not** `pipelex`. Belongs on a separate kajson PR. Spec lives at `../pipelex-api/wip/pipelex-changes.md` item #15; the API has a workaround in place (`_decode_body`'s widened catch tuple). Re-target there if Louis wants this on the same release train.+- **Console targets / agent CLI stdout discipline.** Independent track — `wip/console-targets-and-agent-cli-stdout.md`. Already landed in part on `fix/Log-target`.+- **Kajson untrusted-deserialization design pass.** Separate track at `../pipelex-api/wip/security/kajson-untrusted-deserialization.md` (workspace-level concern, needs `pipelex-app` + `pipelex-api-deploy` in the room).+- **API-side `pipe_code` / `pipeline_run_id` log enrichment.** Done in `pipelex-api`, not here.+- **API-side `RecursionError` in `_decode_body`.** Done in `pipelex-api`, not here.+- **API-side JSON log sink.** Done in `pipelex-api`, not here.++---++## Verification (when items land)++- `make c` + `make t` clean on every commit.+- For items #1-#5: add unit tests that pin the new behavior; the API-side test suite (`pipelex-api` with this branch pinned via the `[tool.uv.sources]` git rev) should also still pass — bump the pin and run `make c && make tp` over there as part of the PR.+- For item #6 (SSRF): integration-style test using a mock resolver. No live network.+- For item #7: depends on the sequencing decision.++---++## Pin coordination with `pipelex-api`++`pipelex-api/pyproject.toml` has a temporary `[tool.uv.sources]` git-rev pin pointing at this repo. When this branch reaches a shippable point:++1. Bump that `rev` to this branch's HEAD; run `make c && make tp` in `pipelex-api`.+2. Update the API-side `TODOS.md` "Deferred / next-track work" → "Upstream-pipelex follow-ups" — strike through the items that landed; keep the rest.+3. Update `../pipelex-api/wip/pipelex-changes.md` Stage 7 tracking table — flip the items' status.++The eventual end-state — flipping the API back to a PyPI floor (`pipelex>=<next-release>`) — is Louis-gated cross-repo release coordination; not part of this branch.++---++## Decisions taken (2026-05-28)++The open questions from the original cold-start session have been resolved. Recording here so they don't get re-litigated:++1. **Item #7 sequencing — DEFERRED to structured-logging refactor.** See item #7 above. The lines it would have touched are explicit deletion targets in `wip/structured-logging/kickoff.md`. Doing the narrow event-name pass now means touching them twice.+2. **Item #6 SSRF rule placement — SHARED HELPER.** Create `pipelex/tools/network/` (greenfield) with `is_disallowed_host(...)`. The pipelex-api side re-points its `_is_disallowed_host` at this helper. Single source of truth for the disallowed CIDR set. See item #6 above for the error-location convention note.+3. **Items #4 / #5 error class shape — NEW `StorageLocalError(StorageError)`.** Mirrors the established per-backend pattern (`StorageS3Error` / `StorageGcpError` with `_declared_title`). Item #5 keeps wrapping as the existing `StorageS3Error`.+4. **`dev` merge — NOT NEEDED.** `git log feature/API-readiness-2..origin/dev --oneline` returns 0 commits. `dev` is not ahead.