Skip to content

feat(engine): add generated persistence codecs and content IDs - #2651

Merged
jbeda merged 2 commits into
mainfrom
impl/persistence-codec
Nov 2, 2026
Merged

jbeda merged 2 commits into
mainfrom
impl/persistence-codec

Conversation

@jbeda

@jbeda jbeda commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add reusable Go-first persistence codec generation for the isolated kernel, without adopting it in production execution or migrating the handwritten history envelope.

  • Generate owner-package CheckT, EncodeT, DecodeT, Clone, and Equal from supported Go DTOs and explicit cbor/cborlimit tags. One generated file per package holds all selected roots; private numeric helpers are methods on a stateless cborgen type.
  • Add strict canonical CBOR primitives and explicit global, aggregate, and named field budgets. Decode validates declarations before allocation, returns owned values, and rejects unknown/missing fields, noncanonical encodings, duplicates, invalid types/ranges, and trailing bytes. Owner semantic validation remains explicit.
  • Keep whole-DTO cloning/equality distinct from persistence: excluded fields participate in Clone/Equal but not codec traversal or admission.
  • Extract fixed-profile exact-byte CID helpers into kernel/contentid, preserving the distinct format.CID facade, existing history bytes, and golden CIDs.
  • Derive generation and nonmutating inventory/byte freshness checks from the same source-local go:generate declarations. CI checks freshness before regeneration, including missing/stale/extra/removed and untracked artifacts.
  • Document the schema/tag/generation contract beside the generator; retain a short kernel overview and runtime accounting/ownership docs.

The build-time generator follows an ordinary compiler trust model: full validation/rendering, marker/regular-file/symlink overwrite safeguards, os.CreateTemp, checked write/close, and atomic replacement. It does not promise hostile-filesystem confinement, concurrent-writer CAS, or crash durability. Runtime persisted-byte admission remains a strict trust boundary.

Scope and deferrals

No reflection-based runtime traversal, new dependencies or module pins, builder framework, custom serialization hooks, CID-valued DTO fields, history codec migration, or production/session integration. Multiple generated outputs and custom implementation names are deferred.

Approved implementation plan

Full plan and approved amendments, including the one-output/private-cborgen decision and compiler trust model.

API compatibility

Additive Go runtime/generated APIs only. No remote-observable behavior, wire major, feature identifier, or client upgrade changes. Existing history API/type identity, canonical bytes, and CIDs are preserved. Future schema/tag/presence changes require their own stored-data compatibility assessment. Early-kernel guidance skips changelog bookkeeping, not API snapshots or layering guards.

Verification

Passed on the final committed source:

  • task --concurrency 3 test
  • task --concurrency 3 test:race
  • task --concurrency 3 test:workspace:race
  • task test:engine-standalone
  • task lint
  • GOWORK=off go test -race ./internal/cborgen/... -count=1
  • Engine codec and architecture focused race tests
  • task generate:codecs, task generate:codecs:check, task api:check, task docs, and git diff --check
  • Offline go run ./cmd/mecademo: tool call, permission ask/approval, and result

The implementation also includes independent canonical/strictness, ownership, allocation-byte admission, real CLI/directive/Taskfile regeneration, malformed-schema, and freshness negative controls. Prior unchanged runtime qualification included two bounded fuzz campaigns totaling 801,225 executions and complete-boundary benchmarks; these are not claims of exhaustive correctness or universal performance.

Implementation panel and affected incremental rechecks have no unresolved findings. The final one-output/private-cborgen simplification received a focused independent source/test review. An earlier aggregate test run hit an unrelated microVM scheduler-leadership startup flake; ten focused repetitions and subsequent full runs passed, including the final pre-PR test/race runs.

Generate bounded canonical CBOR codecs and whole-DTO Clone/Equal methods from Go declarations. Add explicit runtime limits, shared content identity primitives, declaration-derived freshness checks, and isolated qualification fixtures.

Co-authored-by: Mecatl <[email protected]>
@jbeda

jbeda commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Approved implementation plan: persistence-codec

Source: .scratch/persistence-codec-plan.md (local provenance, not a remote link).
Updated: 2026-11-02.
Branch: impl/persistence-codec; base: refs/heads/main.
Immutable start: 31aedf2ec7986ef5b1c1053adeff3d744858ae3d.
Published implementation head: 1cc25165513e8f91e4afd1405f976bdb9fc4ac3f.

The complete publishable plan follows, including approved amendments. No plan content was redacted or omitted. Local run notes, logs, handoff material, and raw review transcripts are not part of this publication. Verification requirements in the plan are intentions; actual gate receipts and limitations are summarized in the PR description.


Go-first persistence codec — specification and plan

Slug: persistence-codec
Implementation branch: impl/persistence-codec
Base branch: main

Approved plan, 2026-11-01, with operator-approved amendments on 2026-11-02. Implementation branch: impl/persistence-codec; base: refs/heads/main; immutable start: 31aedf2ec7986ef5b1c1053adeff3d744858ae3d. The operator authorized PR creation on 2026-11-02. No merge, rebase, release, or production integration is authorized.

