Repository navigation
feat(kernel): retain passive model interactions and run endings - #2746
Conversation
Record scoped model requests, ordered atomic responses, invocation failures, reported usage and opaque provider evidence in the isolated session kernel. Share accepted-source admission across builder, preflight and replay, retain immutable inspection, and reserve actual minimal run-ending envelopes. Keep request construction, tool disposition, accounting and production wiring outside this slice. Add adversarial replay, bounds, ownership and retry tests. Refs #2663 Co-authored-by: Mecatl <[email protected]>
Implementation plan: passive model interactions
This is the full current implementation plan, published without redactions. Verification commands below are the plan's intended checks, not evidence of passing; actual local results and review outcomes are recorded in the PR description. No production integration or merge is authorized. Passive model interactions — slice 3 of #2663Slug: kernel-model-interactions Implementation start: Publication amendment: no semantic scope changes. Concrete ending reasons use compact unsigned codes 1–6. Split review added explicit disclosure responsibility on ending explanations and deterministic malformed-codec/effective-contribution coverage regressions. These are implementation refinements within the approved design. Outcome and boundariesThe isolated session accepts and reconstructs model-request commitments, complete responses or observed invocation failures, requested tool calls, reported per-invocation usage, and explicit run endings. Demonstrate the lifecycle through real History acceptance without calling a model/tool or rebuilding a request. This is slice 3 under #2663, not completion of that issue or #2659. Slice 1 merged in #2687; slice 2 merged in #2725. Slice 4 adds tool intents/dispositions; slice 5 implements versioned request construction/check verification; slice 6 adds aggregate/late/final accounting. No production wiring, legacy session import/wrapper, protocol-adapter changes, execution/coordinator, queues/steering, permissions/hooks, handoff/fencing, compaction execution, blobs, partial-response bodies or comprehensive diagnostic/SDK-attempt logs. Do not implement a retry loop or reasoning-removal transformation. Do not rename existing indexes or refactor unrelated code. Primary decision record: .scratch/kernel-context/slice-3-interview.md (Q1–Q33, all answered). Production research: .scratch/kernel-context/slice-3-production-research.md. The issue was updated/read back with current merged status and revised semantics. Older issue comment 6665718324 is historical: its one-logical-request-spanning-visible-attempts and binary ending model are superseded. Grounding and reuse
Material contractsIdentities and atomic factsProposed names below define coherent responsibilities; final spelling/CBOR keys are routine design work in task 1, not permission to alter semantics.
Public values retain full scope and explicit assignment/Clone/Equal contracts. Constructors own nested mutable storage and return zero on failure. DTOs omit enclosing history/run/request context only where supplied unambiguously by their enclosing fact; reject conflicting public scope before omission. Optional exact provider evidence preserves absence where meaningful; original detail also survives in the private envelope. Structural errors never interpolate payloads or raw backend/provider exceptions. Private data is evidence, not permission. Producer/adapter interprets its schema and validates occurrence mappings before dependent use; the passive session does not parse signatures, encrypted reasoning, provider IDs or private ordinal relations. No silent omission or invented provider pairing tokens. Future derived lookup indexes cannot become a second authority. Accepted source and commit gatesA request is prepared from an ALREADY ACCEPTED snapshot. Its SourceHead must equal the exact sequence+CID immediately before its containing commit; stale/foreign/zero heads reject. The source must already have the same active run, a model binding, no pending request outcome, and no unresolved calls. Missing instructions/catalog mean empty under the construction algorithm; no synthetic facts or current host defaults. Use a small concrete shared admission context carrying the pinned pre-commit source and ordered candidate scalars in builder/preflight/evaluate. Do not confuse prepare's proposed NEW ref with the accepted source. Do not advance source while iterating records.
The recipe's parameters/check are retained without interpretation or algorithm registration. Session does not select source records, verify the check, construct requests, implement compaction or remove reasoning. Unknown algorithm/version remains inspectable; unsupported reconstruction later fails explicitly. Compaction/context changes determine source selection through the documented algorithm; retries are invisible to that algorithm. A changed interpretation needs a new algorithm version; an already defined parameter change does not. Interaction state, input coverage, retriesKeep one outstanding engine-visible request at a time; no new input/request while its outcome is pending or requested calls remain unresolved. An adapter explicitly declares API terminality; EOF/local exception does not. Accept terminal non-success/provider-failure responses, zero items, private-only responses, explicitly empty content/parts and empty text without conflating their representation. A complete response OR observed invocation failure resolves that request's pending outcome once. Both cannot exist; duplicate same/different outcomes reject even if byte-identical. Exact frozen HISTORY-proposal retry remains separate and unchanged. Provider-client internal retries are opaque. A higher layer retries by committing an ordinary NEW request from the current accepted head, optionally referencing an accepted earlier same-run request. RetryOf is correlation only: no automatic retry, frozen-old-context semantics, backoff or eligibility policy. New recipe parameters can deliberately change construction; old request and private data remain intact. Track a per-run admission/coverage frontier for authored submissions and nonempty effective contributions. Every authored submission, including empty content, advances it. An empty EffectiveInput remains a retained no-content contribution and does NOT request generation or dirty an otherwise covered frontier, per effective_input.go:10–14. Nonempty duplicates still contribute/advance; references alone are not processing. Context replacement is not an input frontier change. Capture source frontier at request acceptance; its terminal outcome accounts for that frontier for ending purposes, not proof the model understood/satisfied/received input. Newer input cannot be accounted for by an older outcome. Overflow rejects before consuming IDs or publishing scalars. A response with N calls creates N unresolved obligations, with call ordinals independent of interleaved text/reasoning/refusal. Unknown names, invalid arguments, repeated/missing provider tokens do not suppress calls. Complete call items in terminal non-success responses are obligations too. Adapter must not declare fragments as complete calls. Slice 3 offers no disposition operation: no next request/input or clean completion until slice 4; ending may preserve them unresolved. Endings and uncertaintyOne ending fact makes the active run terminal; no automatic successor, retry, cancellation, outcome synthesis or reload-time ending. Wrong run, duplicate ending or later model outcome for an ended run reject. Starting a successor resets ACTIVE counters without rewriting historical requests/calls/outcomes. Old pending work stays inspectable and cannot be resolved by a new run's IDs. Completed reason requires no pending request/calls and an accounted current input frontier. Input-free runs may end without an invocation. Explicit error/limit/cancel/interrupted/capture-failed reasons may end with unresolved or unprocessed work; that state remains derived from accepted facts, not silently marked resolved. A recorded invocation failure can account its input frontier and justify an error ending after retry exhaustion; it does not prove delivery. New input prevents claiming an old outcome covered it; an explicit uncertain ending can still terminate while preserving that newer unprocessed work. Failed clean-ending attempts reject atomically; do not convert them into another ending. Reason explains the owner's ending, not merely last provider stop. Reported provider tokens/reasons may be unknown. Proposed normalized provider classes: normal/limit/refusal/error/cancelled/other; actual call items, not the label, establish call obligations. Reasons and classifications never themselves authorize execution. Preserve exact optional provider reason independently. Bounds and actual terminal escapeWhole response (canonical items + private envelope + usage/evidence) is one bounded record. Constructor sizing precedes conversion/allocations; generated decode and aggregate cumulative hard checks remain authoritative. No truncation, body/private-envelope dropping or partial call acceptance. If capture rejects, accepted request remains pending; a fresh ending can say capture-failed, not falsely provider-failed. When ordinary bounds permit, its optional CaptureFailureEvidence retains the pending request's available usage/correlation without accepting any stripped response or turning capture rejection into InvocationFailure. Validate full same-run/request membership before DTO scope omission. This evidence has no response-content/envelope field and does not resolve the request. Detailed capture-failed endings are SOFT-bounded; after known local rejection, a fresh minimal ending omits all evidence/detail. Never switch to a fallback proposal after uncertain append acceptance. No partial-stream storage, implicit blob store or UI implementation. Generalize reserveInterruption/prepareInterruption to actual preparation of a one-record minimal ending. Minimal shape is fixed-size identity + compact closed reason and NO explanation/evidence/usage or lists. All promised emergency reason encodings must fit (use compact reason codes and prove worst permitted case). Preserve actual next-envelope sizes, sequence-width changes, hard record/byte/decoded-work/payload/commit constraints, not a guessed reserve. Eligibility for unconditional uncertain ending must not use a synthetic lifecycle missing new pending/coverage scalars. Only an exact minimal-ending-only batch may use the hard-only closeout exception. Detailed endings and mixed ordinary batches remain soft-bounded; never relabel content as cleanup. For a bound session, also validate the exact next minimal envelope against History.Identify's encoding policy (no backend I/O), not only Session.Policy, so the end-to-end encodability claim is honest. Keep internal sizing contexts explicit rather than adding mutable global limits. A backend I/O failure is still possible: the guarantee is reserved encodability/admission, NOT guaranteed acceptance/durability. Unknown append acceptance freezes the exact proposal/slot; no alternate response or ending until resolved/reloaded. A limit-shaped backend error is not known rejection. Apply/Load remain HARD-ONLY, without ordinary soft reservation for hypothetical future writes; loading never executes, retries or closes. Immutable inspection and organizationKeep declarations/helpers/comments beside owning types; format owns schemas/local validation and generator roots. Extend RecordView typed accessors and child views using immutable handles, Count/At and iter.Seq for new ordered parts/items. View zero values, failure returns, ownership and out-of-range behavior follow existing conventions. Call ordinal views derive IDs from request scope and call order; never store redundant independently mutable IDs in every call DTO. Use append-only positions for any needed request/run lookup. Do not retroactively fill outcome pointers in published request entries or mutate slice-prefix elements. Timeline inspection through Records and typed RequestID on outcomes suffices; do not add speculative outcome/provider-token maps or promise O(1) lookups without locators. If direct request lookup is added, follow UserInputByID and extend its architecture guard intentionally. Existing RunView.Records is a chronological span, NOT ownership filtering: idle context after an ending can remain in the preceding span until next run start. Keep that documented behavior. Snapshot capture must remain O(1), old handles/sequences pinned after append/replacement/new outcome/ending/new run, and concurrent readers safe with caller-serialized owner operations. Preserve existing allocation guards; do not promise opaque iter.Seq composition free. Implementation tasks (dependency ordered)
Tasks 1–4 must land as one coherent final candidate; no partial publication using new schemas with old reducers or missing reservation. Direct-write tasks remain serial. Implementation was explicitly authorized after planning; commit/push/PR delivery was separately authorized after local implementation. Never merge as part of this workflow. Observable acceptance / worked histories
Verification and delivery boundaryUse real offline memory History/adapters and explicit policies. Preserve existing tests; extend owning suites rather than remove prior allocation/identity guards. No tests ran for this future implementation during planning. From root: task generate:codecs; task generate:codecs:check; task api:update; task api:check; task lint. From engine: go test -race ./id ./kernel/... ./arch ./adapter/history/...; GOWORK=off go test ./kernel/... ./arch ./adapter/history/.... Add focused repeated source/ending/ownership tests, 386 checks for ordinal/count conversions, and constructor/decode fuzz seeds for new union/envelope/usage schemas. Benchmark representative direct complete new-view traversals across independent count/payload axes; preserve zero-copy direct navigation and intentional byte-export controls. This remains isolated engine work: scoped engine guidance permits focused tests rather than whole-repository test/test:race. Broaden if implementation crosses integration boundaries. Complete Go suite targets get 1800s outer timeout; other full gates 600s. If Markdown changes, task docs. Generated files only via task, not hand editing. No API changelog/compatibility-note bookkeeping under experimental kernel waiver. New stored kinds/replaced ending schema deliberately do not support old experimental data; no migration shim. No current wire behavior or major/features change because no production/remote consumers are wired; reassess BEFORE crossing that boundary. When implementation begins, create/resume impl/kernel-model-interactions from actual clean main after branch/remote/worktree preflight; record its FULL start OID then (do not substitute today's planning baseline). Initial code panel-review fixed point is that recorded implementation start. Capture full final-tree diff/new files; fixes get targeted incremental recheck. Rebase, commit, push or PR creation require their own authority. When a new implementation PR is authorized, publish the latest safe full plan in one identifiable plan comment and verify readback; do not rewrite #2725's historical plan comment. Readiness and remaining risksNo unanswered semantic interview question is intentionally left open. Exact Go names/CBOR keys/closed reason values and conservative internal indexes are task-1 concrete contract work, not a license to revisit decisions. If surface review reveals a material behavior gap, stop and ask rather than silently expanding scope. Highest risks: source vs provisional state, coverage vs actual composition, a failure outcome falsely claiming no remote spend, response/provider relation loss, mutable accepted-prefix outcome indexes, and hard-only ending bypass. The worked tests directly target them. This plan does not prove runtime behavior; passing planning critique is not implementation authorization or PR-wide readiness. |
Make session occurrence identities opaque and nonconvertible across kinds, align identity reference naming, and preserve numeric identity wire bytes. Use bounded string ending reasons, combine cancellation with interruption, and retain actual worst-case minimal-ending reservation. Clarify provider stop reasons and provisional evidence contracts, organize DTOs by record ownership, and strengthen kernel standards and panel review. Co-authored-by: Mecatl <[email protected]>
Share complete immutable backing between proposals and accepted views, internalize low-level reconstruction, and consolidate batch authoring inputs. Preserve lifecycle and storage contracts, adapt regression tests, and capture the future extension-record direction. Co-authored-by: Mecatl <[email protected]>
Fix the strict documentation dead-end finding without weakening graph checks. Co-authored-by: Mecatl <[email protected]>
Retain materialized records directly and validate typed identity scope before DTO conversion. Complete immutable nested inspection views and document admission ownership and lifecycle rationale. Exercise complete scalar traversal and field-only byte exports through Submit and Load, including presence, aliasing, allocation, and pinned-reader coverage. API compatibility: no wire, schema, canonical format, or production behavior changes. Experimental kernel getter signatures intentionally change to views. Co-authored-by: Mecatl <[email protected]>
Summary
Implement slice 3: passive model interactions in the isolated kernel. Refs #2663 (does not close it or #2659).
No production wiring, model/tool invocation, request reconstruction/check verification, tool dispositions, or aggregate/late accounting. Those remain separate slices.
Review map
model_request_id.go,model_request.go,model_response.go,invocation_failure.go,run_ended.go, and the correspondingsession/formatschemas.format/zz_cbor_generated.gois generated; the twoengine/apisnapshots reflect the exported contracts.lifecycle_state.go,session_commit.go,session.go, and the interaction admission/replay/ending/capture/policy suites. Focus on pinned accepted source versus provisional state, clean-ending coverage, minimal hard-only escape, and append uncertainty.record_view.go, views beside the owning types, immutable-view/ownership tests, fuzz seeds, and traversal benchmarks. Call IDs count calls, not all response items.Full implementation plan and decisions, archived as a PR conversation comment with a verified plan digest.
Verification
Passed locally on the final candidate:
task lint(all configured modules; zero issues)task generate:codecs:checkandtask api:check; codecs and both session API snapshots regenerated through their owning taskscd engine && go test -race ./id ./kernel/... ./arch ./adapter/history/...cd engine && GOWORK=off go test ./kernel/... ./arch ./adapter/history/...cd engine && GOARCH=386 go test ./kernel/...task docs(strict link and generated-reference checks)git diff --checkPer
engine/AGENTS.md, this isolated engine change uses scoped race/architecture/API/standalone evidence rather than the full repository test/test:race suites. No live-provider tests ran.Split panel review covered Spec, Standards, Test adequacy, and Domain (architecture, security, library reuse, duplication), fixed against
a5322b5231a970fd21744d3484bd87090c1bf43b. Two test-adequacy findings and one documentation advisory were fixed and passed targeted incremental rechecks. No open findings or reviewer failures. Unaffected axes retain their initial scoped evidence; this is not a claim that every reviewer reran after test/doc-only fixes.API compatibility
RunInterrupted/Interruptwith unified ending types/operations and adds model interaction records. Old experimental interruption histories are intentionally unsupported; no migration shim. This is the approved isolated-kernel waiver, not a production data migration.engine/kernel/AGENTS.mdfor the experiment.