From 39f67a7b0d7f808fbba470aaeb1d83acdb1189f5 Mon Sep 17 00:00:00 2001 From: Tatsat Mishra Date: Sat, 28 Nov 2026 21:05:31 +1300 Subject: [PATCH 1/3] fix(controller): correlate model results by call ID --- api/common.proto | 17 +- api/genpb/common.pb.go | 286 +++++++++------ api/types.go | 21 +- canon/canon_test.go | 58 +++ .../model-result-correlation-compat.md | 9 + .../unreleased/model-result-correlation.md | 6 + controller/effects.go | 33 +- controller/executions.go | 5 + controller/legacy.go | 7 +- controller/model_result.go | 42 +++ controller/resume.go | 58 ++- controller/resume_model_cut_test.go | 342 +++++++++++++++++- docs/api-reference.md | 16 +- docs/concepts.md | 4 +- docs/harness-authoring.md | 13 +- docs/session-data-model.md | 4 + hack/verify_chain.py | 15 +- spec.md | 38 +- sqlitelog/cleanup_resources_test.go | 10 +- sqlitelog/model_correlation_schema_test.go | 60 +++ sqlitelog/sqlitelog.go | 10 +- wire/convert.go | 15 +- wire/convert_test.go | 12 +- 23 files changed, 919 insertions(+), 162 deletions(-) create mode 100644 changelog/unreleased/model-result-correlation-compat.md create mode 100644 changelog/unreleased/model-result-correlation.md create mode 100644 controller/model_result.go create mode 100644 sqlitelog/model_correlation_schema_test.go diff --git a/api/common.proto b/api/common.proto index c7eee550..d59f19a1 100644 --- a/api/common.proto +++ b/api/common.proto @@ -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 params = 2; string input_hash = 3; // §7/§9.1: required for STATELESS_REPLAY so the I0 check can run @@ -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, @@ -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, diff --git a/api/genpb/common.pb.go b/api/genpb/common.pb.go index d0397dad..e0b50268 100644 --- a/api/genpb/common.pb.go +++ b/api/genpb/common.pb.go @@ -232,6 +232,54 @@ func (EventKind) EnumDescriptor() ([]byte, []int) { return file_common_proto_rawDescGZIP(), []int{2} } +type ModelCall_ResultCorrelation int32 + +const ( + // Legacy journals correlate the next OUTPUT by position. New writers never select this mode. + ModelCall_RESULT_CORRELATION_UNSPECIFIED ModelCall_ResultCorrelation = 0 + // The provider-result OUTPUT must carry this ModelCall.id in Event.model_call_id. + ModelCall_RESULT_CORRELATION_BY_ID ModelCall_ResultCorrelation = 1 +) + +// Enum value maps for ModelCall_ResultCorrelation. +var ( + ModelCall_ResultCorrelation_name = map[int32]string{ + 0: "RESULT_CORRELATION_UNSPECIFIED", + 1: "RESULT_CORRELATION_BY_ID", + } + ModelCall_ResultCorrelation_value = map[string]int32{ + "RESULT_CORRELATION_UNSPECIFIED": 0, + "RESULT_CORRELATION_BY_ID": 1, + } +) + +func (x ModelCall_ResultCorrelation) Enum() *ModelCall_ResultCorrelation { + p := new(ModelCall_ResultCorrelation) + *p = x + return p +} + +func (x ModelCall_ResultCorrelation) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ModelCall_ResultCorrelation) Descriptor() protoreflect.EnumDescriptor { + return file_common_proto_enumTypes[3].Descriptor() +} + +func (ModelCall_ResultCorrelation) Type() protoreflect.EnumType { + return &file_common_proto_enumTypes[3] +} + +func (x ModelCall_ResultCorrelation) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ModelCall_ResultCorrelation.Descriptor instead. +func (ModelCall_ResultCorrelation) EnumDescriptor() ([]byte, []int) { + return file_common_proto_rawDescGZIP(), []int{11, 0} +} + type ToolChoice_Mode int32 const ( @@ -268,11 +316,11 @@ func (x ToolChoice_Mode) String() string { } func (ToolChoice_Mode) Descriptor() protoreflect.EnumDescriptor { - return file_common_proto_enumTypes[3].Descriptor() + return file_common_proto_enumTypes[4].Descriptor() } func (ToolChoice_Mode) Type() protoreflect.EnumType { - return &file_common_proto_enumTypes[3] + return &file_common_proto_enumTypes[4] } func (x ToolChoice_Mode) Number() protoreflect.EnumNumber { @@ -341,11 +389,11 @@ func (x ToolResult_Code) String() string { } func (ToolResult_Code) Descriptor() protoreflect.EnumDescriptor { - return file_common_proto_enumTypes[4].Descriptor() + return file_common_proto_enumTypes[5].Descriptor() } func (ToolResult_Code) Type() protoreflect.EnumType { - return &file_common_proto_enumTypes[4] + return &file_common_proto_enumTypes[5] } func (x ToolResult_Code) Number() protoreflect.EnumNumber { @@ -404,11 +452,11 @@ func (x Lifecycle_Kind) String() string { } func (Lifecycle_Kind) Descriptor() protoreflect.EnumDescriptor { - return file_common_proto_enumTypes[5].Descriptor() + return file_common_proto_enumTypes[6].Descriptor() } func (Lifecycle_Kind) Type() protoreflect.EnumType { - return &file_common_proto_enumTypes[5] + return &file_common_proto_enumTypes[6] } func (x Lifecycle_Kind) Number() protoreflect.EnumNumber { @@ -1299,8 +1347,8 @@ type ModelCall struct { // 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. Model string `protobuf:"bytes,1,opt,name=model,proto3" json:"model,omitempty"` Params map[string]string `protobuf:"bytes,2,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` InputHash string `protobuf:"bytes,3,opt,name=input_hash,json=inputHash,proto3" json:"input_hash,omitempty"` // §7/§9.1: required for STATELESS_REPLAY so the I0 check can run @@ -1314,9 +1362,12 @@ type ModelCall struct { Tools []*ToolDefinition `protobuf:"bytes,6,rep,name=tools,proto3" json:"tools,omitempty"` // 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 *ToolChoice `protobuf:"bytes,7,opt,name=tool_choice,json=toolChoice,proto3" json:"tool_choice,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + ToolChoice *ToolChoice `protobuf:"bytes,7,opt,name=tool_choice,json=toolChoice,proto3" json:"tool_choice,omitempty"` + // Host-owned durable correlation mode. New journaled calls use BY_ID; omitted preserves the + // positional interpretation of journals written before model-result correlation. + ResultCorrelation ModelCall_ResultCorrelation `protobuf:"varint,8,opt,name=result_correlation,json=resultCorrelation,proto3,enum=agentsessions.v1.ModelCall_ResultCorrelation" json:"result_correlation,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ModelCall) Reset() { @@ -1398,6 +1449,13 @@ func (x *ModelCall) GetToolChoice() *ToolChoice { return nil } +func (x *ModelCall) GetResultCorrelation() ModelCall_ResultCorrelation { + if x != nil { + return x.ResultCorrelation + } + return ModelCall_RESULT_CORRELATION_UNSPECIFIED +} + // ToolDefinition is a tool offered to a model on one call. It aligns with an MCP Tool (name, // description, inputSchema). It differs from the harness's ToolSpec, which declares a tool and its // default mediation to the host; ToolDefinition is what the model sees. @@ -2350,8 +2408,11 @@ type Event struct { // *Event_ExecutionStart // *Event_Parked // *Event_ReconstructionInfo - Body isEvent_Body `protobuf_oneof:"body"` - Actor *IdentityRef `protobuf:"bytes,18,opt,name=actor,proto3" json:"actor,omitempty"` // emitter principal -> provenance + Body isEvent_Body `protobuf_oneof:"body"` + Actor *IdentityRef `protobuf:"bytes,18,opt,name=actor,proto3" json:"actor,omitempty"` // 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. + ModelCallId *string `protobuf:"bytes,22,opt,name=model_call_id,json=modelCallId,proto3,oneof" json:"model_call_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -2545,6 +2606,13 @@ func (x *Event) GetActor() *IdentityRef { return nil } +func (x *Event) GetModelCallId() string { + if x != nil && x.ModelCallId != nil { + return *x.ModelCallId + } + return "" +} + type isEvent_Body interface { isEvent_Body() } @@ -2776,7 +2844,7 @@ const file_common_proto_rawDesc = "" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"B\n" + "\x0eCallerIdentity\x12\x16\n" + "\x06issuer\x18\x01 \x01(\tR\x06issuer\x12\x18\n" + - "\asubject\x18\x02 \x01(\tR\asubject\"\xfa\x02\n" + + "\asubject\x18\x02 \x01(\tR\asubject\"\xaf\x04\n" + "\tModelCall\x12\x14\n" + "\x05model\x18\x01 \x01(\tR\x05model\x12?\n" + "\x06params\x18\x02 \x03(\v2'.agentsessions.v1.ModelCall.ParamsEntryR\x06params\x12\x1d\n" + @@ -2786,10 +2854,14 @@ const file_common_proto_rawDesc = "" + "\bmessages\x18\x05 \x03(\v2\x19.agentsessions.v1.MessageR\bmessages\x126\n" + "\x05tools\x18\x06 \x03(\v2 .agentsessions.v1.ToolDefinitionR\x05tools\x12=\n" + "\vtool_choice\x18\a \x01(\v2\x1c.agentsessions.v1.ToolChoiceR\n" + - "toolChoice\x1a9\n" + + "toolChoice\x12\\\n" + + "\x12result_correlation\x18\b \x01(\x0e2-.agentsessions.v1.ModelCall.ResultCorrelationR\x11resultCorrelation\x1a9\n" + "\vParamsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x82\x01\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"U\n" + + "\x11ResultCorrelation\x12\"\n" + + "\x1eRESULT_CORRELATION_UNSPECIFIED\x10\x00\x12\x1c\n" + + "\x18RESULT_CORRELATION_BY_ID\x10\x01\"\x82\x01\n" + "\x0eToolDefinition\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12 \n" + "\vdescription\x18\x02 \x01(\tR\vdescription\x12:\n" + @@ -2885,7 +2957,7 @@ const file_common_proto_rawDesc = "" + "\x0fharness_version\x18\x05 \x01(\tR\x0eharnessVersion\x12)\n" + "\x10compute_instance\x18\x06 \x01(\tR\x0fcomputeInstance\x12\x14\n" + "\x05model\x18\a \x01(\tR\x05modelB\x0e\n" + - "\f_input_count\"\x91\b\n" + + "\f_input_count\"\xcc\b\n" + "\x05Event\x12!\n" + "\fexecution_id\x18\x02 \x01(\tR\vexecutionId\x12*\n" + "\x02ts\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\x02ts\x12%\n" + @@ -2905,8 +2977,10 @@ const file_common_proto_rawDesc = "" + "\x0fexecution_start\x18\x13 \x01(\v2 .agentsessions.v1.ExecutionStartH\x00R\x0eexecutionStart\x127\n" + "\x06parked\x18\x14 \x01(\v2\x1d.agentsessions.v1.ApprovalRefH\x00R\x06parked\x12W\n" + "\x13reconstruction_info\x18\x15 \x01(\v2$.agentsessions.v1.ReconstructionInfoH\x00R\x12reconstructionInfo\x123\n" + - "\x05actor\x18\x12 \x01(\v2\x1d.agentsessions.v1.IdentityRefR\x05actorB\x06\n" + - "\x04bodyJ\x04\b\x01\x10\x02J\x04\b\x05\x10\x06J\x04\b\x06\x10\a\"\xa2\x01\n" + + "\x05actor\x18\x12 \x01(\v2\x1d.agentsessions.v1.IdentityRefR\x05actor\x12'\n" + + "\rmodel_call_id\x18\x16 \x01(\tH\x01R\vmodelCallId\x88\x01\x01B\x06\n" + + "\x04bodyB\x10\n" + + "\x0e_model_call_idJ\x04\b\x01\x10\x02J\x04\b\x05\x10\x06J\x04\b\x06\x10\a\"\xa2\x01\n" + "\tLogRecord\x12\x10\n" + "\x03seq\x18\x01 \x01(\x03R\x03seq\x12\x1b\n" + "\tprev_hash\x18\x02 \x01(\tR\bprevHash\x12!\n" + @@ -2952,96 +3026,98 @@ func file_common_proto_rawDescGZIP() []byte { return file_common_proto_rawDescData } -var file_common_proto_enumTypes = make([]protoimpl.EnumInfo, 6) +var file_common_proto_enumTypes = make([]protoimpl.EnumInfo, 7) var file_common_proto_msgTypes = make([]protoimpl.MessageInfo, 28) var file_common_proto_goTypes = []any{ - (HarnessClass)(0), // 0: agentsessions.v1.HarnessClass - (Mediation)(0), // 1: agentsessions.v1.Mediation - (EventKind)(0), // 2: agentsessions.v1.EventKind - (ToolChoice_Mode)(0), // 3: agentsessions.v1.ToolChoice.Mode - (ToolResult_Code)(0), // 4: agentsessions.v1.ToolResult.Code - (Lifecycle_Kind)(0), // 5: agentsessions.v1.Lifecycle.Kind - (*ReconstructionInfo)(nil), // 6: agentsessions.v1.ReconstructionInfo - (*ResourceMetadata)(nil), // 7: agentsessions.v1.ResourceMetadata - (*Part)(nil), // 8: agentsessions.v1.Part - (*TextPart)(nil), // 9: agentsessions.v1.TextPart - (*FilePart)(nil), // 10: agentsessions.v1.FilePart - (*DataPart)(nil), // 11: agentsessions.v1.DataPart - (*ReasoningPart)(nil), // 12: agentsessions.v1.ReasoningPart - (*Message)(nil), // 13: agentsessions.v1.Message - (*IdentityRef)(nil), // 14: agentsessions.v1.IdentityRef - (*Origin)(nil), // 15: agentsessions.v1.Origin - (*CallerIdentity)(nil), // 16: agentsessions.v1.CallerIdentity - (*ModelCall)(nil), // 17: agentsessions.v1.ModelCall - (*ToolDefinition)(nil), // 18: agentsessions.v1.ToolDefinition - (*ToolChoice)(nil), // 19: agentsessions.v1.ToolChoice - (*Usage)(nil), // 20: agentsessions.v1.Usage - (*ToolCall)(nil), // 21: agentsessions.v1.ToolCall - (*ToolResult)(nil), // 22: agentsessions.v1.ToolResult - (*ApprovalRequest)(nil), // 23: agentsessions.v1.ApprovalRequest - (*ApprovalResult)(nil), // 24: agentsessions.v1.ApprovalResult - (*ApprovalRef)(nil), // 25: agentsessions.v1.ApprovalRef - (*Error)(nil), // 26: agentsessions.v1.Error - (*HarnessEnd)(nil), // 27: agentsessions.v1.HarnessEnd - (*Lifecycle)(nil), // 28: agentsessions.v1.Lifecycle - (*ExecutionStart)(nil), // 29: agentsessions.v1.ExecutionStart - (*Event)(nil), // 30: agentsessions.v1.Event - (*LogRecord)(nil), // 31: agentsessions.v1.LogRecord - nil, // 32: agentsessions.v1.Origin.AttributesEntry - nil, // 33: agentsessions.v1.ModelCall.ParamsEntry - (*timestamppb.Timestamp)(nil), // 34: google.protobuf.Timestamp - (*structpb.Struct)(nil), // 35: google.protobuf.Struct + (HarnessClass)(0), // 0: agentsessions.v1.HarnessClass + (Mediation)(0), // 1: agentsessions.v1.Mediation + (EventKind)(0), // 2: agentsessions.v1.EventKind + (ModelCall_ResultCorrelation)(0), // 3: agentsessions.v1.ModelCall.ResultCorrelation + (ToolChoice_Mode)(0), // 4: agentsessions.v1.ToolChoice.Mode + (ToolResult_Code)(0), // 5: agentsessions.v1.ToolResult.Code + (Lifecycle_Kind)(0), // 6: agentsessions.v1.Lifecycle.Kind + (*ReconstructionInfo)(nil), // 7: agentsessions.v1.ReconstructionInfo + (*ResourceMetadata)(nil), // 8: agentsessions.v1.ResourceMetadata + (*Part)(nil), // 9: agentsessions.v1.Part + (*TextPart)(nil), // 10: agentsessions.v1.TextPart + (*FilePart)(nil), // 11: agentsessions.v1.FilePart + (*DataPart)(nil), // 12: agentsessions.v1.DataPart + (*ReasoningPart)(nil), // 13: agentsessions.v1.ReasoningPart + (*Message)(nil), // 14: agentsessions.v1.Message + (*IdentityRef)(nil), // 15: agentsessions.v1.IdentityRef + (*Origin)(nil), // 16: agentsessions.v1.Origin + (*CallerIdentity)(nil), // 17: agentsessions.v1.CallerIdentity + (*ModelCall)(nil), // 18: agentsessions.v1.ModelCall + (*ToolDefinition)(nil), // 19: agentsessions.v1.ToolDefinition + (*ToolChoice)(nil), // 20: agentsessions.v1.ToolChoice + (*Usage)(nil), // 21: agentsessions.v1.Usage + (*ToolCall)(nil), // 22: agentsessions.v1.ToolCall + (*ToolResult)(nil), // 23: agentsessions.v1.ToolResult + (*ApprovalRequest)(nil), // 24: agentsessions.v1.ApprovalRequest + (*ApprovalResult)(nil), // 25: agentsessions.v1.ApprovalResult + (*ApprovalRef)(nil), // 26: agentsessions.v1.ApprovalRef + (*Error)(nil), // 27: agentsessions.v1.Error + (*HarnessEnd)(nil), // 28: agentsessions.v1.HarnessEnd + (*Lifecycle)(nil), // 29: agentsessions.v1.Lifecycle + (*ExecutionStart)(nil), // 30: agentsessions.v1.ExecutionStart + (*Event)(nil), // 31: agentsessions.v1.Event + (*LogRecord)(nil), // 32: agentsessions.v1.LogRecord + nil, // 33: agentsessions.v1.Origin.AttributesEntry + nil, // 34: agentsessions.v1.ModelCall.ParamsEntry + (*timestamppb.Timestamp)(nil), // 35: google.protobuf.Timestamp + (*structpb.Struct)(nil), // 36: google.protobuf.Struct } var file_common_proto_depIdxs = []int32{ 0, // 0: agentsessions.v1.ReconstructionInfo.harness_class:type_name -> agentsessions.v1.HarnessClass - 34, // 1: agentsessions.v1.ResourceMetadata.create_time:type_name -> google.protobuf.Timestamp - 34, // 2: agentsessions.v1.ResourceMetadata.update_time:type_name -> google.protobuf.Timestamp - 9, // 3: agentsessions.v1.Part.text:type_name -> agentsessions.v1.TextPart - 10, // 4: agentsessions.v1.Part.file:type_name -> agentsessions.v1.FilePart - 11, // 5: agentsessions.v1.Part.data:type_name -> agentsessions.v1.DataPart - 12, // 6: agentsessions.v1.Part.reasoning:type_name -> agentsessions.v1.ReasoningPart - 21, // 7: agentsessions.v1.Part.tool_call:type_name -> agentsessions.v1.ToolCall - 22, // 8: agentsessions.v1.Part.tool_result:type_name -> agentsessions.v1.ToolResult - 35, // 9: agentsessions.v1.DataPart.data:type_name -> google.protobuf.Struct - 8, // 10: agentsessions.v1.ReasoningPart.summary:type_name -> agentsessions.v1.Part - 8, // 11: agentsessions.v1.Message.parts:type_name -> agentsessions.v1.Part - 32, // 12: agentsessions.v1.Origin.attributes:type_name -> agentsessions.v1.Origin.AttributesEntry - 33, // 13: agentsessions.v1.ModelCall.params:type_name -> agentsessions.v1.ModelCall.ParamsEntry - 13, // 14: agentsessions.v1.ModelCall.messages:type_name -> agentsessions.v1.Message - 18, // 15: agentsessions.v1.ModelCall.tools:type_name -> agentsessions.v1.ToolDefinition - 19, // 16: agentsessions.v1.ModelCall.tool_choice:type_name -> agentsessions.v1.ToolChoice - 35, // 17: agentsessions.v1.ToolDefinition.input_schema:type_name -> google.protobuf.Struct - 3, // 18: agentsessions.v1.ToolChoice.mode:type_name -> agentsessions.v1.ToolChoice.Mode - 35, // 19: agentsessions.v1.ToolCall.args:type_name -> google.protobuf.Struct - 1, // 20: agentsessions.v1.ToolCall.mediation:type_name -> agentsessions.v1.Mediation - 35, // 21: agentsessions.v1.ToolResult.output:type_name -> google.protobuf.Struct - 8, // 22: agentsessions.v1.ToolResult.content:type_name -> agentsessions.v1.Part - 4, // 23: agentsessions.v1.ToolResult.code:type_name -> agentsessions.v1.ToolResult.Code - 16, // 24: agentsessions.v1.ApprovalResult.verified_approver:type_name -> agentsessions.v1.CallerIdentity - 26, // 25: agentsessions.v1.HarnessEnd.error:type_name -> agentsessions.v1.Error - 5, // 26: agentsessions.v1.Lifecycle.kind:type_name -> agentsessions.v1.Lifecycle.Kind - 34, // 27: agentsessions.v1.Event.ts:type_name -> google.protobuf.Timestamp - 2, // 28: agentsessions.v1.Event.kind:type_name -> agentsessions.v1.EventKind - 13, // 29: agentsessions.v1.Event.message:type_name -> agentsessions.v1.Message - 17, // 30: agentsessions.v1.Event.model:type_name -> agentsessions.v1.ModelCall - 21, // 31: agentsessions.v1.Event.tool:type_name -> agentsessions.v1.ToolCall - 22, // 32: agentsessions.v1.Event.result:type_name -> agentsessions.v1.ToolResult - 23, // 33: agentsessions.v1.Event.approval:type_name -> agentsessions.v1.ApprovalRequest - 24, // 34: agentsessions.v1.Event.approval_result:type_name -> agentsessions.v1.ApprovalResult - 20, // 35: agentsessions.v1.Event.usage:type_name -> agentsessions.v1.Usage - 28, // 36: agentsessions.v1.Event.lifecycle:type_name -> agentsessions.v1.Lifecycle - 27, // 37: agentsessions.v1.Event.end:type_name -> agentsessions.v1.HarnessEnd - 26, // 38: agentsessions.v1.Event.error:type_name -> agentsessions.v1.Error - 29, // 39: agentsessions.v1.Event.execution_start:type_name -> agentsessions.v1.ExecutionStart - 25, // 40: agentsessions.v1.Event.parked:type_name -> agentsessions.v1.ApprovalRef - 6, // 41: agentsessions.v1.Event.reconstruction_info:type_name -> agentsessions.v1.ReconstructionInfo - 14, // 42: agentsessions.v1.Event.actor:type_name -> agentsessions.v1.IdentityRef - 30, // 43: agentsessions.v1.LogRecord.event:type_name -> agentsessions.v1.Event - 44, // [44:44] is the sub-list for method output_type - 44, // [44:44] is the sub-list for method input_type - 44, // [44:44] is the sub-list for extension type_name - 44, // [44:44] is the sub-list for extension extendee - 0, // [0:44] is the sub-list for field type_name + 35, // 1: agentsessions.v1.ResourceMetadata.create_time:type_name -> google.protobuf.Timestamp + 35, // 2: agentsessions.v1.ResourceMetadata.update_time:type_name -> google.protobuf.Timestamp + 10, // 3: agentsessions.v1.Part.text:type_name -> agentsessions.v1.TextPart + 11, // 4: agentsessions.v1.Part.file:type_name -> agentsessions.v1.FilePart + 12, // 5: agentsessions.v1.Part.data:type_name -> agentsessions.v1.DataPart + 13, // 6: agentsessions.v1.Part.reasoning:type_name -> agentsessions.v1.ReasoningPart + 22, // 7: agentsessions.v1.Part.tool_call:type_name -> agentsessions.v1.ToolCall + 23, // 8: agentsessions.v1.Part.tool_result:type_name -> agentsessions.v1.ToolResult + 36, // 9: agentsessions.v1.DataPart.data:type_name -> google.protobuf.Struct + 9, // 10: agentsessions.v1.ReasoningPart.summary:type_name -> agentsessions.v1.Part + 9, // 11: agentsessions.v1.Message.parts:type_name -> agentsessions.v1.Part + 33, // 12: agentsessions.v1.Origin.attributes:type_name -> agentsessions.v1.Origin.AttributesEntry + 34, // 13: agentsessions.v1.ModelCall.params:type_name -> agentsessions.v1.ModelCall.ParamsEntry + 14, // 14: agentsessions.v1.ModelCall.messages:type_name -> agentsessions.v1.Message + 19, // 15: agentsessions.v1.ModelCall.tools:type_name -> agentsessions.v1.ToolDefinition + 20, // 16: agentsessions.v1.ModelCall.tool_choice:type_name -> agentsessions.v1.ToolChoice + 3, // 17: agentsessions.v1.ModelCall.result_correlation:type_name -> agentsessions.v1.ModelCall.ResultCorrelation + 36, // 18: agentsessions.v1.ToolDefinition.input_schema:type_name -> google.protobuf.Struct + 4, // 19: agentsessions.v1.ToolChoice.mode:type_name -> agentsessions.v1.ToolChoice.Mode + 36, // 20: agentsessions.v1.ToolCall.args:type_name -> google.protobuf.Struct + 1, // 21: agentsessions.v1.ToolCall.mediation:type_name -> agentsessions.v1.Mediation + 36, // 22: agentsessions.v1.ToolResult.output:type_name -> google.protobuf.Struct + 9, // 23: agentsessions.v1.ToolResult.content:type_name -> agentsessions.v1.Part + 5, // 24: agentsessions.v1.ToolResult.code:type_name -> agentsessions.v1.ToolResult.Code + 17, // 25: agentsessions.v1.ApprovalResult.verified_approver:type_name -> agentsessions.v1.CallerIdentity + 27, // 26: agentsessions.v1.HarnessEnd.error:type_name -> agentsessions.v1.Error + 6, // 27: agentsessions.v1.Lifecycle.kind:type_name -> agentsessions.v1.Lifecycle.Kind + 35, // 28: agentsessions.v1.Event.ts:type_name -> google.protobuf.Timestamp + 2, // 29: agentsessions.v1.Event.kind:type_name -> agentsessions.v1.EventKind + 14, // 30: agentsessions.v1.Event.message:type_name -> agentsessions.v1.Message + 18, // 31: agentsessions.v1.Event.model:type_name -> agentsessions.v1.ModelCall + 22, // 32: agentsessions.v1.Event.tool:type_name -> agentsessions.v1.ToolCall + 23, // 33: agentsessions.v1.Event.result:type_name -> agentsessions.v1.ToolResult + 24, // 34: agentsessions.v1.Event.approval:type_name -> agentsessions.v1.ApprovalRequest + 25, // 35: agentsessions.v1.Event.approval_result:type_name -> agentsessions.v1.ApprovalResult + 21, // 36: agentsessions.v1.Event.usage:type_name -> agentsessions.v1.Usage + 29, // 37: agentsessions.v1.Event.lifecycle:type_name -> agentsessions.v1.Lifecycle + 28, // 38: agentsessions.v1.Event.end:type_name -> agentsessions.v1.HarnessEnd + 27, // 39: agentsessions.v1.Event.error:type_name -> agentsessions.v1.Error + 30, // 40: agentsessions.v1.Event.execution_start:type_name -> agentsessions.v1.ExecutionStart + 26, // 41: agentsessions.v1.Event.parked:type_name -> agentsessions.v1.ApprovalRef + 7, // 42: agentsessions.v1.Event.reconstruction_info:type_name -> agentsessions.v1.ReconstructionInfo + 15, // 43: agentsessions.v1.Event.actor:type_name -> agentsessions.v1.IdentityRef + 31, // 44: agentsessions.v1.LogRecord.event:type_name -> agentsessions.v1.Event + 45, // [45:45] is the sub-list for method output_type + 45, // [45:45] is the sub-list for method input_type + 45, // [45:45] is the sub-list for extension type_name + 45, // [45:45] is the sub-list for extension extendee + 0, // [0:45] is the sub-list for field type_name } func init() { file_common_proto_init() } @@ -3086,7 +3162,7 @@ func file_common_proto_init() { File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_common_proto_rawDesc), len(file_common_proto_rawDesc)), - NumEnums: 6, + NumEnums: 7, NumMessages: 28, NumExtensions: 0, NumServices: 0, diff --git a/api/types.go b/api/types.go index af089847..dfaad31c 100644 --- a/api/types.go +++ b/api/types.go @@ -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 } @@ -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 diff --git a/canon/canon_test.go b/canon/canon_test.go index 0a0621ee..940749e4 100644 --- a/canon/canon_test.go +++ b/canon/canon_test.go @@ -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 diff --git a/changelog/unreleased/model-result-correlation-compat.md b/changelog/unreleased/model-result-correlation-compat.md new file mode 100644 index 00000000..2ff65563 --- /dev/null +++ b/changelog/unreleased/model-result-correlation-compat.md @@ -0,0 +1,9 @@ +--- +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 a failed re-drive of an old positional call, immediate + direct fallback output is refused as ambiguous; a fresh model-call retry remains supported. diff --git a/changelog/unreleased/model-result-correlation.md b/changelog/unreleased/model-result-correlation.md new file mode 100644 index 00000000..f68d30cd --- /dev/null +++ b/changelog/unreleased/model-result-correlation.md @@ -0,0 +1,6 @@ +--- +category: Fixed +--- + +- Provider-result `OUTPUT` records name the durable `MODEL_CALL` they answer. Replay and recovery no + longer reinterpret direct fallback output after a handled provider error as model success. diff --git a/controller/effects.go b/controller/effects.go index 9d187a36..51bc8e3f 100644 --- a/controller/effects.go +++ b/controller/effects.go @@ -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) @@ -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, @@ -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 @@ -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 @@ -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() diff --git a/controller/executions.go b/controller/executions.go index ec879127..afccfeb1 100644 --- a/controller/executions.go +++ b/controller/executions.go @@ -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 diff --git a/controller/legacy.go b/controller/legacy.go index fc5fd949..18eb18e5 100644 --- a/controller/legacy.go +++ b/controller/legacy.go @@ -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 { @@ -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 diff --git a/controller/model_result.go b/controller/model_result.go new file mode 100644 index 00000000..89bb27de --- /dev/null +++ b/controller/model_result.go @@ -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 +} diff --git a/controller/resume.go b/controller/resume.go index c3944393..d12f68dd 100644 --- a/controller/resume.go +++ b/controller/resume.go @@ -244,6 +244,10 @@ type resumeSink struct { // awaitingGate is set by continueAtGate until the first sink call: only the gated ToolCall // may come first (APR-16). awaitingGate bool + // ambiguousLegacyFailure marks a failed re-drive of a pre-v11 positional call. A direct OUTPUT + // cannot be the next durable effect: later replay would mistake it for that call's completion. + // Any other successfully appended effect, including a fresh BY_ID model-call retry, clears it. + ambiguousLegacyFailure bool } // continueAtGate positions a memory-tier recovery at its decided, unreceipted approval gate @@ -326,8 +330,11 @@ func (s *resumeSink) 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("resume: model input hash mismatch (I0)")) } - out, ok := s.recordedNext(api.EventOutput) - if !ok { + out, found, correlationErr := recordedModelResult(s.stream, s.i, mc.ModelCall) + if correlationErr != nil { + return api.ModelResponse{}, s.diverged(fmt.Errorf("resume: %w", correlationErr)) + } + if !found { if s.i != len(s.stream) { return api.ModelResponse{}, errors.New("resume: recorded completion missing") } @@ -341,8 +348,19 @@ func (s *resumeSink) Model(ctx context.Context, req api.ModelRequest) (api.Model // without calling the model; only journals with execution IDs are re-driven. return api.ModelResponse{}, errors.New("resume: recorded completion missing") } - return s.live.completeModel(ctx, req) + if mc.ModelCall == nil || mc.ModelCall.ID == "" { + if mc.ModelCall != nil && mc.ModelCall.ResultCorrelation == api.ModelResultCorrelationUnspecified { + s.ambiguousLegacyFailure = true + } + return api.ModelResponse{}, errors.New("resume: recorded model call has no ID") + } + resp, err := s.live.completeModel(ctx, req, mc.ModelCall.ID) + if err != nil && mc.ModelCall.ResultCorrelation == api.ModelResultCorrelationUnspecified { + s.ambiguousLegacyFailure = true + } + return resp, err } + s.i++ var msg api.Message if out.Message != nil { msg = *out.Message @@ -355,7 +373,12 @@ func (s *resumeSink) Model(ctx context.Context, req api.ModelRequest) (api.Model } return api.ModelResponse{Message: msg, Usage: usage}, nil } - return s.live.model(ctx, req) // past the crash point: first-ever execution + before := s.live.appends + resp, err := s.live.model(ctx, req) // past the crash point: first-ever execution + if s.live.appends > before { + s.ambiguousLegacyFailure = false + } + return resp, err } func (s *resumeSink) Output(ctx context.Context, delta string) error { @@ -380,6 +403,9 @@ func (s *resumeSink) Output(ctx context.Context, delta string) error { if !ok { return s.diverged(errors.New("resume: recorded stream diverged (expected output)")) } + if out.ModelCallID != nil { + return s.diverged(errors.New("resume: direct output matched a model result")) + } recorded := "" if out.Message != nil { recorded = out.Message.Text() @@ -389,6 +415,9 @@ func (s *resumeSink) Output(ctx context.Context, delta string) error { } return nil } + if s.ambiguousLegacyFailure { + return s.diverged(errors.New("resume: direct output immediately after a failed legacy model call is ambiguous")) + } return s.live.output(ctx, delta) } @@ -475,7 +504,12 @@ func (s *resumeSink) ToolCall(ctx context.Context, tc api.ToolCall) (api.ToolRes // outcomes, not evidence failures: the harness may handle them and finish the turn. return s.live.execTool(ctx, *call.ToolCall) } - return s.live.toolCall(ctx, tc) + before := s.live.appends + result, err := s.live.toolCall(ctx, tc) + if s.live.appends > before { + s.ambiguousLegacyFailure = false + } + return result, err } func (s *resumeSink) Report(ctx context.Context, tr api.ToolResult) error { @@ -515,7 +549,12 @@ func (s *resumeSink) Report(ctx context.Context, tr api.ToolResult) error { } return nil } - return s.live.report(ctx, tr) + before := s.live.appends + err := s.live.report(ctx, tr) + if s.live.appends > before { + s.ambiguousLegacyFailure = false + } + return err } func (s *resumeSink) Usage(ctx context.Context, u api.Usage) error { @@ -554,5 +593,10 @@ func (s *resumeSink) Usage(ctx context.Context, u api.Usage) error { } return nil } - return s.live.usage(ctx, u) + before := s.live.appends + err := s.live.usage(ctx, u) + if s.live.appends > before { + s.ambiguousLegacyFailure = false + } + return err } diff --git a/controller/resume_model_cut_test.go b/controller/resume_model_cut_test.go index 0f21025e..1f01ef4f 100644 --- a/controller/resume_model_cut_test.go +++ b/controller/resume_model_cut_test.go @@ -66,6 +66,53 @@ func (retryHarness) Run(ctx context.Context, s *api.Start, sink api.EventSink) e return err } +// fallbackHarness handles a model error by emitting direct fallback output. Replay and recovery +// must return the model failure again rather than reinterpret that output as provider success. +type fallbackHarness struct { + id string + crash func() + success *int +} + +type swallowCorrelationHarness struct { + first, later error +} + +func (*swallowCorrelationHarness) Describe(context.Context) (api.Descriptor, error) { + return api.Descriptor{ID: "echo", Capabilities: api.Capabilities{Resumability: api.ResumabilityStatelessReplay}}, nil +} + +func (h *swallowCorrelationHarness) Run(ctx context.Context, s *api.Start, sink api.EventSink) error { + _, h.first = sink.Model(ctx, api.ModelRequest{Model: "echo", Messages: []api.Message{s.Inputs[0]}}) + h.later = sink.Output(ctx, "later") + return nil +} + +func (h fallbackHarness) Describe(context.Context) (api.Descriptor, error) { + id := h.id + if id == "" { + id = "fallback" + } + return api.Descriptor{ID: id, Capabilities: api.Capabilities{Resumability: api.ResumabilityStatelessReplay}}, nil +} + +func (h fallbackHarness) Run(ctx context.Context, s *api.Start, sink api.EventSink) error { + _, err := sink.Model(ctx, api.ModelRequest{Model: "echo", Messages: []api.Message{s.Inputs[0]}}) + if err == nil { + if h.success != nil { + (*h.success)++ + } + return errors.New("model unexpectedly succeeded") + } + if err := sink.Output(ctx, "fallback"); err != nil { + return err + } + if h.crash != nil { + h.crash() + } + return nil +} + func journalKinds(t *testing.T, log eventlog.Store) []api.EventKind { t.Helper() recs, err := log.Read(1) @@ -131,14 +178,27 @@ func resumeOnce(t *testing.T, log eventlog.Store, har api.Harness, model *script // replays with zero provider calls. func assertRecovered(t *testing.T, log eventlog.Store) { t.Helper() - kinds := journalKinds(t, log) + records, err := log.Read(1) + if err != nil { + t.Fatal(err) + } + kinds := make([]api.EventKind, 0, len(records)) var calls, outputs int - for _, k := range kinds { - switch k { + var callID string + for _, record := range records { + kinds = append(kinds, record.Event.Kind) + switch record.Event.Kind { case api.EventModelCall: calls++ + if record.Event.ModelCall == nil || record.Event.ModelCall.ResultCorrelation != api.ModelResultCorrelationByID || record.Event.ModelCall.ID == "" { + t.Fatalf("recorded model call lacks ID correlation: %+v", record.Event.ModelCall) + } + callID = record.Event.ModelCall.ID case api.EventOutput: outputs++ + if record.Event.ModelCallID == nil || *record.Event.ModelCallID != callID { + t.Fatalf("recorded model result ID = %v, want %q", record.Event.ModelCallID, callID) + } } } if calls != 1 || outputs != 1 { @@ -276,6 +336,282 @@ func TestResumeRetryAfterFailedRedrive(t *testing.T) { } } +func TestModelResultIDsDistinguishProviderResultsFromFallbackOutput(t *testing.T) { + log := memStore(t) + store := &crashStore{Store: log} + model := &scriptedModel{failures: 1} + c, err := controller.New(store, model.call) + if err != nil { + t.Fatal(err) + } + h := fallbackHarness{crash: func() { store.crashed = true }} + if err := c.Exec(t.Context(), h, []api.Message{msg("hi")}, 0); !errors.Is(err, errCrashed) { + t.Fatalf("Exec = %v, want crash after fallback", err) + } + recs, err := log.Read(1) + if err != nil { + t.Fatal(err) + } + if len(recs) != 4 || recs[2].Event.ModelCall == nil || recs[2].Event.ModelCall.ResultCorrelation != api.ModelResultCorrelationByID || + recs[3].Event.Kind != api.EventOutput || recs[3].Event.ModelCallID != nil { + t.Fatalf("journal does not distinguish call and direct fallback: %+v", recs) + } + + success := 0 + recoveryModel := &scriptedModel{} + if err := resumeOnce(t, log, fallbackHarness{success: &success}, recoveryModel); err != nil { + t.Fatalf("Resume = %v", err) + } + if recoveryModel.calls != 0 || success != 0 { + t.Fatalf("Resume treated fallback as model success: provider=%d success-path=%d", recoveryModel.calls, success) + } + assertKinds(t, log, api.EventExecutionStart, api.EventInput, api.EventModelCall, api.EventOutput, api.EventEnd) + + replayModel := &scriptedModel{} + replay, err := controller.New(log, replayModel.call) + if err != nil { + t.Fatal(err) + } + out, err := replay.Replay(t.Context(), fallbackHarness{success: &success}) + if err != nil || !reflect.DeepEqual(out, []string{"fallback"}) || replayModel.calls != 0 || success != 0 { + t.Fatalf("Replay = outputs %v err %v provider=%d success-path=%d", out, err, replayModel.calls, success) + } +} + +func TestModelResultCorrelationIsExact(t *testing.T) { + for _, tc := range []struct { + name string + change func(*api.Event, *api.Event) + }{ + {name: "wrong result ID", change: func(_ *api.Event, output *api.Event) { output.ModelCallID = stringPointer("other") }}, + {name: "empty result ID", change: func(_ *api.Event, output *api.Event) { output.ModelCallID = stringPointer("") }}, + {name: "empty call ID", change: func(call, _ *api.Event) { call.ModelCall.ID = "" }}, + {name: "unknown mode", change: func(call, _ *api.Event) { call.ModelCall.ResultCorrelation = 99 }}, + } { + t.Run(tc.name, func(t *testing.T) { + source := memStore(t) + c, err := controller.New(source, echoModel) + if err != nil { + t.Fatal(err) + } + if err := c.Exec(t.Context(), &echoHarness{}, []api.Message{msg("hi")}, 0); err != nil { + t.Fatal(err) + } + records, err := source.Read(1) + if err != nil { + t.Fatal(err) + } + tc.change(&records[2].Event, &records[3].Event) + + log := memStore(t) + fence, err := log.NewFence() + if err != nil { + t.Fatal(err) + } + for i, record := range records { + if _, err := log.Append(int64(i), fence, record.Event); err != nil { + t.Fatal(err) + } + } + replay, err := controller.New(log, nil) + if err != nil { + t.Fatal(err) + } + if _, err := replay.Replay(t.Context(), &echoHarness{}); !errors.Is(err, controller.ErrReplayDiverged) { + t.Fatalf("Replay = %v, want ErrReplayDiverged", err) + } + }) + } +} + +func TestResumeModelResultCorrelationIsExactAndSticky(t *testing.T) { + for _, tc := range []struct { + name string + change func(*api.Event, *api.Event) + }{ + {name: "wrong result ID", change: func(_ *api.Event, output *api.Event) { output.ModelCallID = stringPointer("other") }}, + {name: "empty result ID", change: func(_ *api.Event, output *api.Event) { output.ModelCallID = stringPointer("") }}, + {name: "empty call ID", change: func(call, _ *api.Event) { call.ModelCall.ID = "" }}, + {name: "unknown mode", change: func(call, _ *api.Event) { call.ModelCall.ResultCorrelation = 99 }}, + } { + t.Run(tc.name, func(t *testing.T) { + source := memStore(t) + store := &crashStore{Store: source} + c, err := controller.New(store, echoModel) + if err != nil { + t.Fatal(err) + } + if err := c.Exec(t.Context(), &crashAfterModelHarness{crash: func() { store.crashed = true }}, []api.Message{msg("hi")}, 0); !errors.Is(err, errCrashed) { + t.Fatal(err) + } + records, err := source.Read(1) + if err != nil { + t.Fatal(err) + } + tc.change(&records[2].Event, &records[3].Event) + log := memStore(t) + fence, err := log.NewFence() + if err != nil { + t.Fatal(err) + } + for i, record := range records { + if _, err := log.Append(int64(i), fence, record.Event); err != nil { + t.Fatal(err) + } + } + model := &scriptedModel{} + err = resumeOnce(t, log, &echoHarness{}, model) + if !errors.Is(err, controller.ErrReplayDiverged) || model.calls != 0 { + t.Fatalf("Resume = %v provider=%d, want divergence without provider", err, model.calls) + } + assertKinds(t, log, api.EventExecutionStart, api.EventInput, api.EventModelCall, api.EventOutput, api.EventError) + }) + } +} + +func TestModelResultCorrelationDivergenceStaysSticky(t *testing.T) { + log := memStore(t) + c, err := controller.New(log, echoModel) + if err != nil { + t.Fatal(err) + } + if err := c.Exec(t.Context(), &echoHarness{}, []api.Message{msg("hi")}, 0); err != nil { + t.Fatal(err) + } + records, err := log.Read(1) + if err != nil { + t.Fatal(err) + } + records[3].Event.ModelCallID = stringPointer("wrong") + tampered := memStore(t) + fence, err := tampered.NewFence() + if err != nil { + t.Fatal(err) + } + for i, record := range records { + if _, err := tampered.Append(int64(i), fence, record.Event); err != nil { + t.Fatal(err) + } + } + h := &swallowCorrelationHarness{} + replay, err := controller.New(tampered, nil) + if err != nil { + t.Fatal(err) + } + if _, err := replay.Replay(t.Context(), h); !errors.Is(err, controller.ErrReplayDiverged) || + !errors.Is(h.first, controller.ErrReplayDiverged) || h.later != h.first { + t.Fatalf("Replay=%v first=%v later=%v, want the same sticky divergence", err, h.first, h.later) + } +} + +func TestLegacyPositionalModelResultStillReplays(t *testing.T) { + source := memStore(t) + c, err := controller.New(source, echoModel) + if err != nil { + t.Fatal(err) + } + if err := c.Exec(t.Context(), &echoHarness{}, []api.Message{msg("hi")}, 0); err != nil { + t.Fatal(err) + } + records, err := source.Read(1) + if err != nil { + t.Fatal(err) + } + records[2].Event.ModelCall.ResultCorrelation = api.ModelResultCorrelationUnspecified + records[3].Event.ModelCallID = nil + legacy := memStore(t) + fence, err := legacy.NewFence() + if err != nil { + t.Fatal(err) + } + for i, record := range records { + if _, err := legacy.Append(int64(i), fence, record.Event); err != nil { + t.Fatal(err) + } + } + replay, err := controller.New(legacy, nil) + if err != nil { + t.Fatal(err) + } + out, err := replay.Replay(t.Context(), &echoHarness{}) + if err != nil || !reflect.DeepEqual(out, []string{"echo:hi"}) { + t.Fatalf("legacy Replay = %v, %v", out, err) + } +} + +func TestFailedLegacyRedriveRefusesImmediateFallback(t *testing.T) { + log := memStore(t) + execCutAtModelCall(t, log, true) + records, err := log.Read(1) + if err != nil { + t.Fatal(err) + } + if records[2].Event.ModelCall == nil { + t.Fatal("missing recorded model call") + } + records[2].Event.ModelCall.ResultCorrelation = api.ModelResultCorrelationUnspecified + legacy := memStore(t) + fence, err := legacy.NewFence() + if err != nil { + t.Fatal(err) + } + for i, record := range records { + if _, err := legacy.Append(int64(i), fence, record.Event); err != nil { + t.Fatal(err) + } + } + model := &scriptedModel{failures: 1} + err = resumeOnce(t, legacy, fallbackHarness{id: "echo"}, model) + if !errors.Is(err, controller.ErrReplayDiverged) || model.calls != 1 { + t.Fatalf("Resume = %v provider=%d, want divergence after one failed re-drive", err, model.calls) + } + assertKinds(t, legacy, api.EventExecutionStart, api.EventInput, api.EventModelCall, api.EventError) +} + +func TestFailedLegacyRedriveAllowsFreshCorrelatedRetry(t *testing.T) { + log := memStore(t) + execCutAtModelCall(t, log, true) + records, err := log.Read(1) + if err != nil { + t.Fatal(err) + } + records[2].Event.ModelCall.ResultCorrelation = api.ModelResultCorrelationUnspecified + legacy := memStore(t) + fence, err := legacy.NewFence() + if err != nil { + t.Fatal(err) + } + for i, record := range records { + if _, err := legacy.Append(int64(i), fence, record.Event); err != nil { + t.Fatal(err) + } + } + model := &scriptedModel{failures: 1} + if err := resumeOnce(t, legacy, retryHarness{}, model); err != nil { + t.Fatalf("Resume = %v", err) + } + records, err = legacy.Read(1) + if err != nil { + t.Fatal(err) + } + var calls []*api.ModelCall + var resultID string + for _, record := range records { + if record.Event.ModelCall != nil { + calls = append(calls, record.Event.ModelCall) + } + if record.Event.ModelCallID != nil { + resultID = *record.Event.ModelCallID + } + } + if len(calls) != 2 || calls[0].ResultCorrelation != api.ModelResultCorrelationUnspecified || + calls[1].ResultCorrelation != api.ModelResultCorrelationByID || calls[0].ID == calls[1].ID || resultID != calls[1].ID { + t.Fatalf("retry correlation calls=%+v resultID=%q", calls, resultID) + } +} + +func stringPointer(value string) *string { return &value } + // A re-issued request whose input hash differs from the recorded MODEL_CALL is divergence: no // provider call, nothing recorded for the call, and the turn stays recoverable by a matching // harness. diff --git a/docs/api-reference.md b/docs/api-reference.md index 047e5232..083a9c3b 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -169,6 +169,7 @@ transport (see Delta in session.proto) and coalesce into the finalized event (§ | parked | [ApprovalRef](#agentsessions-v1-ApprovalRef) | | EVENT_PARKED echoes the park reference; Event.execution_id must match its execution_id. | | reconstruction_info | [ReconstructionInfo](#agentsessions-v1-ReconstructionInfo) | | | | actor | [IdentityRef](#agentsessions-v1-IdentityRef) | | emitter principal -> provenance | +| model_call_id | [string](#string) | optional | 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. | @@ -325,13 +326,14 @@ message. Under STATELESS_REPLAY the harness never calls a provider directly. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| model | [string](#string) | | 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. | +| model | [string](#string) | | 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. Admitted policy-enabled calls record the resolved model in this field. | | params | [ModelCall.ParamsEntry](#agentsessions-v1-ModelCall-ParamsEntry) | repeated | | | input_hash | [string](#string) | | §7/§9.1: required for STATELESS_REPLAY so the I0 check can run | | id | [string](#string) | | correlation id for the served ModelResult | | messages | [Message](#agentsessions-v1-Message) | repeated | messages is the request context the host needs to INVOKE the model on the live path. It is wire-only: the host records the call with input_hash alone (messages stripped), since the recorded form only needs the hash to re-check I0 on replay. | | tools | [ToolDefinition](#agentsessions-v1-ToolDefinition) | repeated | tools are the definitions offered to the model on this call. Wire-only like messages: the recorded form keeps input_hash, which covers them. | | tool_choice | [ToolChoice](#agentsessions-v1-ToolChoice) | | tool_choice constrains whether and which tool the model calls. Wire-only like messages and covered by input_hash. Unset means the provider default. | +| result_correlation | [ModelCall.ResultCorrelation](#agentsessions-v1-ModelCall-ResultCorrelation) | | Host-owned durable correlation mode. New journaled calls use BY_ID; omitted preserves the positional interpretation of journals written before model-result correlation. | @@ -660,6 +662,18 @@ Mediation controls how a tool call is executed / who enforces record-before-effe + + +### ModelCall.ResultCorrelation + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| RESULT_CORRELATION_UNSPECIFIED | 0 | Legacy journals correlate the next OUTPUT by position. New writers never select this mode. | +| RESULT_CORRELATION_BY_ID | 1 | The provider-result OUTPUT must carry this ModelCall.id in Event.model_call_id. | + + + ### ToolChoice.Mode diff --git a/docs/concepts.md b/docs/concepts.md index b5d88c33..0f3b5a08 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -273,8 +273,8 @@ cost, audit, and tool approval are first-class rather than parsed out of text af |---|---| | `EXECUTION_START` | Host-owned execution config, cursor, input count, resolved harness name and advertised version, recorded before inputs for every new execution. | | `INPUT` | A user or producer input message. | -| `MODEL_CALL` | A call to a model was made (records the model, params, and an input hash for the replay check). | -| `OUTPUT` | Assistant output (a delta or a full message). | +| `MODEL_CALL` | A call to a model was made (records the model, params, input hash, call ID and durable result-correlation mode). | +| `OUTPUT` | Assistant output. A provider result names its `MODEL_CALL`; direct harness output leaves that correlation absent. | | `TOOL_CALL` / `TOOL_RESULT` | A tool invocation and its outcome. Aligned with an MCP tool call. | | `APPROVAL_REQUEST` / `APPROVAL_RESULT` | A host-owned request and explicit caller decision around a tool call. | | `USAGE` | Per-call token and cost accounting. | diff --git a/docs/harness-authoring.md b/docs/harness-authoring.md index 3cb218da..379a8314 100644 --- a/docs/harness-authoring.md +++ b/docs/harness-authoring.md @@ -277,9 +277,12 @@ diverge or re-spend the call. This single rule is why replay never invokes the m that calls its provider anyway is unmediated, whether or not it means to be, and loses that guarantee. -The host records `MODEL_CALL` (with the request's input hash) before it invokes the provider and records -the completion as `OUTPUT` after. A process death or provider error between the two leaves a turn whose -last effect is a `MODEL_CALL` with no completion. On `Resume`, when your harness re-issues that request, +The host records `MODEL_CALL` (with the request's input hash, call ID and ID-correlation mode) before +it invokes the provider, and records the completion as `OUTPUT` naming that call. Output your harness +emits directly carries no model-call ID, so a handled provider error followed by fallback output is +not replayed as provider success. A process death or provider error between intent and completion +leaves a turn whose last effect is a `MODEL_CALL` with no correlated completion. On `Resume`, when +your harness re-issues that request, the host serves everything recorded before it, checks the re-issued request's input hash against the recorded one, then invokes the provider live and records the completion after that same `MODEL_CALL`. It never records a second `MODEL_CALL` or a second `OUTPUT` for it. This applies to journals with @@ -296,7 +299,9 @@ provider call. If the recovering call fails and your harness returns the error, that `MODEL_CALL` is still the turn's last effect and the next `Resume` re-drives it again. Do not retry a failed `sink.Model` call inside the run. Over the harness wire a `sink.Model` error ends the bridge, so a remote harness never sees it -and cannot retry. An in-process harness that retries only some errors can leave `MODEL_CALL`, `ERROR`, +and cannot retry. After upgrading a markerless pre-v11 call, direct fallback output immediately after +a failed re-drive is refused because it would be positionally ambiguous; issue a fresh model call or +return the error. An in-process harness that retries only some errors can leave `MODEL_CALL`, `ERROR`, `MODEL_CALL`, `OUTPUT`, `END`, which `Replay` rejects when the harness does not reproduce the same retry. A harness that retries every error replays that journal, but returning the error and letting `Resume` re-drive the call is the supported path. diff --git a/docs/session-data-model.md b/docs/session-data-model.md index 7c5827fa..cf22991e 100644 --- a/docs/session-data-model.md +++ b/docs/session-data-model.md @@ -249,6 +249,10 @@ event. Events in one turn share an `execution_id`. The principal event kinds are `PARKED` is a transport acknowledgement and is not journaled. +New `MODEL_CALL` records use ID correlation. Their provider-result `OUTPUT` carries the same +`model_call_id`; output emitted directly by the harness carries none. Calls written before SQLite +schema v11 retain positional result matching for compatibility. + SQLite maintains bounded `approval_executions` and `approval_calls` projections so `GetSession` and `ListSessions` do not need to decode every event. Those tables are reporting evidence only. The controller independently inspects the journal for admission, approval decisions, replay, and diff --git a/hack/verify_chain.py b/hack/verify_chain.py index 93841aef..c34dd9cd 100755 --- a/hack/verify_chain.py +++ b/hack/verify_chain.py @@ -106,6 +106,19 @@ "0d1ff028379c892d4f15b1f331a6a8baabfa2dfb43bf32fbb8095fe03725e0a2", ) +# ID-correlated MODEL_CALL and provider-result OUTPUT (canon +# TestModelResultCorrelationGoldenVectors). The mode marker distinguishes new calls from legacy +# positional calls; model_call_id is present only on the provider result, never direct output. +MODEL_CORRELATION_GOLDENS = [ + ({"execution_id": "exec-model", "kind": "EVENT_MODEL_CALL", + "model": {"model": "gpt-test", "input_hash": "sha256:input", "id": "model-call-1", + "result_correlation": "RESULT_CORRELATION_BY_ID"}}, + "8e5c3dfd99d817ef8123b158230fc1839bdb409e5485674fb6cff46c59d4406d"), + ({"execution_id": "exec-model", "kind": "EVENT_OUTPUT", "model_call_id": "model-call-1", + "message": {"role": "assistant", "parts": [{"text": {"text": "answer"}}]}}, + "f93c67086837ff8a9b4e865e00b52964b35dcd7d3ca94611fde1e49b1ddc1a07"), +] + EVENT_TYPE = "agentsessions.v1.Event" @@ -123,7 +136,7 @@ def golden_check(): return 1 print("DELETE canonical:", DELETE_CANONICAL.decode("utf-8")) vectors = [(GOLDEN_EVENT, GOLDEN_EXPECTED), *START_GOLDENS, TOOL_CALL_GOLDEN, DELETE_GOLDEN, - *FORK_GOLDENS, APPROVAL_GOLDEN] + *FORK_GOLDENS, APPROVAL_GOLDEN, *MODEL_CORRELATION_GOLDENS] for event, expected in vectors: record = {"event": event, "prev_hash": "", "seq": "1"} digest = hashlib.sha256(_stdlib_jcs(record)).hexdigest() diff --git a/spec.md b/spec.md index 32a888ec..c0c32150 100644 --- a/spec.md +++ b/spec.md @@ -330,8 +330,8 @@ no flattened lifecycle enum. |---|---|---|---| | `EVENT_EXECUTION_START` | `ExecutionStart` | host | First record of every new execution (§8.1). | | `EVENT_INPUT` | `Message` | host | One per input message. | -| `EVENT_MODEL_CALL` | `ModelCall` | host | Recorded before the provider is invoked. Journal form keeps `model`, `params`, `input_hash`, `id`; the reference host records only `model`, `input_hash` and `id`, so `params` is covered by `input_hash` alone (`EXE-11`). | -| `EVENT_OUTPUT` | `Message` | host | The finalized model completion (`EXE-12`), or text the harness emits through `Output`: one `assistant` text record per call (a wire harness's message keeps only its text parts). Streaming deltas (`ExecUpdate.delta`) are never journaled. | +| `EVENT_MODEL_CALL` | `ModelCall` | host | Recorded before the provider is invoked. Journal form keeps `model`, `params`, `input_hash`, `id` and `result_correlation`; the reference host records only `model`, `input_hash`, `id` and the correlation mode, so `params` is covered by `input_hash` alone (`EXE-11`). | +| `EVENT_OUTPUT` | `Message` | host | The finalized model completion (`EXE-12`), with `model_call_id` naming its `MODEL_CALL` for new records; or text the harness emits through `Output`, with no model-call ID: one `assistant` text record per call (a wire harness's message keeps only its text parts). Streaming deltas (`ExecUpdate.delta`) are never journaled. | | `EVENT_TOOL_CALL` | `ToolCall` | host | Intent, recorded before a host-executed tool runs. | | `EVENT_TOOL_RESULT` | `ToolResult` | host | Receipt, or a harness-reported result. | | `EVENT_APPROVAL_REQUEST` | `ApprovalRequest` | host only | §10. | @@ -697,9 +697,14 @@ other operations but never sees those calls. ### 8.3 Model calls -- `EXE-10`: On the live path the host MUST append `EVENT_MODEL_CALL` (with `input_hash` and a fresh - call id) before invoking the provider, then append the completion as `EVENT_OUTPUT`. The - `OUTPUT` carries no call id; its position after the `MODEL_CALL` is the correlation. +- `EXE-10`: On the live path the host MUST append `EVENT_MODEL_CALL` (with `input_hash`, a fresh + call id and `result_correlation = BY_ID`) before invoking the provider, then append the completion + as `EVENT_OUTPUT` with `model_call_id` present and equal to that call id. `EventSink.Output` + produces a direct `OUTPUT` with no `model_call_id`. Replay and recovery consume a new call's + provider result only when the IDs match; an empty or different present ID is sticky divergence. + A markerless call retains the positional interpretation of pre-v11 journals: an immediately + following ID-less `OUTPUT` is its completion. This compatibility rule cannot distinguish a + historical fallback output and therefore does not retroactively repair old ambiguous histories. - `EXE-11`: `input_hash` MUST cover the full model request: model, messages, params, tool definitions, and tool choice. In the reference host it is SHA-256 over the Go JSON encoding of `api.ModelRequest`, with later-added fields omitted when empty so older hashes stay stable. It is @@ -721,8 +726,8 @@ other operations but never sees those calls. New live effects of a policy-aware invocation face the current policy, if configured. Removing policy removes membership checks, not the invocation's recorded default. Invocations with an empty recorded default, including markerless journals, retain their old model behavior without - default resolution or membership checks. Per-call IDs remain in the existing `ModelCall.model`; - its format is unchanged. + default resolution or membership checks. Per-call IDs remain in `ModelCall.id`; new calls also + declare their result-correlation mode (`EXE-10`). - `EXE-12`: Model streaming deltas (`ExecUpdate.delta`) MUST NOT be journaled. Exactly one `EVENT_OUTPUT` records each finalized completion. Text a harness passes to `Output` is not a delta: each call is journaled as its own `EVENT_OUTPUT`. @@ -734,7 +739,8 @@ These are named in the reference controller. The numbering is the code's. `I0`, concerns host-executed tools and applies to both classes. - `I0`: On reconstruction replay, each model call the harness re-issues MUST have the same - `input_hash` as the recorded `MODEL_CALL` at that position, its output text MUST equal the + `input_hash` as the recorded `MODEL_CALL` at that position, its correlated provider output MUST + name that call for new records, and its output text MUST equal the recorded `OUTPUT` text, and reported usage MUST equal the recorded `USAGE` (except in the legacy execution, `EXE-32`). Any mismatch is divergence (`ErrReplayDiverged`). Recovery checks served effects the same way, except that a `REQUIRES_MEMORY_SNAPSHOT` recovery at a decided approval @@ -779,13 +785,18 @@ concerns host-executed tools and applies to both classes. the live path for new effects only. The exception is a `REQUIRES_MEMORY_SNAPSHOT` execution whose latest gate is decided without a receipt: recovery serves from that gate (`APR-16`). - `EXE-22`: Model cut rule, outside legacy recovery (`EXE-30`): if the trailing effect is a - `MODEL_CALL` with no `OUTPUT` and the re-issued `input_hash` matches, recovery MUST invoke the - provider once and append the `OUTPUT` after the existing `MODEL_CALL`. A hash mismatch is + `MODEL_CALL` with no correlated `OUTPUT` and the re-issued `input_hash` matches, recovery MUST + invoke the provider once and append the `OUTPUT` after the existing `MODEL_CALL`, carrying that + call's ID. A hash mismatch is divergence: the provider is not called and no `OUTPUT` is appended (the failed run's `EVENT_ERROR`, `EXE-23`, still applies). A non-trailing `MODEL_CALL` without `OUTPUT` MUST NOT reach the provider: the re-issued call returns an error to the harness, which is not divergence. The execution fails only if the harness does not handle that error; over `Harness.Connect` it always fails (`EXE-33`). + A failed re-drive of a markerless pre-v11 call MUST NOT be followed immediately by direct output: + later replay would interpret that ID-less output as the old call's positional completion. The + reference host returns sticky divergence before appending it. The harness MAY instead issue a new + model call, whose `BY_ID` marker makes its later result unambiguous. - `EXE-23`: Recovery that fails after the harness has started running appends a best-effort `EVENT_ERROR`; recovery that succeeds appends `EVENT_END`. Failures raised before the harness runs (a chain mismatch `CHAIN-12`, invalid log, incomplete invocation `EXE-24`, harness identity @@ -2466,6 +2477,13 @@ The reference implementation protects the integrity of the record, not access to back up the database and WAL before the first version 10 open. An older binary refuses a version 10 journal at Open, but one that already has it open is not stopped by the stamp. There is no downgrade; restore the backup to roll back. + - Version 11 changes no table and rewrites no event. Its stamp marks a journal whose new + `MODEL_CALL` records may carry `result_correlation = BY_ID` and whose provider-result `OUTPUT` + records may carry `model_call_id`. Existing calls and outputs retain positional behavior and + unchanged hashes. Stop every older host and embedded client sharing the journal before the first + version 11 open, and back up the database and WAL. An older binary refuses v11 on open; one that + already has the journal open drops the new hash-bound fields and fails verification on a session + that carries them. There is no downgrade; restore the backup to roll back. - Version 9 extends `approval_executions` with an execution outcome and rebuilds the shared execution/approval projection from the journal. Events, canonical bytes, hashes and fences do not change. An undecodable session reports RUNNING without an approval reference; SQL diff --git a/sqlitelog/cleanup_resources_test.go b/sqlitelog/cleanup_resources_test.go index 31d6fec6..5a0aae2d 100644 --- a/sqlitelog/cleanup_resources_test.go +++ b/sqlitelog/cleanup_resources_test.go @@ -48,9 +48,9 @@ func owned(t *testing.T, resources ...api.CleanupResource) api.Incarnation { return api.Incarnation{ID: "child", Cleanup: evidence} } -// A journal written by the v0.4.0 release migrates to v10 with its legacy attempt intact and its -// inventory still uncertified. -func TestCleanupV9FixtureMigratesToV10(t *testing.T) { +// A journal written by the v0.4.0 release migrates through v10 to the current schema with its legacy +// attempt intact and its inventory still uncertified. +func TestCleanupV9FixtureMigratesToCurrent(t *testing.T) { path := filepath.Join(t.TempDir(), "cleanup-v9.db") blob, err := os.ReadFile("testdata/cleanup-v9.db") if err != nil { @@ -71,8 +71,8 @@ func TestCleanupV9FixtureMigratesToV10(t *testing.T) { raw.Close() s := deletionStore(t, path) - if err := s.db.QueryRow(`PRAGMA user_version`).Scan(&version); err != nil || version != 10 { - t.Fatalf("migrated user_version=%d err=%v, want 10", version, err) + if err := s.db.QueryRow(`PRAGMA user_version`).Scan(&version); err != nil || version != SchemaVersion { + t.Fatalf("migrated user_version=%d err=%v, want %d", version, err, SchemaVersion) } allocations, err := s.Allocations(t.Context(), "v9-session") if err != nil || len(allocations) != 1 || allocations[0].ResourceID != "v9-handle" || !allocations[0].Confirmed { diff --git a/sqlitelog/model_correlation_schema_test.go b/sqlitelog/model_correlation_schema_test.go new file mode 100644 index 00000000..48e38165 --- /dev/null +++ b/sqlitelog/model_correlation_schema_test.go @@ -0,0 +1,60 @@ +package sqlitelog_test + +import ( + "database/sql" + "path/filepath" + "reflect" + "testing" + + "github.com/agent-primitives/sessions/api" + "github.com/agent-primitives/sessions/sqlitelog" +) + +func TestV10ToV11MigrationIsStampOnly(t *testing.T) { + path := filepath.Join(t.TempDir(), "v10.db") + s := mustOpen(t, path) + log := s.Session("legacy") + fence, err := log.NewFence() + if err != nil { + t.Fatal(err) + } + if _, err := log.Append(0, fence, api.Event{ExecutionID: "e", Kind: api.EventModelCall, + ModelCall: &api.ModelCall{ID: "legacy", InputHash: "hash"}}); err != nil { + t.Fatal(err) + } + s.Close() + setUserVersion(t, path, 10) + raw, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + beforeSchema := queryValues(t, raw, `SELECT * FROM sqlite_schema ORDER BY name`) + beforeEvents := queryValues(t, raw, `SELECT * FROM events ORDER BY session,seq`) + raw.Close() + + s, err = sqlitelog.Open(path) + if err != nil { + t.Fatal(err) + } + s.Close() + raw, err = sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + defer raw.Close() + if got := readUserVersion(t, path); got != sqlitelog.SchemaVersion { + t.Fatalf("user_version=%d, want %d", got, sqlitelog.SchemaVersion) + } + if after := queryValues(t, raw, `SELECT * FROM sqlite_schema ORDER BY name`); !reflect.DeepEqual(after, beforeSchema) { + t.Fatalf("stamp-only migration changed schema:\nbefore=%v\nafter=%v", beforeSchema, after) + } + if after := queryValues(t, raw, `SELECT * FROM events ORDER BY session,seq`); !reflect.DeepEqual(after, beforeEvents) { + t.Fatalf("stamp-only migration changed events:\nbefore=%v\nafter=%v", beforeEvents, after) + } +} + +func TestJournalStampIsNewerThanVersion10(t *testing.T) { + if sqlitelog.SchemaVersion <= 10 { + t.Fatalf("schema version=%d; a v10 build would open ID-correlated model results", sqlitelog.SchemaVersion) + } +} diff --git a/sqlitelog/sqlitelog.go b/sqlitelog/sqlitelog.go index 7e222789..94052980 100644 --- a/sqlitelog/sqlitelog.go +++ b/sqlitelog/sqlitelog.go @@ -90,8 +90,9 @@ CREATE INDEX IF NOT EXISTS sessions_project_created // version 6 records explicit session model-policy eligibility; version 7 adds the allocation // ledger and inventory completeness/evidence columns; version 8 marks a journal whose // APPROVAL_RESULT records may carry a verified approver; version 9 adds execution outcomes; -// version 10 records immutable backend resource identity for cleanup attempts. -const SchemaVersion = 10 +// version 10 records immutable backend resource identity for cleanup attempts; version 11 marks a +// journal whose MODEL_CALL and provider-result OUTPUT records may carry ID-correlation fields. +const SchemaVersion = 11 // migrations[i] moves a database from version i+1 to i+2, inside the migration transaction. The // array length is tied to SchemaVersion, so bumping one without the other does not compile. @@ -105,6 +106,7 @@ var migrations = [SchemaVersion - 1]func(*sql.Tx) error{ migrateV7ToV8, migrateV8ToV9, migrateCleanupIdentity, + migrateV10ToV11, } // migrateV7ToV8 changes no table and rewrites no event. The stamp alone is the change: this build @@ -114,6 +116,10 @@ var migrations = [SchemaVersion - 1]func(*sql.Tx) error{ // they were. func migrateV7ToV8(*sql.Tx) error { return nil } +// migrateV10ToV11 changes no table and rewrites no event. The stamp prevents an older build from +// opening a journal whose model correlation fields it would drop before hash verification. +func migrateV10ToV11(*sql.Tx) error { return nil } + // migrateV5ToV6 leaves every existing session on legacy model semantics, including empty logs. func migrateV5ToV6(tx *sql.Tx) error { _, err := tx.Exec(`ALTER TABLE sessions ADD COLUMN model_policy INTEGER NOT NULL DEFAULT 0`) diff --git a/wire/convert.go b/wire/convert.go index 1600cd00..8e864c7e 100644 --- a/wire/convert.go +++ b/wire/convert.go @@ -33,6 +33,7 @@ func EventToProto(e api.Event) *v1.Event { SchemaVersion: e.SchemaVersion, Kind: kindToProto(e.Kind), Actor: identityToProto(e.Actor), + ModelCallId: e.ModelCallID, } if !e.Timestamp.IsZero() { out.Ts = timestamppb.New(e.Timestamp) @@ -82,6 +83,10 @@ func EventFromProto(p *v1.Event) api.Event { Kind: kindFromProto(p.GetKind()), Actor: identityFromProto(p.GetActor()), } + if p.ModelCallId != nil { + id := p.GetModelCallId() + out.ModelCallID = &id + } if p.GetTs() != nil { out.Timestamp = p.GetTs().AsTime() } @@ -340,14 +345,20 @@ func modelCallToProto(m *api.ModelCall) *v1.ModelCall { if m == nil { return nil } - return &v1.ModelCall{Model: m.Model, Params: m.Params, InputHash: m.InputHash, Id: m.ID} + return &v1.ModelCall{ + Model: m.Model, Params: m.Params, InputHash: m.InputHash, Id: m.ID, + ResultCorrelation: v1.ModelCall_ResultCorrelation(m.ResultCorrelation), + } } func modelCallFromProto(m *v1.ModelCall) *api.ModelCall { if m == nil { return nil } - return &api.ModelCall{Model: m.GetModel(), Params: m.GetParams(), InputHash: m.GetInputHash(), ID: m.GetId()} + return &api.ModelCall{ + Model: m.GetModel(), Params: m.GetParams(), InputHash: m.GetInputHash(), ID: m.GetId(), + ResultCorrelation: api.ModelResultCorrelation(m.GetResultCorrelation()), + } } func toolCallToProto(t *api.ToolCall) *v1.ToolCall { diff --git a/wire/convert_test.go b/wire/convert_test.go index acddb316..ee2149db 100644 --- a/wire/convert_test.go +++ b/wire/convert_test.go @@ -130,6 +130,12 @@ func TestEventRoundTrip(t *testing.T) { ExecutionID: "e1", SchemaVersion: 1, Timestamp: ts, Kind: api.EventOutput, Message: richMessage(), Actor: actor, }, + "output_model_result": { + ExecutionID: "e1", Kind: api.EventOutput, Message: richMessage(), ModelCallID: proto.String("mc-1"), + }, + "output_model_result_empty": { + ExecutionID: "e1", Kind: api.EventOutput, Message: richMessage(), ModelCallID: proto.String(""), + }, "output_tool_calls": { ExecutionID: "e1", SchemaVersion: 1, Timestamp: ts, Kind: api.EventOutput, Message: toolCallMessage(), Actor: actor, @@ -142,7 +148,7 @@ func TestEventRoundTrip(t *testing.T) { Kind: api.EventModelCall, ModelCall: &api.ModelCall{ Model: "azure-openai/gpt-x", Params: map[string]string{"temperature": "0"}, - InputHash: "sha256:dd", ID: "mc-1", + InputHash: "sha256:dd", ID: "mc-1", ResultCorrelation: api.ModelResultCorrelationByID, }, }, "tool_call": { @@ -215,8 +221,8 @@ func TestHashStableAcrossWire(t *testing.T) { {Kind: api.EventExecutionStart, ExecutionStart: &api.ExecutionStart{InputCount: proto.Int64(0)}}, {Kind: api.EventExecutionStart, ExecutionStart: &api.ExecutionStart{}}, {Kind: api.EventInput, Message: api.TextMessage("user", "drive")}, - {Kind: api.EventModelCall, ModelCall: &api.ModelCall{Model: "m", Params: map[string]string{"a": "b"}, InputHash: "h", ID: "c1"}}, - {Kind: api.EventOutput, Message: richMessage()}, + {Kind: api.EventModelCall, ModelCall: &api.ModelCall{Model: "m", Params: map[string]string{"a": "b"}, InputHash: "h", ID: "c1", ResultCorrelation: api.ModelResultCorrelationByID}}, + {Kind: api.EventOutput, Message: richMessage(), ModelCallID: proto.String("c1")}, {Kind: api.EventOutput, Message: toolCallMessage()}, {Kind: api.EventInput, Message: toolResultMessage()}, {Kind: api.EventToolResult, Result: toolResultMessage().Parts[0].ToolResult}, From f923d185cddcdd7888da9b45b85acb1bd1731625 Mon Sep 17 00:00:00 2001 From: Tatsat Mishra Date: Mon, 30 Nov 2026 07:22:09 +1300 Subject: [PATCH 2/3] fix(controller): refuse ambiguous legacy fallback --- .../model-result-correlation-compat.md | 5 +- .../unreleased/model-result-correlation.md | 4 +- controller/resume.go | 3 + controller/v012_journal_test.go | 29 ++++++++++ docs/harness-authoring.md | 56 +++++++++---------- spec.md | 38 +++++++------ 6 files changed, 86 insertions(+), 49 deletions(-) diff --git a/changelog/unreleased/model-result-correlation-compat.md b/changelog/unreleased/model-result-correlation-compat.md index 2ff65563..74f95d4b 100644 --- a/changelog/unreleased/model-result-correlation-compat.md +++ b/changelog/unreleased/model-result-correlation-compat.md @@ -5,5 +5,6 @@ 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 a failed re-drive of an old positional call, immediate - direct fallback output is refused as ambiguous; a fresh model-call retry remains supported. + 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. diff --git a/changelog/unreleased/model-result-correlation.md b/changelog/unreleased/model-result-correlation.md index f68d30cd..6781dd9f 100644 --- a/changelog/unreleased/model-result-correlation.md +++ b/changelog/unreleased/model-result-correlation.md @@ -2,5 +2,5 @@ category: Fixed --- -- Provider-result `OUTPUT` records name the durable `MODEL_CALL` they answer. Replay and recovery no - longer reinterpret direct fallback output after a handled provider error as model success. +- 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. diff --git a/controller/resume.go b/controller/resume.go index d12f68dd..66fa16fd 100644 --- a/controller/resume.go +++ b/controller/resume.go @@ -346,6 +346,9 @@ func (s *resumeSink) Model(ctx context.Context, req api.ModelRequest) (api.Model if s.live.legacyRecovery { // A v0.1.2 ID-less journal keeps the contract of rejecting a missing completion // without calling the model; only journals with execution IDs are re-driven. + if mc.ModelCall.ResultCorrelation == api.ModelResultCorrelationUnspecified { + s.ambiguousLegacyFailure = true + } return api.ModelResponse{}, errors.New("resume: recorded completion missing") } if mc.ModelCall == nil || mc.ModelCall.ID == "" { diff --git a/controller/v012_journal_test.go b/controller/v012_journal_test.go index 2c65270e..cecfce10 100644 --- a/controller/v012_journal_test.go +++ b/controller/v012_journal_test.go @@ -438,6 +438,35 @@ func TestV012ReplayUnfinishedLogAndMissingModelCompletion(t *testing.T) { } } +func TestV012MissingModelCompletionRefusesFallbackOutput(t *testing.T) { + log, original := v012Log(t, "crashed-model") + c, err := v012Controller(log, func(context.Context, api.ModelRequest) (api.ModelResponse, error) { + t.Fatal("legacy recovery invoked model") + return api.ModelResponse{}, nil + }) + if err != nil { + t.Fatal(err) + } + resumed, err := c.Resume(t.Context(), fallbackHarness{}) + if !resumed || !errors.Is(err, controller.ErrReplayDiverged) || !strings.Contains(err.Error(), "ambiguous") { + t.Fatalf("fallback Resume = %v, %v; want ambiguous divergence", resumed, err) + } + if c.ModelInvocations() != 0 { + t.Fatal("missing completion recovery repeated model") + } + after, err := log.Read(1) + if err != nil { + t.Fatal(err) + } + if len(after) != len(original)+1 || !reflect.DeepEqual(after[:len(original)], original) || + after[len(original)].Event.Kind != api.EventError { + t.Fatalf("fallback recovery journaled output: %#v", after) + } + if err := log.Verify(); err != nil { + t.Fatal(err) + } +} + func TestV012CommittedUpgradeFixtures(t *testing.T) { for _, name := range []string{"upgraded-resume", "mixed-completed", "mixed-interrupted"} { t.Run(name, func(t *testing.T) { diff --git a/docs/harness-authoring.md b/docs/harness-authoring.md index 379a8314..e86d0059 100644 --- a/docs/harness-authoring.md +++ b/docs/harness-authoring.md @@ -277,34 +277,34 @@ diverge or re-spend the call. This single rule is why replay never invokes the m that calls its provider anyway is unmediated, whether or not it means to be, and loses that guarantee. -The host records `MODEL_CALL` (with the request's input hash, call ID and ID-correlation mode) before -it invokes the provider, and records the completion as `OUTPUT` naming that call. Output your harness -emits directly carries no model-call ID, so a handled provider error followed by fallback output is -not replayed as provider success. A process death or provider error between intent and completion -leaves a turn whose last effect is a `MODEL_CALL` with no correlated completion. On `Resume`, when -your harness re-issues that request, -the host serves everything recorded before it, checks the re-issued request's input hash against the -recorded one, then invokes the provider live and records the completion after that same `MODEL_CALL`. It -never records a second `MODEL_CALL` or a second `OUTPUT` for it. This applies to journals with -execution IDs; a v0.1.2 journal without them is not re-driven, and `Resume` fails with "recorded -completion missing" without calling the provider. A different input hash fails as -divergence (I0) without calling the provider. The cost: whether the original provider call ran is -unknown, so a cut during a model call costs at most one extra provider call. That bound holds within -one host, where the placement layer's per-session guard serializes `Exec`, `Suspend` and `Resume`; it -does not hold across hosts that share a journal, where overlapping `Resume`s are not serialized by -that guard. A fork whose fork point is a `MODEL_CALL` copies the call without any completion the -parent recorded later, so `Resume` on the child re-calls the provider once: each such fork costs one -provider call. - -If the recovering call fails and your harness returns the error, that `MODEL_CALL` is still the turn's -last effect and the next `Resume` re-drives it again. Do not retry a failed `sink.Model` call inside -the run. Over the harness wire a `sink.Model` error ends the bridge, so a remote harness never sees it -and cannot retry. After upgrading a markerless pre-v11 call, direct fallback output immediately after -a failed re-drive is refused because it would be positionally ambiguous; issue a fresh model call or -return the error. An in-process harness that retries only some errors can leave `MODEL_CALL`, `ERROR`, -`MODEL_CALL`, `OUTPUT`, `END`, which `Replay` rejects when the harness does not reproduce the same -retry. A harness that retries every error replays that journal, but returning the error and letting -`Resume` re-drive the call is the supported path. +The host records `MODEL_CALL` (with the request's input hash, call ID and ID-correlation mode) +before it invokes the provider, and records the completion as `OUTPUT` naming that call. Output your +harness emits directly carries no model-call ID, so a handled provider error followed by fallback +output is not replayed as provider success. A process death or provider error between intent and +completion leaves a turn whose last effect is a `MODEL_CALL` with no correlated completion. On +`Resume`, when your harness re-issues that request, the host serves everything recorded before it, +checks the re-issued request's input hash against the recorded one, then invokes the provider live +and records the completion after that same `MODEL_CALL`. It never records a second `MODEL_CALL` or +a second `OUTPUT` for it. This applies to journals with execution IDs; a v0.1.2 journal without them +is not re-driven, and `Resume` fails with "recorded completion missing" without calling the +provider. A different input hash fails as divergence (I0) without calling the provider. The cost: +whether the original provider call ran is unknown, so a cut during a model call costs at most one +extra provider call. That bound holds within one host, where the placement layer's per-session guard +serializes `Exec`, `Suspend` and `Resume`; it does not hold across hosts that share a journal, where +overlapping `Resume`s are not serialized by that guard. A fork whose fork point is a `MODEL_CALL` +copies the call without any completion the parent recorded later, so `Resume` on the child re-calls +the provider once: each such fork costs one provider call. + +If the recovering call fails and your harness returns the error, that `MODEL_CALL` is still the +turn's last effect and the next `Resume` re-drives it again. Do not retry a failed `sink.Model` call +inside the run. Over the harness wire a `sink.Model` error ends the bridge, so a remote harness +never sees it and cannot retry. After upgrading a markerless pre-v11 call, direct fallback output is +refused when legacy recovery rejects the call or a modern recovery's re-drive fails, because the +output would be positionally ambiguous; issue a fresh model call or return the error. An in-process +harness that retries only some errors can leave `MODEL_CALL`, `ERROR`, `MODEL_CALL`, `OUTPUT`, +`END`, which `Replay` rejects when the harness does not reproduce the same retry. A harness that +retries every error replays that journal, but returning the error and letting `Resume` re-drive the +call is the supported path. In journals with execution IDs, `ERROR` events written by failed turns and failed `Resume` attempts stay in the journal as an audit trail; they are not effects, so they are skipped on replay and do not diff --git a/spec.md b/spec.md index c0c32150..1b9280bb 100644 --- a/spec.md +++ b/spec.md @@ -740,11 +740,11 @@ concerns host-executed tools and applies to both classes. - `I0`: On reconstruction replay, each model call the harness re-issues MUST have the same `input_hash` as the recorded `MODEL_CALL` at that position, its correlated provider output MUST - name that call for new records, and its output text MUST equal the - recorded `OUTPUT` text, and reported usage MUST equal the recorded `USAGE` (except in the legacy - execution, `EXE-32`). Any mismatch is divergence (`ErrReplayDiverged`). Recovery checks served - effects the same way, except that a `REQUIRES_MEMORY_SNAPSHOT` recovery at a decided approval - gate starts serving at the gate and does not check the prefix before it (`APR-16`). + name that call for new records, its output text MUST equal the recorded `OUTPUT` text, and + reported usage MUST equal the recorded `USAGE` (except in the legacy execution, `EXE-32`). Any + mismatch is divergence (`ErrReplayDiverged`). Recovery checks served effects the same way, except + that a `REQUIRES_MEMORY_SNAPSHOT` recovery at a decided approval gate starts serving at the gate + and does not check the prefix before it (`APR-16`). - `I1`: Reconstruction replay MUST NOT invoke the model provider or the tool executor. Recorded completions and receipts are served from the log. - `I3`: A host-executed tool intent recorded without a receipt is re-driven on recovery under the @@ -787,16 +787,17 @@ concerns host-executed tools and applies to both classes. - `EXE-22`: Model cut rule, outside legacy recovery (`EXE-30`): if the trailing effect is a `MODEL_CALL` with no correlated `OUTPUT` and the re-issued `input_hash` matches, recovery MUST invoke the provider once and append the `OUTPUT` after the existing `MODEL_CALL`, carrying that - call's ID. A hash mismatch is - divergence: the provider is not called and no `OUTPUT` is appended (the failed run's - `EVENT_ERROR`, `EXE-23`, still applies). A non-trailing `MODEL_CALL` without `OUTPUT` MUST NOT - reach the provider: the re-issued call returns an error to the harness, which is not - divergence. The execution fails only if the harness does not handle that error; over + call's ID. A hash mismatch is divergence: the provider is not called and no `OUTPUT` is appended + (the failed run's `EVENT_ERROR`, `EXE-23`, still applies). A non-trailing `MODEL_CALL` without + `OUTPUT` MUST NOT reach the provider: the re-issued call returns an error to the harness, which is + not divergence. The execution fails only if the harness does not handle that error; over `Harness.Connect` it always fails (`EXE-33`). - A failed re-drive of a markerless pre-v11 call MUST NOT be followed immediately by direct output: - later replay would interpret that ID-less output as the old call's positional completion. The - reference host returns sticky divergence before appending it. The harness MAY instead issue a new - model call, whose `BY_ID` marker makes its later result unambiguous. + When recovery returns an error for a markerless pre-v11 call without a completion, whether because + legacy recovery refuses its re-drive (`EXE-30`) or a modern recovery's re-drive fails, the call + MUST NOT be followed immediately by direct output: later replay would interpret that ID-less + output as the old call's positional completion. The reference host returns sticky divergence + before appending it. The harness MAY instead issue a new model call, whose `BY_ID` marker makes + its later result unambiguous. - `EXE-23`: Recovery that fails after the harness has started running appends a best-effort `EVENT_ERROR`; recovery that succeeds appends `EVENT_END`. Failures raised before the harness runs (a chain mismatch `CHAIN-12`, invalid log, incomplete invocation `EXE-24`, harness identity @@ -857,9 +858,12 @@ invokes no harness and stays a no-op without one. call is accepted without comparison while recorded effects remain and journaled after they are exhausted. - A trailing `MODEL_CALL` without `OUTPUT` is not re-driven (`EXE-22` does not apply): the - re-issued call returns an error to the harness and the provider is not called. If the run - then fails (over `Harness.Connect` it always does, `EXE-33`), its `ERROR` completes the - legacy execution (`EXE-29`). + re-issued call returns an error to the harness and the provider is not called. If the harness + handles that error, direct output immediately afterwards MUST be refused as sticky divergence + before append because replay would interpret it as the old call's positional completion. The + harness MAY instead issue a fresh model call, whose `BY_ID` marker makes a later result + unambiguous. If the run fails (over `Harness.Connect` it always does, `EXE-33`), its `ERROR` + completes the legacy execution (`EXE-29`). - A `REQUIRES_APPROVAL` tool call that passes `APR-1` is refused (`ErrInvalidApprovalCall`) before any append; `APR-2` does not apply. - Records it appends carry no `execution_id` (`EXE-4`). From 5f07f2b66b416da18648ba65823f12d189e1e89d Mon Sep 17 00:00:00 2001 From: Tatsat Mishra Date: Mon, 30 Nov 2026 09:17:31 +1300 Subject: [PATCH 3/3] test(controller): cover markerless result replay --- controller/resume_model_cut_test.go | 110 ++++++++++++++++++++++++++++ spec.md | 10 ++- 2 files changed, 116 insertions(+), 4 deletions(-) diff --git a/controller/resume_model_cut_test.go b/controller/resume_model_cut_test.go index 1f01ef4f..6181196a 100644 --- a/controller/resume_model_cut_test.go +++ b/controller/resume_model_cut_test.go @@ -539,6 +539,116 @@ func TestLegacyPositionalModelResultStillReplays(t *testing.T) { } } +func TestMarkerlessModelCallRedrivePreservesIDAndPrefix(t *testing.T) { + source := memStore(t) + execCutAtModelCall(t, source, true) + records, err := source.Read(1) + if err != nil { + t.Fatal(err) + } + records[2].Event.ModelCall.ResultCorrelation = api.ModelResultCorrelationUnspecified + + log := memStore(t) + fence, err := log.NewFence() + if err != nil { + t.Fatal(err) + } + for i, record := range records { + if _, err := log.Append(int64(i), fence, record.Event); err != nil { + t.Fatal(err) + } + } + prefix, err := log.Read(1) + if err != nil { + t.Fatal(err) + } + callID := prefix[2].Event.ModelCall.ID + if callID == "" { + t.Fatal("markerless model call has no ID") + } + + model := &scriptedModel{} + if err := resumeOnce(t, log, &echoHarness{}, model); err != nil { + t.Fatalf("Resume = %v", err) + } + if model.calls != 1 { + t.Fatalf("Resume invoked the provider %d times, want 1", model.calls) + } + upgraded, err := log.Read(1) + if err != nil { + t.Fatal(err) + } + if len(upgraded) != len(prefix)+2 || !reflect.DeepEqual(upgraded[:len(prefix)], prefix) { + t.Fatalf("Resume changed the markerless journal prefix: before=%+v after=%+v", prefix, upgraded) + } + result := upgraded[len(prefix)].Event + if result.Kind != api.EventOutput || result.ModelCallID == nil || *result.ModelCallID != callID { + t.Fatalf("re-driven result ID = %v, want original call ID %q", result.ModelCallID, callID) + } + if err := log.Verify(); err != nil { + t.Fatalf("Verify = %v", err) + } + + replayModel := &scriptedModel{} + streamCalls := 0 + replay, err := controller.New(log, replayModel.call, controller.WithStreamingModel( + func(context.Context, api.ModelRequest, func(string)) (api.ModelResponse, error) { + streamCalls++ + return api.ModelResponse{}, errProvider + }, + )) + if err != nil { + t.Fatal(err) + } + out, err := replay.Replay(t.Context(), &echoHarness{}) + if err != nil || !reflect.DeepEqual(out, []string{"echo:hi"}) || replayModel.calls != 0 || streamCalls != 0 { + t.Fatalf("Replay = outputs %v err %v provider=%d stream=%d, want [echo:hi], nil, 0, 0", + out, err, replayModel.calls, streamCalls) + } + + for _, tc := range []struct { + name string + id string + }{ + {name: "empty result ID"}, + {name: "wrong result ID", id: "other"}, + } { + t.Run(tc.name, func(t *testing.T) { + malformed := memStore(t) + fence, err := malformed.NewFence() + if err != nil { + t.Fatal(err) + } + for i, record := range upgraded { + event := record.Event + if i == len(prefix) { + event.ModelCallID = stringPointer(tc.id) + } + if _, err := malformed.Append(int64(i), fence, event); err != nil { + t.Fatal(err) + } + } + if err := malformed.Verify(); err != nil { + t.Fatalf("Verify = %v", err) + } + model := &scriptedModel{} + streamCalls := 0 + replay, err := controller.New(malformed, model.call, controller.WithStreamingModel( + func(context.Context, api.ModelRequest, func(string)) (api.ModelResponse, error) { + streamCalls++ + return api.ModelResponse{}, errProvider + }, + )) + if err != nil { + t.Fatal(err) + } + if _, err := replay.Replay(t.Context(), &echoHarness{}); !errors.Is(err, controller.ErrReplayDiverged) || model.calls != 0 || streamCalls != 0 { + t.Fatalf("Replay = %v provider=%d stream=%d, want divergence without provider", err, model.calls, streamCalls) + } + }) + } +} + func TestFailedLegacyRedriveRefusesImmediateFallback(t *testing.T) { log := memStore(t) execCutAtModelCall(t, log, true) diff --git a/spec.md b/spec.md index 1b9280bb..7b0dae0b 100644 --- a/spec.md +++ b/spec.md @@ -713,8 +713,9 @@ other operations but never sees those calls. (`CHAIN-1`) so a journal written by one host implementation can be replayed by another? - `EXE-34`: For an invocation with a nonempty `ExecutionStart.model`, an empty `ModelRequest.model` MUST resolve to that recorded default before hashing, journaling and provider - dispatch; a nonempty ID is a per-call override. Each live request, including a trailing intent - re-driven by Resume, MUST belong to the current configured host allowlist before provider IO. + dispatch; a nonempty model ID is a per-call override. Each live request, including a trailing + intent re-driven by Resume, MUST belong to the current configured host allowlist before provider + IO. A rejection MUST be execution-fatal even if the harness catches it: no provider call, no new `MODEL_CALL` appended, no later harness effects, best-effort `ERROR` and no `END`. An existing trailing `MODEL_CALL` intent remains recorded. The reference Sessions API reports @@ -726,8 +727,9 @@ other operations but never sees those calls. New live effects of a policy-aware invocation face the current policy, if configured. Removing policy removes membership checks, not the invocation's recorded default. Invocations with an empty recorded default, including markerless journals, retain their old model behavior without - default resolution or membership checks. Per-call IDs remain in `ModelCall.id`; new calls also - declare their result-correlation mode (`EXE-10`). + default resolution or membership checks. Per-call model IDs remain in `ModelCall.model`; their + format is unchanged. New calls use `ModelCall.id` for the independently generated call-correlation + token and also declare their result-correlation mode (`EXE-10`). - `EXE-12`: Model streaming deltas (`ExecUpdate.delta`) MUST NOT be journaled. Exactly one `EVENT_OUTPUT` records each finalized completion. Text a harness passes to `Output` is not a delta: each call is journaled as its own `EVENT_OUTPUT`.