Approved amendments (2026-11-02)

These decisions supersede conflicting generator/build/documentation details below. The runtime format, policy, ownership and canonicality requirements are unchanged.

  • Source-local go:generate directives are the sole declarations of package/root/output selection. Taskfile orchestration spans modules, and generation plus nonmutating inventory/byte freshness checking derive from those same declarations. Checking detects missing/stale/extra/removed artifacts, including untracked outputs. Repository-wide orphan enforcement belongs only to checking/CI, not ordinary generation of unrelated packages. No manually maintained target registry.
  • Treat the build generator as an ordinary compiler, not a hostile-filesystem security boundary. Concurrent generation/editing of the same artifact is unsupported. Remove before/after snapshots, CAS comparisons, os.Root confinement, retained-directory/ancestor-swap mechanisms, artifact Sync, custom random-name/exclusive-open temporary creation, and tests for the discarded confinement/race guarantees. Keep actionable path/output validation, regular-file/no-symlink and unmarked-handwritten-file overwrite safeguards, full validation/rendering before replacement, checked write/close errors, os.CreateTemp cleanup, and atomic rename. No crash-durability promise. Runtime persisted-byte admission remains a trust boundary.
  • Loader environment overrides retain only the containing-module selection (GOWORK=off). Preserve ordinary Go build context and checksum verification; do not default production GOSUMDB=off or impose test-only offline/hermetic restrictions. Controlled offline and poisoned-ambient-state isolation belongs in tests. Keep missing/stale/broken output recovery with handwritten function AND method callers, without suppressing real handwritten diagnostics.
  • Assume one generated output file per package, containing all selected roots. Group private codec/Clone/Equal helpers as simple deterministic numeric methods on one unexported stateless type named cborgen. Keep public owner entry points and methods unchanged. Remove filename/type-shape mangling; custom names and multiple outputs per package are deferred. Minimize package aliases while retaining imported/anonymous/container types and valid local identifier handling. Keep collision diagnostics and real compiled owner-method tests.
  • Add concise deterministic type-mapping comments beside private helpers/opaque identifiers and WHY comments beside pivotal logic: loader metadata versus typed passes and temporary stubs; whole-value versus persisted traversal; named-cap resolution under absent optional branches; complete Check before output/sorting allocation; canonical strict key order also rejecting duplicates. Avoid repeated boilerplate, timestamps, and absolute paths.
  • The detailed DTO/tag/generation reference belongs in internal/cborgen/README.md, including exact grammar/rejections, supported types, examples, directives, and diagnostics. Keep engine/kernel/README.md an overview/link and codec/doc.go focused on runtime limits/accounting/ownership. Use tech-writer and run task docs; no broader architecture/public-user-doc expansion.
  • CID-valued fields and migration of handwritten history codecs remain a separate follow-on PR. No such adoption or production integration belongs here. The existing CID facade extraction in this PR still preserves current history bytes and golden CIDs.

The acceptance criteria and tasks below are planned requirements, not verification receipts. Actual completed checks and any limitations are summarized separately in the PR description.

Goal and boundaries

Build a reusable Go-first generated persistence codec for simple DTOs, initially using Atmos CBOR primitives. Deliver generator, bounded runtime helpers, generated Clone/Equal methods, representative generated fixture packages, deterministic generation/freshness integration and developer documentation. This is not a fixed-fixture generator or a general Go object serializer. Builder and immutable-type generation are explicitly deferred; do not add their abstractions or hooks now.

No separate IDL, runtime-reflective codec/preflight, generic value tree, backend/plugin interface, arbitrary custom codecs or new module. Do not migrate existing history envelope codecs, change canonical bytes/CIDs or acceptance/storage contracts, design session DTOs/aggregate behavior, or integrate the isolated kernel into production entry points. The only existing-history refactor proposed is delegating fixed-profile CID primitives to a reusable leaf while preserving format.CID's public defined type, signatures, zero/comparability behavior and all existing bytes. Future owners explicitly adopt the codec.

Confirmed decisions

  • Go declarations/tags are the schema; generated typed code initially targets Atmos. Backend flexibility means later implementation replacement without redefining format semantics, not a speculative abstraction now.
  • Unknown struct fields are rejected. Unknown-data retention/re-emission is deferred, never silently dropped. Opaque payload bytes stay opaque.
  • Explicit operational limits are distinct from schema validity. Incomplete/zero policy is invalid, not defaults/unlimited; errors distinguish invalid policy, exhausted limits and invalid data.
  • Support bool, strings, fixed-width signed/unsigned integers, named supported types, structs, pointers, slices, fixed byte arrays and string-keyed maps with supported values. Reject unsupported shapes at generation time. No floats, interfaces/any, recursive shapes, custom codecs or CID-specific encoding; reject int/uint/uintptr.
  • Optional pointer nil means absent; nonnil pointer to zero means present. Required nil slices/maps encode empty collections; decode normalizes to initialized empty. Explicit null is rejected.
  • Generated operations enforce structural/schema validity, canonical encoding, ownership and limits. Higher-level invariants remain explicit owner code, never automatic discovery/invocation of Validate.
  • Small mapping-tag vocabulary inspired by other CBOR libraries: wire names and optional presence, not semantic range/regex/enum/cross-field validation DSLs. Q11 deliberately extends the original Q7 scope with separate field-budget tags for literal or dictionary-referenced operational maxima; resource rejection remains distinct from invalid schema/data.
  • Q12 adds optional shared fixed-profile CID derivation/verification, not mandatory hashing or additional CID returns in generated Check/Encode/Decode. A separate pass over authoritative bytes is acceptable; no streaming/fused hashing machinery or configurable algorithm framework.
  • Generate Clone() T and Equal(other T) bool methods on each selected local DTO root. Q10 confirms whole-DTO behavior, including cbor:"-" fields; excluded fields must also have supported clone/equality shapes. Clone detaches mutable storage and preserves nil-versus-empty; Equal compares values, treating nil/empty collections equally and distinguishing nil pointers from present-zero. Neither validates/freezes data or applies codec limits. Builder/immutable-type generation is deferred, with no speculative hooks/framework now.

