Repository navigation
feat(engine): add generated persistence codecs and content IDs - #2651
Conversation
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]>
Approved implementation plan: persistence-codecSource: 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 planSlug: persistence-codec Approved plan, 2026-11-01, with operator-approved amendments on 2026-11-02. Implementation branch: Approved amendments (2026-11-02)These decisions supersede conflicting generator/build/documentation details below. The runtime format, policy, ownership and canonicality requirements are unchanged.
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 boundariesBuild 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
Grounded seams and reuse
Examined fxamacker options: inspiration, not a feature checklistJoe 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 (
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 specificationSelected 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.
Every persisted field requires explicit
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 compositionFor 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) boolWhole-DTO Clone and EqualGenerate 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 operationsCheckT 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 budgetsUse separate Records []Record `cbor:"records" cborlimit:"items=@max_records"`
Label string `cbor:"label" cborlimit:"bytes=256"`
Each field may specify one applicable maximum, either a positive decimal literal or Extend 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 identityKeep 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 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 Operational policyProposed
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
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 Acceptance and evidence
Implementation tasks (dependency order)
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 compatibilityIterate with root 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 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 confirmationInitial 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- 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. |
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]>
Summary
Add reusable Go-first persistence codec generation for the isolated kernel, without adopting it in production execution or migrating the handwritten history envelope.
CheckT,EncodeT,DecodeT,Clone, andEqualfrom supported Go DTOs and explicitcbor/cborlimittags. One generated file per package holds all selected roots; private numeric helpers are methods on a statelesscborgentype.Clone/Equalbut not codec traversal or admission.kernel/contentid, preserving the distinctformat.CIDfacade, existing history bytes, and golden CIDs.go:generatedeclarations. CI checks freshness before regeneration, including missing/stale/extra/removed and untracked artifacts.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-
cborgendecision 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 testtask --concurrency 3 test:racetask --concurrency 3 test:workspace:racetask test:engine-standalonetask lintGOWORK=off go test -race ./internal/cborgen/... -count=1task generate:codecs,task generate:codecs:check,task api:check,task docs, andgit diff --checkgo run ./cmd/mecademo: tool call, permission ask/approval, and resultThe 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-
cborgensimplification 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.