Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions api/common.proto
Original file line number Diff line number Diff line change
Expand Up @@ -158,13 +158,20 @@ enum Mediation {
// completion (text, reasoning, and tool_call parts) is recorded separately as an EVENT_OUTPUT
// message. Under STATELESS_REPLAY the harness never calls a provider directly.
message ModelCall {
enum ResultCorrelation {
// Legacy journals correlate the next OUTPUT by position. New writers never select this mode.
RESULT_CORRELATION_UNSPECIFIED = 0;
// The provider-result OUTPUT must carry this ModelCall.id in Event.model_call_id.
RESULT_CORRELATION_BY_ID = 1;
}

// On new policy-enabled turns, an empty request model resolves to Start.model; explicit per-call
// overrides are allowed within the host's allowed set. Membership is checked before invoking
// the provider. Rejection is execution-fatal even if caught: the provider is not invoked, no new
// MODEL_CALL is appended, and subsequent effects are refused. An existing trailing intent remains
// recorded. Without policy, existing semantics apply.
// Replay uses recorded invocation state, not today's default. The recorded ModelCall format
// is unchanged; admitted policy-enabled calls record the resolved model in this field.
// Replay uses recorded invocation state, not today's default. Admitted policy-enabled calls
// record the resolved model in this field.
string model = 1;
map<string, string> params = 2;
string input_hash = 3; // §7/§9.1: required for STATELESS_REPLAY so the I0 check can run
Expand All @@ -179,6 +186,9 @@ message ModelCall {
// tool_choice constrains whether and which tool the model calls. Wire-only like messages and
// covered by input_hash. Unset means the provider default.
ToolChoice tool_choice = 7;
// Host-owned durable correlation mode. New journaled calls use BY_ID; omitted preserves the
// positional interpretation of journals written before model-result correlation.
ResultCorrelation result_correlation = 8;
}

// ToolDefinition is a tool offered to a model on one call. It aligns with an MCP Tool (name,
Expand Down Expand Up @@ -442,6 +452,9 @@ message Event {
}

IdentityRef actor = 18; // emitter principal -> provenance
// Present only on an EVENT_OUTPUT that records the provider result for a MODEL_CALL. Direct
// EventSink.Output leaves it absent. Presence is significant: an explicitly empty ID is invalid.
optional string model_call_id = 22;
}

// LogRecord is the host's durable, ordered wrapper around an Event. The host assigns seq,
Expand Down
286 changes: 181 additions & 105 deletions api/genpb/common.pb.go

Large diffs are not rendered by default.

21 changes: 17 additions & 4 deletions api/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@ type Event struct {
Err *Error
ExecutionStart *ExecutionStart
Parked *ApprovalRef `json:",omitempty"` // transport only, excluded from durable history
// ModelCallID is present only when this OUTPUT is a provider result. Nil identifies direct
// harness output; a non-nil empty value is malformed correlation evidence.
ModelCallID *string

Actor IdentityRef // emitter principal -> provenance on every action
}
Expand Down Expand Up @@ -180,12 +183,22 @@ const (

// ModelCall records a call to a model (model-agnostic) for audit and cost.
type ModelCall struct {
Model string
Params map[string]string
InputHash string // required for STATELESS_REPLAY so the §9.1 I0 check can run
ID string // correlation id for the served ModelResult (proto ModelCall.id)
Model string
Params map[string]string
InputHash string // required for STATELESS_REPLAY so the §9.1 I0 check can run
ID string // correlation id for the served ModelResult (proto ModelCall.id)
ResultCorrelation ModelResultCorrelation
}

// ModelResultCorrelation selects the durable provider-result correlation rule. The zero value is
// positional compatibility for old journals; new calls use ModelResultCorrelationByID.
type ModelResultCorrelation int32

const (
ModelResultCorrelationUnspecified ModelResultCorrelation = iota
ModelResultCorrelationByID
)

// Usage is per-model-call token/cost accounting.
type Usage struct {
Model string
Expand Down
58 changes: 58 additions & 0 deletions canon/canon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,64 @@ func TestToolCallPartGoldenVector(t *testing.T) {
}
}

func TestModelResultCorrelationGoldenVectors(t *testing.T) {
call := api.Event{ExecutionID: "exec-model", Kind: api.EventModelCall, ModelCall: &api.ModelCall{
Model: "gpt-test", InputHash: "sha256:input", ID: "model-call-1",
ResultCorrelation: api.ModelResultCorrelationByID,
}}
result := api.Event{ExecutionID: "exec-model", Kind: api.EventOutput,
Message: api.TextMessage("assistant", "answer"), ModelCallID: proto.String("model-call-1")}
for _, tc := range []struct {
name string
event api.Event
want string
wantHash string
}{
{
name: "call", event: call,
want: `{"event":{"execution_id":"exec-model","kind":"EVENT_MODEL_CALL","model":{"id":"model-call-1","input_hash":"sha256:input","model":"gpt-test","result_correlation":"RESULT_CORRELATION_BY_ID"}},"prev_hash":"","seq":"1"}`,
wantHash: "8e5c3dfd99d817ef8123b158230fc1839bdb409e5485674fb6cff46c59d4406d",
},
{
name: "result", event: result,
want: `{"event":{"execution_id":"exec-model","kind":"EVENT_OUTPUT","message":{"parts":[{"text":{"text":"answer"}}],"role":"assistant"},"model_call_id":"model-call-1"},"prev_hash":"","seq":"1"}`,
wantHash: "f93c67086837ff8a9b4e865e00b52964b35dcd7d3ca94611fde1e49b1ddc1a07",
},
} {
t.Run(tc.name, func(t *testing.T) {
got, err := canon.Record("", 1, tc.event)
if err != nil || string(got) != tc.want {
t.Fatalf("canonical %s = %s, %v; want %s", tc.name, got, err, tc.want)
}
hash, err := canon.HashRecord("", 1, tc.event)
if err != nil || hash != tc.wantHash {
t.Fatalf("%s hash = %s, %v; want %s (also update hack/verify_chain.py)", tc.name, hash, err, tc.wantHash)
}
roundTrip, err := canon.HashRecord("", 1, wire.EventFromProto(wire.EventToProto(tc.event)))
if err != nil || roundTrip != hash {
t.Fatalf("%s hash after wire round-trip = %s, %v; want %s", tc.name, roundTrip, err, hash)
}
})
}
}

func TestModelResultCorrelationPresenceIsHashBound(t *testing.T) {
absent := api.Event{Kind: api.EventOutput, Message: api.TextMessage("assistant", "answer")}
empty := absent
empty.ModelCallID = proto.String("")
absentHash, err := canon.HashRecord("", 1, absent)
if err != nil {
t.Fatal(err)
}
emptyHash, err := canon.HashRecord("", 1, empty)
if err != nil {
t.Fatal(err)
}
if absentHash == emptyHash {
t.Fatal("absent and explicitly empty model_call_id hash alike")
}
}

// A FORK marker's compute_instance (the clone a stateful fork made) is part of its canonical bytes
// only when set, so a marker that records none, which every marker written before the field existed
// is, keeps its canonical bytes and hash. Both are interop vectors (hack/verify_chain.py) and must
Expand Down
10 changes: 10 additions & 0 deletions changelog/unreleased/model-result-correlation-compat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
category: Compatibility
---

- SQLite schema v11 is a stamp-only, one-way migration for hash-bound model-result correlation
fields. Stop every older writer and embedded client and back up the database and WAL before the
first v11 open; rollback requires restoring that backup. Existing records keep positional model
result behavior and unchanged hashes. After recovery refuses an old positional call or its
re-drive fails, immediate direct fallback output is refused as ambiguous; a fresh model-call retry
remains supported.
6 changes: 6 additions & 0 deletions changelog/unreleased/model-result-correlation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
category: Fixed
---

- Provider-result `OUTPUT` records for new model calls name the durable `MODEL_CALL` they answer, so
replay and recovery do not reinterpret direct fallback output as provider success.
33 changes: 23 additions & 10 deletions controller/effects.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ type liveSink struct {
// runCtx is the context Exec or Resume passed to Harness.Run. It, not the per-call context a
// harness may narrow for ToolCall, decides whether the host ended the turn.
runCtx context.Context
// appends counts durable sink writes in this run. Resume uses it to tell whether another effect
// made a failed legacy model call's later direct output unambiguous.
appends int
}

var _ api.EventSink = (*liveSink)(nil)
Expand Down Expand Up @@ -54,21 +57,24 @@ func (s *liveSink) model(ctx context.Context, req api.ModelRequest) (api.ModelRe
if err := s.validateModel(req); err != nil {
return api.ModelResponse{}, err
}
callID := newID()
if _, err := s.append(api.Event{
Kind: api.EventModelCall,
ModelCall: &api.ModelCall{Model: req.Model, InputHash: hashModelInput(req), ID: newID()},
Kind: api.EventModelCall,
ModelCall: &api.ModelCall{
Model: req.Model, InputHash: hashModelInput(req), ID: callID,
ResultCorrelation: api.ModelResultCorrelationByID,
},
}); err != nil {
return api.ModelResponse{}, err
}
return s.completeModel(ctx, req)
return s.completeModel(ctx, req, callID)
}

// completeModel invokes the model for a MODEL_CALL that is already recorded and appends the
// completion as the OUTPUT that answers it: OUTPUT carries no call ID, so its position directly
// after the MODEL_CALL in the execution's effect stream is the correlation. It is reused verbatim
// when Resume re-drives a call cut before its completion was recorded, so both paths get the
// completion as the OUTPUT that answers callID. It is reused when Resume re-drives a call cut before
// its completion was recorded, so both paths keep the original durable ID and get the
// controller.model_call span; a completion served from the journal gets none.
func (s *liveSink) completeModel(ctx context.Context, req api.ModelRequest) (resp api.ModelResponse, err error) {
func (s *liveSink) completeModel(ctx context.Context, req api.ModelRequest, callID string) (resp api.ModelResponse, err error) {
ctx, finish := observability.BeginDebug(ctx, s.c.logger, "controller", "model_call",
"session_uid", s.c.sessionUID,
"execution_id", s.executionID,
Expand All @@ -95,7 +101,7 @@ func (s *liveSink) completeModel(ctx context.Context, req api.ModelRequest) (res
}
s.c.liveModelCalls++
msg := resp.Message
if _, err := s.append(api.Event{Kind: api.EventOutput, Message: &msg}); err != nil {
if _, err := s.append(api.Event{Kind: api.EventOutput, Message: &msg, ModelCallID: &callID}); err != nil {
return api.ModelResponse{}, err
}
return resp, nil
Expand Down Expand Up @@ -321,12 +327,16 @@ func (s *replaySink) Model(ctx context.Context, req api.ModelRequest) (api.Model
if mc.ModelCall == nil || mc.ModelCall.InputHash != hashModelInput(req) {
return api.ModelResponse{}, s.diverged(errors.New("replay: model input hash mismatch — harness violated STATELESS_REPLAY (I0)"))
}
out, ok := s.nextOf(api.EventOutput)
if !ok {
out, found, correlationErr := recordedModelResult(s.stream, s.i, mc.ModelCall)
if correlationErr != nil {
return api.ModelResponse{}, s.diverged(fmt.Errorf("replay: %w", correlationErr))
}
if !found {
// A handled provider failure can leave a call without completion. Preserve its
// bounded, handleable historical outcome rather than latching identity divergence.
return api.ModelResponse{}, errors.New("replay: expected a recorded completion, found none")
}
s.i++
var msg api.Message
if out.Message != nil {
msg = *out.Message
Expand Down Expand Up @@ -373,6 +383,9 @@ func (s *replaySink) Output(ctx context.Context, delta string) error {
if !ok {
return s.diverged(errors.New("replay: unexpected output (no matching recorded event)"))
}
if ev.ModelCallID != nil {
return s.diverged(errors.New("replay: direct output matched a model result"))
}
recorded := ""
if ev.Message != nil {
recorded = ev.Message.Text()
Expand Down
5 changes: 5 additions & 0 deletions controller/executions.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ type recordedExecution struct {
// runs. It preserves an ID-less legacy prefix, then groups modern events by ID in first-seen order.
// Lifecycle is session-scoped.
func recordedExecutions(events []api.Event) ([]recordedExecution, error) {
for i, event := range events {
if event.ModelCallID != nil && event.Kind != api.EventOutput {
return nil, fmt.Errorf("%w: event %d (%s) carries model result correlation", ErrInvalidExecutionLog, i+1, event.Kind)
}
}
prefixEnd, err := legacyPrefix(events)
if err != nil {
return nil, err
Expand Down
7 changes: 6 additions & 1 deletion controller/legacy.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,11 @@ func (c *Controller) legacyExecutionID(record eventlog.Record) (string, error) {
// into a later Exec. Streaming deltas also retain the empty legacy identity without journaling it.
func (s *liveSink) append(event api.Event) (eventlog.Record, error) {
if !s.legacyRecovery {
return s.c.appendSeq(s.executionID, event)
record, err := s.c.appendSeq(s.executionID, event)
if err == nil {
s.appends++
}
return record, err
}
head, err := s.c.log.Head()
if err != nil {
Expand All @@ -143,6 +147,7 @@ func (s *liveSink) append(event api.Event) (eventlog.Record, error) {
event.ExecutionID = ""
record, err := s.c.log.Append(head, s.c.fence, event)
if err == nil {
s.appends++
s.c.observe(record)
}
return record, err
Expand Down
42 changes: 42 additions & 0 deletions controller/model_result.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package controller

import (
"errors"
"fmt"

"github.com/agent-primitives/sessions/api"
)

// recordedModelResult returns the provider-result OUTPUT immediately after call. found is false
// without consuming anything when the next effect is direct output or another effect. Explicitly
// contradictory correlation evidence is an error and must be latched by the caller.
func recordedModelResult(stream []api.Event, i int, call *api.ModelCall) (out api.Event, found bool, err error) {
if call == nil {
return api.Event{}, false, errors.New("recorded model call has no payload")
}
switch call.ResultCorrelation {
case api.ModelResultCorrelationUnspecified, api.ModelResultCorrelationByID:
default:
return api.Event{}, false, fmt.Errorf("unknown model result correlation mode %d", call.ResultCorrelation)
}
if call.ResultCorrelation == api.ModelResultCorrelationByID && call.ID == "" {
return api.Event{}, false, errors.New("ID-correlated model call has no ID")
}
if i >= len(stream) || stream[i].Kind != api.EventOutput {
return api.Event{}, false, nil
}
out = stream[i]
if call.ResultCorrelation == api.ModelResultCorrelationUnspecified && out.ModelCallID == nil {
return out, true, nil // legacy positional completion
}
if out.ModelCallID == nil {
return api.Event{}, false, nil // direct output after a failed ID-correlated call
}
if *out.ModelCallID == "" {
return api.Event{}, false, errors.New("model result has an empty call ID")
}
if call.ID == "" || *out.ModelCallID != call.ID {
return api.Event{}, false, fmt.Errorf("model result call ID %q does not match %q", *out.ModelCallID, call.ID)
}
return out, true, nil
}
Loading