Grounded seams and reuse

  • engine/kernel/history/format/commit.go:87-90 limits handwritten coding to the existing small envelope and directs generation before more persisted types. record.go:11-21 already separates opaque owner payloads from history vocabulary.
  • engine/kernel/history/format/limits.go:5-25 provides precedent for explicit positive limits independent of Validate; do not change/reuse its envelope-specific fields.
  • Atmos v0.8.0 is already in engine/go.mod:8; use qualified header/append primitives, not mutable-global-controlled typed readers/SkipValue. No fxamacker production dependency, including the generator; remove the scratch schema checker's fixture-package coupling.
  • Root go.mod already pins x/tools0.52.0; internal/apicheck/apicheck_test.go:39,109-135 uses go/packages/go/types outside engine, loading metadata from the engine module. Reuse that dependency, not its API-snapshot logic.
  • New runtime leaves must be registered in engine/arch/surface.go, coreImportRules in layering_test.go, root .golangci.yml, and public API snapshots. CID extraction also changes history/format's allowed lower-level imports, not its public defined CID type or wire representation.
  • Taskfile.yml:1251-1271 owns generation; .github/workflows/ci.yml:355-358 explicitly checks existing paths, not new codec output/additions automatically.
  • Tag inspiration: fxamacker/cbor v2.10.0 Struct Tags. Borrow cbor:"name", omitempty, and -; do not inherit toarray/keyasint/omitzero/JSON fallback or arbitrary empty-value omission. Document the strict subset, not drop-in library compatibility.
  • Scratch qualification .scratch/persistence-codegen/integrated-report.md establishes feasibility/regression lessons, not final APIs, production performance or universal peak memory bounds. Preserve it; production does not import scratch.

Examined fxamacker options: inspiration, not a feature checklist

Joe requested examining useful fxamacker options without adding nonbasic features absent a concrete reason. Reviewed pinned v2.10.0 Struct Tags documentation/structfields.go and EncOptions/DecOptions (go doc from the standalone experiment). These are comparisons of behavior, not a switch from generated Atmos code to fxamacker.

Upstream facility Decision and reason
Explicit cbor field names, -, pointer omitempty Adopt familiar spelling. Narrow omission to nil optional pointers; preserve required zero/empty and present-zero. Reject other omission uses rather than silently adopting upstream empty-value modes.
Canonical sorting, definite lengths, duplicate-key enforcement, valid UTF-8, exact field-name matching, unknown-field errors Implement as fixed strict contract, not configurable permissiveness knobs. Already required for unambiguous persistence.
NilContainers and ByteArray representation controls Adopt one fixed mapping: nil collections→empty, fixed byte arrays→byte strings. No alternative representations/configuration surface.
Immutable modes and MaxNestedLevels/MaxArrayElements/MaxMapPairs Borrow explicit isolated policy/concurrency discipline; our value Limits also covers aggregate work/declarations/scalar bytes. Do not inherit upstream defaults/minimums or instantiate a reflective mode at runtime.
omitzero / IsZero and broad omitempty modes Defer. Omission loses required-zero distinctions or invokes methods; optional pointer presence already solves the current need.
keyasint Defer. Smaller keys are plausible only with measured storage need; requires a separate integer-key profile, conflicts with the initial text-key contract.
toarray Defer. Positional schemas complicate evolution/presence; no current consumer or measured need justifies another encoding form.
toindefarray / indefinite-length output Exclude from this canonical profile.
JSON tag fallback, anonymous-field dominance, permissive case/byte-string matching and string/byte coercions Exclude initially. Implicit schema selection/normalization conflicts with explicit exact DTO mapping.
time/bignum/float/tag/custom-marshaler/JSON-transcoder options and generic-any decoding controls Defer/exclude with their unsupported Go shapes; no generic tree, conversions or custom extension mechanism now.
User buffers/streaming APIs, buffer pools and sequences Defer. Owned single-item []byte boundary is sufficient; add only after a concrete consumer/allocation requirement.

Future scope additions require a motivating consumer/measurement, a precise wire/presence/ownership/limit contract, and tests; upstream availability alone is not justification. This table does not add any new runtime option beyond explicit resource limits.

Schema and format specification

Selected roots are locally defined, nongeneric struct DTO types in the declaring package, so Go permits generating their methods; alias/imported roots are rejected with an actionable diagnostic. Reachable named/anonymous structs and supported named scalar/container types are allowed, including imported DTOs only when all fields needed for whole-value cloning/equality are accessible and obey these rules. Resolve aliases in reachable fields normally; reject recursive type graphs even if a particular value is acyclic, including cycles through codec-excluded fields.

Go shape Wire meaning
bool false/true
string, named equivalent UTF-8 text
int8/16/32/64; uint8/16/32/64 Minimal integer; decode checks exact destination range before narrowing.
[]byte, [N]byte and named equivalents with uint8-underlying elements Byte string; fixed array requires exact byte length.
Other slices Ordered arrays. Other fixed arrays unsupported initially.
Struct Map of tagged text keys.
Map with string-underlying keys Canonical text-key map; supported typed values. Entries are data, not unknown schema fields.
Pointer Indirection to supported value; omitempty controls field absence.

Every persisted field requires explicit cbor:"name" or cbor:"name,omitempty": nonempty UTF-8, exact/case-sensitive, unique within the struct. omitempty is allowed only on pointer fields and omits only nil, never nonnil zero/empty pointees. Without omitempty, pointer fields are required and nil is invalid. Nil pointers in slices/maps are invalid; double-pointer chains unsupported. Pointer-to-nil-collection is present-empty; nil optional pointer is absent.

cbor:"-" explicitly excludes a field from codec traversal/persistence; decode leaves it zero and codec roundtrip/ownership guarantees do not cover it. Clone/Equal DO cover it, recursively, so its type must be supported and accessible to generated whole-value helpers; no hidden shallow-copy/ignore fallback. Name/presence tag rules apply only to fields traversed for persistence, not a wholly excluded subtree. Other unexported fields, embedding, missing/duplicate tags, unknown/repeated options, generics, channels/functions, interfaces, floats, nonstring keys and custom CBOR/text/binary marshal/unmarshal contracts on persisted types fail generation. Whole-value shapes outside the approved vocabulary also fail even if excluded from persistence. Ordinary domain methods do not affect the schema. No implicit Go field naming/JSON fallback or IsZero hook.

Encode one definite-length item, shortest integer/length headers, text-key maps ordered by UTF-8 byte length then bytewise lexical order. Struct ordering is generated; map sorting uses validated/bounded scratch. Decode rejects duplicate/unordered keys, unknown/missing fields, wrong types, malformed/truncated/nonminimal input, invalid UTF-8, integer overflow, null, trailing data, floats, tags/CIDs, indefinite forms and unsupported simple values. Unknown-field failure returns immediately; no need to validate/retain the rejected value. Full MinInt64/MaxInt64 and MaxUint64 supported with overflow-safe arithmetic. Byte-string contents remain uninterpreted, including non-UTF-8/opaque JSON bytes.

This is a documented strict no-float/no-CID subset, not unrestricted DAG-CBOR/DRISL certification. Logical roundtrip ignores nil-versus-empty required collections and excluded fields, but preserves ordered slices, exact opaque bytes and optional presence.

Proposed owner API and semantic composition

For each selected root T, generate owner-package entry points:

func CheckT(v T, limits codec.Limits) error
func EncodeT(v T, limits codec.Limits) ([]byte, error)
func DecodeT(data []byte, limits codec.Limits) (T, error)
func (v T) Clone() T
func (v T) Equal(other T) bool

Whole-DTO Clone and Equal

Generate methods for selected locally defined roots and typed private helpers for reachable values; do not require users to select every nested type or add methods to imported types. Existing handwritten method/field/name collisions fail generation explicitly, including pointer-receiver Clone/Equal methods; never silently override or invoke them. Regeneration overlays must include both generated functions and methods so handwritten callers of either survive missing/stale output.

Clone copies every field, including codec-excluded fields and nested mutable bytes/slices/maps/pointers. Preserve nil versus nonnil empty collections and pointer absence; recursively detach mutable map values and slice elements. Immutable scalars/strings may share storage. Slice capacity and internal pointer-sharing topology are not preserved; repeated references may be cloned independently, but no mutable result may alias source storage. Both source and result remain mutable. Inputs must stay stable during the operation.

Equal compares all field values, including excluded fields: scalar equality; pointer nilness then pointee contents, not addresses; ordered slice elements; maps by exact key membership and value, not iteration order. Nil/empty collections compare equally at every level; nil pointer differs from nonnil pointer to a zero/empty value. Map lookup must distinguish missing key from present-zero/nil. Equal(Clone(v), v) holds for every supported value, including values invalid for encoding (invalid UTF-8, required nil pointer, etc.). Neither method performs codec/domain validation, calls user Clone/Equal/Validate hooks, freezes data, or accepts Limits.

These are ordinary in-memory value operations, not untrusted-input/resource-admission boundaries. Codec CheckT does NOT bound excluded-field storage or make a subsequent whole-DTO Clone bounded by codec policy. Callers own in-memory size/admission; do not add a second bounded-clone API or generic cloning/freezing interface. Builder/immutable-type generation remains future work.

Codec operations

CheckT bounds work and checks structure without output/sorting allocation or domain-method calls. EncodeT enforces equivalent checks itself; prior CheckT is never a bypass. Safe owner encoding: CheckT → owner semantics → EncodeT. Safe owner decoding: DecodeT → owner semantics → accepted state. Repeated bounded checks are acceptable. No semantic callback/registry or generic codec interface.

Output bytes and decoded persisted strings/bytes/slices/maps/pointers own storage; tiny strings must not retain the whole input. CheckT does not mutate input. All inputs remain stable during synchronous calls; concurrent input mutation unsupported. Independent operations are stateless/concurrency-safe. Failure returns nil encoded bytes/zero decoded T, never partial caller state. Success proves neither semantic version support, authorization, accepted-state immutability, history acceptance nor durability.

Field-specific operational budgets

Use separate cborlimit metadata so standard CBOR mapping tags retain their familiar small grammar:

Records []Record `cbor:"records" cborlimit:"items=@max_records"`
Label   string   `cbor:"label"   cborlimit:"bytes=256"`

items bounds the immediate count of a nonbyte slice or typed map (array elements/map pairs). bytes bounds a UTF-8 string or byte-string length (including fixed byte arrays). Follow supported pointer indirection; count/length is checked only when the optional value is present. No aggregate subtree-byte expression, per-element path selector, arbitrary expression, callback or cross-field validator. Global/aggregate caps still govern every operation and nested element.

Each field may specify one applicable maximum, either a positive decimal literal or @name. Names are case-sensitive ASCII identifiers ([a-zA-Z_][a-zA-Z0-9_]*); dictionary keys match exactly. Reject malformed/overflowing/nonpositive literals, empty references, wrong-shape/unknown/repeated options, and budget tags on codec-excluded fields/subtrees during generation. Use overflow-safe literal comparisons independent of target int width; referenced runtime values are operational machine-sized integers. Literal tags are baked-in resource caps, not domain validity or new wire representations.

Extend codec.Limits with Named map[string]int. Every referenced name must be present with a positive value; missing/nonpositive values return ErrInvalidLimits, even if the referencing optional field is absent in this particular value/input. Resolve the finite schema-known reference set ONCE at operation entry before inspecting content/allocation, into generated local budget values. Ignore unreferenced dictionary entries so one policy dictionary can serve multiple schemas; do not scan/copy an arbitrarily large supplied dictionary. Nil dictionary is valid only when no references are needed. No zero/unlimited/default semantics; global numeric limits remain explicit/positive.

Limits values/dictionary must remain stable during a call, just like DTO/input bytes; generated code never mutates, retains or globally caches the dictionary. Per-call materialization removes repeated lookups and keeps traversal policy fixed after entry. It is not synchronization against concurrent map mutation, which callers must not do. Concurrent read-only reuse is supported.

Field maxima supplement global scalar/collection/aggregate limits and cannot relax them: satisfy BOTH applicable caps. Generated Check/Encode enforce before scans/output/sorting allocation; Decode enforces declared count/length before typed allocation/copy. Exceeding literal or resolved maxima is ErrLimitExceeded, not ErrInvalidData or implicit semantic version failure. Check/Encode/Decode resolve/check the same policy; Clone/Equal ignore it entirely. Tightening resource policy can reject previously accepted values without changing canonical bytes; document that operational compatibility separately from schema evolution.

Optional content identity

Keep generated EncodeT/DecodeT bytes-only. Provide shared fixed-profile CID derivation and expected-CID verification as explicit owner operations, using a separate pass over exact bytes. No per-root wrappers/duplicate hashing implementations, fused encode/hash state, streaming buffers, algorithm registry or extra CID returns from generated operations.

Proposed leaf engine/kernel/contentid/ owns an opaque comparable CID value (zero unset), canonical text parsing/formatting and CIDv1/DAG-CBOR/SHA-256 derivation/verification. Reuse the existing profile/algorithm from history/format/cid.go, not a second CID library/profile. Suggested surface: Sum(data []byte) CID, Verify(data []byte, expected CID) error, canonical text parse/String and only the fixed binary conversion needed by existing history link encoding. No change to the profile, accepted canonical CID spelling or authoritative bytes.

Sum identifies exact supplied bytes, NOT schema/canonical validity, semantic validity, history membership or authorization. Verify compares those exact bytes to an explicitly supplied valid expected CID; zero/unset expected CID is an error, never 'skip verification'. Expose distinguishable invalid-expected/mismatch errors without input contents. Hashing is synchronous/stateless, does not retain/mutate input and is opt-in with O(n) byte work, no clone. Caller bounds input first; helpers do not silently validate/normalize CBOR or apply a second implicit codec policy. Codec structural checks and owner semantics remain explicit prerequisites to accepting state. A trusted expected CID establishes identity only, not authority or semantic validity.

Owner composition examples: EncodeT → Sum(emitted bytes); DecodeT → Verify(original input, expected) → owner semantics → accept. Do not reencode to derive/verify identity. CID link values inside DTO schemas remain unsupported; root identity derivation is a different capability.

To avoid duplication/coupling, extract shared primitives into the leaf and keep history/format.CID as its existing distinct public defined type wrapping/delegating internally, not a type alias that changes public identity. Keep ParseCID/String/EncodeCommit/DecodeCommit signatures, unset behavior, comparability, strict parent-link representation and golden CIDs byte-identical. The generic codec must not import history; neither codec nor generated code needs to import contentid unless an owner explicitly uses it. This is identity-helper extraction, not migrating the history schema/codec to generation. If preserving that boundary requires a wider public/API/storage change, stop for approval instead of broadening scope.

Operational policy

Proposed codec.Limits is passed by value. Validate every numeric global field and every schema-referenced Named value as positive before examining input; Named itself is a read-only dictionary input, not a numeric field. No mutable defaults/dependency globals. The dictionary is governed by the field-budget resolution/lifetime contract above.

Field Meaning
MaxBytes Complete input bytes on decode; conservative canonical output estimate on Check/Encode.
MaxStringBytes Each UTF-8 value/key byte length, including schema keys.
MaxByteStringBytes Each opaque byte-string length, including fixed byte arrays.
MaxArrayElements Each array count.
MaxMapPairs Each struct/data map pair count.
MaxDepth Maximum nesting depth, root0; policy field still positive.
MaxNodes Aggregate visited wire-value nodes, including map keys; pointer indirection is not a node.
MaxCollectionElements Aggregate declared array elements plus map pairs, including schema maps; charged BEFORE related allocations.

Counts, remaining input, lengths and aggregate declarations are checked before allocation/conversion, using subtraction/overflow-safe arithmetic. Reserve declared container exposure, not only visited entries, so malformed nested prefixes cannot allocate oversized typed storage before eventual node failure. UTF-8/key scans follow length checks. Map sorting scratch is bounded by count/reservation policy. Resource failure is not schema invalidity.

Conservative size accounting is allowed, not mandatory exact sizing. Mirror its known-value estimate on decode so accepted values re-encode under the same limits. This can reject canonical inputs below MaxBytes and must be explicit/tested. Container limits and aggregate reservations plus bounded scalar content give finite allocation/traversal exposure for generated fixed shapes, NOT byte-exact heap/RSS or process-wide concurrency quotas. No whole-input owning clone.

Provide errors.Is-compatible ErrInvalidLimits, ErrLimitExceeded, ErrInvalidData. Add safe field/index context, not payload contents. Exact error strings/precedence for multiply-invalid data are unspecified; policy validation always comes first. Generation failures are build-time diagnostics with type/field location/reason. Semantic errors remain owner-defined.

Packages and generation

  • Runtime engine/kernel/codec/: public policy/errors and only low-level reader/accounting helpers required by emitted code in other packages; doc.go overview and coherent type-owned implementation. Dependencies stdlib + Atmos primitives only; no reflect traversal, os, host internal, adapters, generated contracts or session/history concepts. Register both layering guards/CorePackages/API snapshots; no speculative helper exports.
  • Identity leaf engine/kernel/contentid/: stdlib-only fixed-profile CID value/hash/parse/verify primitives. Register core/layering/API snapshots; history/format may depend inward on this leaf through its preserved CID facade. No leaf→history/codec import or source-type alias migration.
  • Root tool internal/cborgen/ and internal/cborgen/cmd/cborgen/: static Go schema validation/emission using existing go/packages/go/types dependency; no importing/executing DTO packages or reflection driver. No engine dependency/pin changes.
  • Representative owner engine/kernel/codec/internal/fixture/: two small unrelated schema families, declarations plus generated root functions, independent of history/session; external-package codec tests avoid test import cycles. Negative declaration fixtures must reach the relevant shape check, not fail an earlier package/root guard.

Proposed repo-root invocation:

go run ./internal/cborgen/cmd/cborgen -dir engine/kernel/codec/internal/fixture -types Example,Envelope -out zz_cbor_generated.go

-dir identifies declaring package; explicit root set is sorted/deduplicated, not a second field schema. -out names one package-local owned file. Deterministic imports/declarations/gofmt; generator marker, no timestamp/absolute paths. Collision with handwritten names is an error, not automatic renaming.

Load from the module containing -dir, not root's published engine pin. Missing/stale/uncompilable owned output must not prevent regeneration, including handwritten owner wrappers referencing generated public functions. Propose a narrowly scoped load overlay replacing owned generated output with stable public-entry-point declarations; schema-reachable/unrelated handwritten errors must still fail rather than suppressing all package errors. Prove this seam first. No package initialization execution, cross-module distribution product, or generic source-analysis framework. Keep schemas platform-neutral and test cross-architecture generation consistency.

Validate declarations and format complete output before updating destination. Refuse unmarked handwritten output targets and output symlinks. Success replaces the single owned artifact atomically; load/validation/emission errors leave prior bytes intact. No deletion of unrelated files; per-package output is atomic, not a transaction across all targets.

Add task generate:codecs with explicit package/root/output selections, called by task generate. Add nonmutating freshness check comparing expected inventory AND bytes, wired into CI. Detect missing/modified/extra/stale owned output—including removed roots/targets—while preserving authored siblings. Freshness cannot rely on git diff alone ignoring untracked additions. Generated files change only via task generate.

Acceptance and evidence

  • Independent canonical goldens over all supported shapes; randomized map insertion, repeated/concurrent calls, root/input declaration order and CWD produce identical wire/generated bytes. Cover multibyte UTF-8 keys and length-first ordering.
  • Required zero/empty, optional absent/present-zero, nil/empty collections, pointer-to-empty, fixed byte length, opaque binary values; all integer extrema/narrowing failures. Error/zero outputs for strict malformed/type/presence/order/unknown/null/trailing/unsupported cases; truncate fixtures at every offset.
  • Each policy dimension at/over threshold; invalid policy first; length/count/depth/overflow/nested-prefix attacks before allocation. Measure allocated BYTES for prebuilt rejected known collections/oversized inputs and bounded map sorting, not allocation count alone. No host-OOM tests. Conservative headroom/decode-reencode symmetry explicitly covered.
  • Field-budget tests: literal/named caps at/over threshold before scan/allocation, global cap tighter/looser, nested repeated values, pointer absence/presence, UTF-8 byte length versus rune count, array count versus byte-string length, map pair count, missing/zero/negative references including absent optional branches, unreferenced dictionary entries accepted, read-only concurrent reuse, no dictionary retention/mutation, and generation failures for invalid syntax/shape/excluded tags. Check/Encode/Decode agree without imposing budgets on Clone/Equal.
  • Identity tests use independently derived fixed-profile canonical CIDs: Sum matches emitted/accepted bytes, Verify matching/mismatching/unset identity, byte alteration changes identity, no implicit normalization/schema validation, canonical text/binary roundtrips and rejection of noncanonical/other-profile forms. Owner example verifies exact ORIGINAL input and still rejects unsupported semantics before acceptance. Existing history root/successor/parent-link goldens, CID public API/type compatibility and format/history conformance remain unchanged after delegation; no generic codec import of history/contentid.
  • Owner semantic rejection after structural success; planted Validate/custom-codec hooks never invoked. Check-before-semantics controls prove bounded work precedes an independent semantic failure. Codec-excluded fields not claimed preserved by decoding; Clone/Equal still cover them.
  • Generated Clone/Equal compile and execute through real owner methods. Test nested mutation isolation for slices/bytes/maps/map values/pointers and excluded mutable fields in both directions; source unchanged, clones independent, nil/empty representation preserved by Clone. Test equality reflexivity/symmetry/transitivity and clone equality, distinct pointer addresses/equal contents, absent versus present-zero, missing map key versus present-zero/nil, map insertion order, nil/empty collections, excluded-field differences, and codec-invalid-but-supported values. Unsupported excluded shapes/inaccessible imported fields/cycles, alias roots and handwritten method/field collisions fail generation for the intended reason. No custom method delegation or immutable/builder machinery.
  • Input/result mutation proves ownership of every mutable type; tiny strings do not retain a near-cap input clone. Race tests on shared stateless functions and whole-DTO methods with stable inputs. Atmos-global independence checked without races against unrelated library tests.
  • Actual CLI/task-backed generation in test-owned copied module trees: two clean outputs, real directive/target path, poisoned ambient Go config, offline pinned cache inputs; missing/broken/stale generated output and wrappers referencing public generated functions; initialization trap, name collisions, reason-specific unsupported declarations, real schema errors still rejected. Failure preserves prior output; unmarked/symlink targets protected.
  • CI-facing freshness negative controls plant modified/missing/extra/stale artifacts, including removed target; checker fails without modifying files. Compile and run generated owner functions, not only source-string assertions.
  • Fresh managed-cache bounded fuzz campaigns seeded with canonical/strictness/resource cases; record execution counts/duration, no exhaustiveness claim. Complete-boundary benchmarks on small/nested/large/many-small/map-heavy shapes and allocation measurements, not scanner-only comparison or an invented universal speed threshold.

Implementation tasks (dependency order)

  1. Runtime contract. Add global/field policy, named-budget resolution, error/doc/accounting slice; core/API/layering registration. Focused policy/arithmetic/concurrency/standalone checks. Completion: documented coherent public contract with helper exports justified by generated use, no domain behavior changes.
  2. Schema loader and regeneration seam. Tool/driver, static type/tag graph validation including cborlimit bindings and whole-DTO Clone/Equal field coverage, narrow generated-output overlay and safe output handling. Prove stale/missing output plus handwritten function/method references, init nonexecution, aliases/imported DTOs and reason-specific unsupported shape failures before expanding emitter. Completion: generation recovers without hiding real source errors.
  3. Whole-DTO methods. Generate Clone/Equal methods and typed reachable-value helpers, including excluded fields; preserve nil/empty in cloning, compare nil/empty equivalently, detach all mutable storage, no semantic/codec limits or custom hooks. Validate accessibility/type support/collisions and extend loader overlays with method declarations. Completion: compiled method mutation/equality/invalid-value tests pass, including excluded fields and missing-map-key controls; no builder/immutable API.
  4. Check/Encode. Typed shapes, signed/named values, byte arrays, canonical maps, global and literal/named field-budget checks before scans/preallocation, and root entry points. Golden/presence/ownership/limit tests. Completion: Check/Encode policy resolution/acceptance agrees, no semantic hooks/unsafe bypass.
  5. Owning strict Decode. Required presence/order/duplicates/type/range/unknown rejection, declared field/global checks before allocation, aggregate reservations and conservative-estimate symmetry in one traversal. Runtime helpers and generated decoder land together. Completion: owner end-to-end semantics example and strict/resource/error-zero suite pass without reflection preflight/whole-input scan.
  6. Optional identity helpers. Extract fixed CID profile into contentid leaf, add Sum/Verify, preserve existing format.CID defined type/facade and exact parent-link/hash/golden behavior. No generated CID API or CID-valued DTO fields. Completion: independent identity tests, explicit codec-owner composition, unchanged format/history conformance, architecture/API guards.
  7. Build/freshness/docs. task generate:codecs/task generate/CI inventory-content check and negative controls. Small kernel README developer guide explains schema/profile/generation, operational field tags/dictionary lifetime, Clone/Equal versus codec-excluded fields, opt-in exact-byte identity and explicit semantic composition; code comments authoritative. Small stable architecture correction for shared identity leaf. Completion: reproducible real-task regeneration/nonmutating checks, no change-history dump or server user-doc scope creep.
  8. Integrate/qualify/review. Integrator gates, dependency closure, fuzz/bench evidence and implementation panel-review against recorded branch start OID. Fixes receive targeted incremental review against prior reviewed candidate; no automatic rebase. Completion: no open correctness blockers, honest limitations and no automatic production adoption.

Split tasks further only at coherent ownership boundaries; no broad frameworks. Tasks4/5 must share identical format/accounting rules; no consumer adoption in an unsafe intermediate state.

Required integration checks and compatibility

Iterate with root go test ./internal/cborgen/..., engine GOWORK=off go test -race ./kernel/codec/... ./kernel/contentid/... ./kernel/history/... ./adapter/history/... ./arch, task api:update/api:check. Generated changes via task generate only. Early-kernel guidance skips changelog bookkeeping, not API snapshots/guards. Identity delegation requires unchanged history golden/conformance tests, not just new-leaf tests.

Follow docs/module-development.md: same-checkout task test:workspace:race, independent task test:engine-standalone, standalone root generator tests with GOWORK=off, runtime closure/engine dependency proof. Root tooling must not import the new unpublished engine package; source metadata/generation suffices. No premature pins/replace/go.work edits; keep tracked module sums deliberate.

Integrator runs task test once per integrated set, task lint, task test:race, task generate and codec freshness/API checks; task docs for Markdown changes. Before PR readiness run offline go run ./cmd/mecademo tool→ask/approval→result smoke, isolated from operator state (including test-owned UserModelDir where composition is used). Full test/workspace suites1800s outer timeout; other full gates600s. Report blocked gates honestly; CI does not substitute for local evidence.

API compatibility: additive Go runtime/generated entry points only. No remote-observable behavior/feature/wire-major change, existing stored-byte/CID change or client upgrade. Future type/tag/presence/acceptance changes need their own stored-data compatibility assessment. Existing history goldens/conformance remain unchanged. New semantics/version support stay owner decisions, not harmless unknown additions.

Plan stays ignored/uncommitted. The operator authorized implementation and PR publication, including preserving the full publishable current plan in one verified PR conversation comment. This does not authorize merging, releasing, rebasing, or production adoption. No HANDOFF update unless requested or session clear/restart imminent.

Review state / final confirmation

Initial design reviews and targeted amendment rechecks found no blockers or important findings. Their static-loader regeneration/error-isolation advisory was carried as the task 2 stop/go gate and closed by implementation tests for missing/stale/broken output and handwritten function/method callers, with real handwritten errors preserved. The identity helper/facade also received its coherent contract and unchanged-byte checks. Implementation panel and incremental review-fix rechecks completed without unresolved findings. The later single-output/private-cborgen simplification received a focused independent source/test review. No design decisions remain open for this PR; numeric operational policies remain caller-owned.

The plan and all listed amendments are approved. Implementation is complete on the recorded branch. PR publication is authorized; humans alone merge. Verification intentions above remain distinct from actual command receipts in the PR description.

@jbeda
jbeda enabled auto-merge (squash) November 2, 2026 20:00
Avoid a hard-coded include list that misses Taskfiles introduced on main when CI tests the PR merge. Exercise new and nested includes through the real Task executable in an isolated fixture.

Co-authored-by: Mecatl <[email protected]>
@jbeda
jbeda merged commit 0dde05a into main Nov 2, 2026
46 checks passed
@jbeda
jbeda deleted the impl/persistence-codec branch November 2, 2026 21:16
@toolhive-release-app toolhive-release-app Bot mentioned this pull request Nov 18, 2026
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant