package openai

import (
	"encoding/json"
	"errors"
	"fmt"
	"sync"
	"testing"
	"time"

	"iop/packages/go/config"
)

func TestLogicalRequestContinuationMatrix(t *testing.T) {
	coordinator := newLogicalRequestCoordinator(logicalRequestCoordinatorOptions{
		IDSource: sequentialLogicalRequestIDs("matrix"),
	})
	lineage := mustChatLogicalRequestLineage(t, "unchanged", "tool-a")
	request, err := coordinator.create(logicalRequestAdmission{
		OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: lineage, PresetGeneration: "preset-gen-1",
	})
	if err != nil {
		t.Fatalf("create: %v", err)
	}
	stageID, err := coordinator.newStageID()
	if err != nil {
		t.Fatalf("new stage id: %v", err)
	}
	if _, err := coordinator.activateStage(request.ID, "edge-a", stageID); err != nil {
		t.Fatalf("activate stage: %v", err)
	}
	const issuedHash = "matrix_issued_hash_123"
	if _, err := coordinator.awaitToolResults(request.ID, "edge-a", stageID, []logicalRequestExpectedTool{
		{PublicCallID: "call_one", ProviderCallID: "provider_one"},
		{PublicCallID: "call_two", ProviderCallID: "provider_two"},
	}, issuedHash); err != nil {
		t.Fatalf("await tool results: %v", err)
	}

	assertUnchanged := func(name string, want error, continuation logicalRequestContinuation) {
		t.Helper()
		if _, err := coordinator.consumeContinuation(continuation); !errors.Is(err, want) {
			t.Fatalf("%s error = %v, want %v", name, err, want)
		}
		snapshot, err := coordinator.snapshot(request.ID)
		if err != nil {
			t.Fatalf("%s snapshot: %v", name, err)
		}
		if snapshot.State != logicalRequestStateWaiting || len(snapshot.ExpectedCallIDs) != 2 || snapshot.ActiveStageID != stageID {
			t.Fatalf("%s mutated request state: %+v", name, snapshot)
		}
	}

	committedLineage := logicalRequestLineage{
		Endpoint:      lineage.Endpoint,
		HistoryDigest: "matrix_committed_history_digest",
		ToolsetDigest: lineage.ToolsetDigest,
	}
	baseLineage := logicalRequestContinuationLineage{
		Prefix:         lineage,
		IssuedCallHash: issuedHash,
		ResultIDs:      []string{"call_one", "call_two"},
		Committed:      committedLineage,
	}
	base := logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: baseLineage,
		Results: []logicalRequestToolResult{{PublicCallID: "call_one"}, {PublicCallID: "call_two"}},
	}
	assertUnchanged("cross owner", errLogicalRequestOwnerMismatch, logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: "edge-b", PrincipalRef: base.PrincipalRef, Lineage: base.Lineage, Results: base.Results,
	})
	assertUnchanged("cross principal", errLogicalRequestPrincipal, logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: base.OwnerEdgeID, PrincipalRef: "principal-b", Lineage: base.Lineage, Results: base.Results,
	})
	assertUnchanged("mutated history", errLogicalRequestLineage, logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: base.OwnerEdgeID, PrincipalRef: base.PrincipalRef,
		Lineage: logicalRequestContinuationLineage{
			Prefix:         mustChatLogicalRequestLineage(t, "mutated", "tool-a"),
			IssuedCallHash: issuedHash,
			ResultIDs:      base.Lineage.ResultIDs,
			Committed:      committedLineage,
		}, Results: base.Results,
	})
	assertUnchanged("mutated toolset", errLogicalRequestLineage, logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: base.OwnerEdgeID, PrincipalRef: base.PrincipalRef,
		Lineage: logicalRequestContinuationLineage{
			Prefix:         mustChatLogicalRequestLineage(t, "unchanged", "tool-b"),
			IssuedCallHash: issuedHash,
			ResultIDs:      base.Lineage.ResultIDs,
			Committed:      committedLineage,
		}, Results: base.Results,
	})
	assertUnchanged("missing result", errLogicalRequestFrontier, logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: base.OwnerEdgeID, PrincipalRef: base.PrincipalRef, Lineage: base.Lineage,
		Results: []logicalRequestToolResult{{PublicCallID: "call_one"}},
	})
	assertUnchanged("unknown result", errLogicalRequestFrontier, logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: base.OwnerEdgeID, PrincipalRef: base.PrincipalRef, Lineage: base.Lineage,
		Results: []logicalRequestToolResult{{PublicCallID: "call_one"}, {PublicCallID: "call_unknown"}},
	})
	assertUnchanged("duplicate result", errLogicalRequestFrontier, logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: base.OwnerEdgeID, PrincipalRef: base.PrincipalRef, Lineage: base.Lineage,
		Results: []logicalRequestToolResult{{PublicCallID: "call_one"}, {PublicCallID: "call_one"}},
	})

	resumed, err := coordinator.consumeContinuation(logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: baseLineage,
		Results: []logicalRequestToolResult{{PublicCallID: "call_two"}, {PublicCallID: "call_one"}},
	})
	if err != nil {
		t.Fatalf("ordered-independent consume: %v", err)
	}
	if resumed.State != logicalRequestStateResumed || resumed.ActiveStageID != "" || len(resumed.ExpectedCallIDs) != 0 {
		t.Fatalf("resumed snapshot: %+v", resumed)
	}
	if public, err := coordinator.publicToolID(request.ID, "provider_one"); err != nil || public != "call_one" {
		t.Fatalf("provider mapping = %q, %v", public, err)
	}
	if _, err := coordinator.consumeContinuation(base); !errors.Is(err, errLogicalRequestNoFrontier) {
		t.Fatalf("duplicate consume error = %v, want %v", err, errLogicalRequestNoFrontier)
	}
	if _, err := coordinator.consumeContinuation(logicalRequestContinuation{RequestID: "req_missing", OwnerEdgeID: "edge-a"}); !errors.Is(err, errLogicalRequestNotFound) {
		t.Fatalf("missing state error = %v, want %v", err, errLogicalRequestNotFound)
	}
}

func TestLogicalRequestCoordinatorIsServerOwned(t *testing.T) {
	server := NewServer(config.EdgeOpenAIConf{}, nil, nil)
	if server.logicalRequests() == nil {
		t.Fatal("NewServer must install an Edge-local logical request coordinator")
	}
}

func TestLogicalRequestConcurrentFrontierExactlyOnce(t *testing.T) {
	coordinator := newLogicalRequestCoordinator(logicalRequestCoordinatorOptions{IDSource: sequentialLogicalRequestIDs("race")})
	lineage := mustChatLogicalRequestLineage(t, "history", "tool")
	request, err := coordinator.create(logicalRequestAdmission{OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: lineage, PresetGeneration: "preset-gen-1"})
	if err != nil {
		t.Fatalf("create: %v", err)
	}
	stageID, err := coordinator.newStageID()
	if err != nil {
		t.Fatalf("new stage: %v", err)
	}
	if _, err := coordinator.activateStage(request.ID, "edge-a", stageID); err != nil {
		t.Fatalf("activate: %v", err)
	}
	const issuedHash = "race_issued_hash_123"
	if _, err := coordinator.awaitToolResults(request.ID, "edge-a", stageID, []logicalRequestExpectedTool{{PublicCallID: "call_one", ProviderCallID: "provider_one"}}, issuedHash); err != nil {
		t.Fatalf("await: %v", err)
	}
	continuation := logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: "edge-a", PrincipalRef: "principal-a",
		Lineage: logicalRequestContinuationLineage{
			Prefix:         lineage,
			IssuedCallHash: issuedHash,
			ResultIDs:      []string{"call_one"},
			Committed:      logicalRequestLineage{Endpoint: lineage.Endpoint, HistoryDigest: "race_committed_digest", ToolsetDigest: lineage.ToolsetDigest},
		},
		Results: []logicalRequestToolResult{{PublicCallID: "call_one"}},
	}
	const callers = 32
	start := make(chan struct{})
	var wg sync.WaitGroup
	var mu sync.Mutex
	successes := 0
	failures := make([]error, 0, callers)
	for range callers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			<-start
			_, err := coordinator.consumeContinuation(continuation)
			mu.Lock()
			defer mu.Unlock()
			if err == nil {
				successes++
				return
			}
			failures = append(failures, err)
		}()
	}
	close(start)
	wg.Wait()
	if successes != 1 {
		t.Fatalf("successful frontier consumptions = %d, want 1 (failures=%v)", successes, failures)
	}
	for _, err := range failures {
		if !errors.Is(err, errLogicalRequestNoFrontier) {
			t.Fatalf("concurrent loser error = %v, want %v", err, errLogicalRequestNoFrontier)
		}
	}
}

func TestLogicalRequestIDCollisionRegenerates(t *testing.T) {
	ids := []string{"collision", "collision", "replacement"}
	var next int
	coordinator := newLogicalRequestCoordinator(logicalRequestCoordinatorOptions{
		IDSource: func() (string, error) {
			id := ids[next]
			next++
			return id, nil
		},
	})
	lineage := mustChatLogicalRequestLineage(t, "history", "tool")
	first, err := coordinator.create(logicalRequestAdmission{OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: lineage, PresetGeneration: "preset-gen-1"})
	if err != nil {
		t.Fatalf("first create: %v", err)
	}
	second, err := coordinator.create(logicalRequestAdmission{OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: lineage, PresetGeneration: "preset-gen-1"})
	if err != nil {
		t.Fatalf("second create: %v", err)
	}
	if first.ID != "req_collision" || second.ID != "req_replacement" {
		t.Fatalf("collision ids = %q, %q", first.ID, second.ID)
	}
}

func TestLogicalRequestLineageCanonicalizesToolJSON(t *testing.T) {
	left := mustChatLogicalRequestLineage(t, "history", map[string]any{"name": "tool", "parameters": map[string]any{"b": 2, "a": 1}})
	right := mustChatLogicalRequestLineage(t, "history", map[string]any{"parameters": map[string]any{"a": 1, "b": 2}, "name": "tool"})
	if left != right {
		t.Fatalf("equivalent tool schema lineages differ: %+v != %+v", left, right)
	}
}

func TestLogicalRequestLineageMutationMatrix(t *testing.T) {
	chatEquivalent := []byte(`{
        "tools": [{"function":{"parameters":{"maximum":9007199254740992,"type":"object"},"name":"artifact"},"type":"function"}],
        "messages": [{"content":[{"text":"preserved","type":"text"}],"role":"user"}],
        "model":"preset-model"
    }`)
	chatBase := mustRawLogicalRequestLineage(t, newChatRequestLineage, chatEquivalent)
	chatReordered := mustRawLogicalRequestLineage(t, newChatRequestLineage, []byte(`{"model":"preset-model","messages":[{"role":"user","content":[{"type":"text","text":"preserved"}]}],"tools":[{"type":"function","function":{"name":"artifact","parameters":{"type":"object","maximum":9007199254740992}}}]}`))
	if chatBase != chatReordered {
		t.Fatalf("equivalent Chat lineage differs: %+v != %+v", chatBase, chatReordered)
	}
	for name, raw := range map[string][]byte{
		"large schema integer": []byte(`{"model":"preset-model","messages":[{"role":"user","content":[{"type":"text","text":"preserved"}]}],"tools":[{"type":"function","function":{"name":"artifact","parameters":{"type":"object","maximum":9007199254740993}}}]}`),
		"structured content":   []byte(`{"model":"preset-model","messages":[{"role":"user","content":[{"type":"text","text":"mutated"}]}],"tools":[{"type":"function","function":{"name":"artifact","parameters":{"type":"object","maximum":9007199254740992}}}]}`),
	} {
		t.Run("chat "+name, func(t *testing.T) {
			if got := mustRawLogicalRequestLineage(t, newChatRequestLineage, raw); got == chatBase {
				t.Fatalf("Chat %s mutation retained the same lineage", name)
			}
		})
	}

	anthropicBase := mustRawLogicalRequestLineage(t, newAnthropicRequestLineage, []byte(`{"model":"preset-model","system":[{"type":"text","text":"system"}],"messages":[{"role":"user","content":"hello"},{"role":"assistant","content":[{"type":"tool_use","id":"tool-1","name":"artifact","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"tool-1","content":"ok"}]}],"tools":[{"name":"artifact","input_schema":{"type":"object","maximum":9007199254740992}}]}`))
	anthropicEquivalent := mustRawLogicalRequestLineage(t, newAnthropicRequestLineage, []byte(`{"tools":[{"input_schema":{"maximum":9007199254740992,"type":"object"},"name":"artifact"}],"messages":[{"role":"user","content":"hello"},{"content":[{"id":"tool-1","input":{},"name":"artifact","type":"tool_use"}],"role":"assistant"},{"content":[{"content":"ok","tool_use_id":"tool-1","type":"tool_result"}],"role":"user"}],"system":[{"text":"system","type":"text"}],"model":"preset-model"}`))
	if anthropicBase != anthropicEquivalent {
		t.Fatalf("equivalent Anthropic lineage differs: %+v != %+v", anthropicBase, anthropicEquivalent)
	}
	for name, raw := range map[string][]byte{
		"large schema integer": []byte(`{"model":"preset-model","system":[{"type":"text","text":"system"}],"messages":[{"role":"user","content":"hello"},{"role":"assistant","content":[{"type":"tool_use","id":"tool-1","name":"artifact","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"tool-1","content":"ok"}]}],"tools":[{"name":"artifact","input_schema":{"type":"object","maximum":9007199254740993}}]} `),
		"committed result":     []byte(`{"model":"preset-model","system":[{"type":"text","text":"system"}],"messages":[{"role":"user","content":"hello"},{"role":"assistant","content":[{"type":"tool_use","id":"tool-1","name":"artifact","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"tool-1","content":"changed"}]}],"tools":[{"name":"artifact","input_schema":{"type":"object","maximum":9007199254740992}}]}`),
	} {
		t.Run("anthropic "+name, func(t *testing.T) {
			if got := mustRawLogicalRequestLineage(t, newAnthropicRequestLineage, raw); got == anthropicBase {
				t.Fatalf("Anthropic %s mutation retained the same lineage", name)
			}
		})
	}
	if chatBase == anthropicBase {
		t.Fatal("endpoint-specific lineage must not collide")
	}
}

func TestLogicalRequestEndpointContinuationLineage(t *testing.T) {
	// Chat continuation test
	chatInitialRaw := []byte(`{
		"model": "preset-model",
		"messages": [{"role": "user", "content": "hello"}],
		"tools": [{"type": "function", "function": {"name": "artifact", "parameters": {"type": "object", "maximum": 9007199254740992}}}]
	}`)
	chatInitialLineage, err := newChatRequestLineage(chatInitialRaw)
	if err != nil {
		t.Fatalf("newChatRequestLineage: %v", err)
	}

	chatContinuationRaw := []byte(`{
		"model": "preset-model",
		"messages": [
			{"role": "user", "content": "hello"},
			{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "artifact"}}]},
			{"role": "tool", "tool_call_id": "call_1", "content": "ok"}
		],
		"tools": [{"type": "function", "function": {"name": "artifact", "parameters": {"type": "object", "maximum": 9007199254740992}}}]
	}`)
	chatContinuationLineage, err := newChatContinuationLineage(chatContinuationRaw)
	if err != nil {
		t.Fatalf("newChatContinuationLineage: %v", err)
	}

	if chatContinuationLineage.Prefix != chatInitialLineage {
		t.Fatalf("Chat prefix lineage mismatch: %+v != %+v", chatContinuationLineage.Prefix, chatInitialLineage)
	}
	if len(chatContinuationLineage.ResultIDs) != 1 || chatContinuationLineage.ResultIDs[0] != "call_1" {
		t.Fatalf("Chat result IDs = %v, want [call_1]", chatContinuationLineage.ResultIDs)
	}
	if chatContinuationLineage.IssuedCallHash == "" {
		t.Fatal("Chat issued call hash is empty")
	}

	// Anthropic continuation test
	anthropicInitialRaw := []byte(`{
		"model": "preset-model",
		"system": [{"type": "text", "text": "sys"}],
		"messages": [{"role": "user", "content": "hello"}],
		"tools": [{"name": "artifact", "input_schema": {"type": "object", "maximum": 9007199254740992}}]
	}`)
	anthropicInitialLineage, err := newAnthropicRequestLineage(anthropicInitialRaw)
	if err != nil {
		t.Fatalf("newAnthropicRequestLineage: %v", err)
	}

	anthropicContinuationRaw := []byte(`{
		"model": "preset-model",
		"system": [{"type": "text", "text": "sys"}],
		"messages": [
			{"role": "user", "content": "hello"},
			{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "artifact", "input": {}}]},
			{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}]}
		],
		"tools": [{"name": "artifact", "input_schema": {"type": "object", "maximum": 9007199254740992}}]
	}`)
	anthropicContinuationLineage, err := newAnthropicContinuationLineage(anthropicContinuationRaw)
	if err != nil {
		t.Fatalf("newAnthropicContinuationLineage: %v", err)
	}

	if anthropicContinuationLineage.Prefix != anthropicInitialLineage {
		t.Fatalf("Anthropic prefix lineage mismatch: %+v != %+v", anthropicContinuationLineage.Prefix, anthropicInitialLineage)
	}
	if len(anthropicContinuationLineage.ResultIDs) != 1 || anthropicContinuationLineage.ResultIDs[0] != "tu_1" {
		t.Fatalf("Anthropic result IDs = %v, want [tu_1]", anthropicContinuationLineage.ResultIDs)
	}
	if anthropicContinuationLineage.IssuedCallHash == "" {
		t.Fatal("Anthropic issued call hash is empty")
	}

	// Rejections
	for name, raw := range map[string][]byte{
		"chat no assistant": []byte(`{
			"model": "preset-model",
			"messages": [
				{"role": "user", "content": "hello"},
				{"role": "tool", "tool_call_id": "call_1", "content": "ok"}
			]
		}`),
		"chat tool call count mismatch": []byte(`{
			"model": "preset-model",
			"messages": [
				{"role": "user", "content": "hello"},
				{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "artifact"}}, {"id": "call_2", "type": "function", "function": {"name": "artifact"}}]},
				{"role": "tool", "tool_call_id": "call_1", "content": "ok"}
			]
		}`),
		"anthropic no tool_result": []byte(`{
			"model": "preset-model",
			"messages": [
				{"role": "user", "content": "hello"},
				{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "artifact", "input": {}}]},
				{"role": "user", "content": [{"type": "text", "text": "not result"}]}
			]
		}`),
	} {
		t.Run("rejection "+name, func(t *testing.T) {
			if _, err := newChatContinuationLineage(raw); err == nil {
				t.Fatalf("Chat %s should have failed", name)
			}
			if _, err := newAnthropicContinuationLineage(raw); err == nil {
				t.Fatalf("Anthropic %s should have failed", name)
			}
		})
	}
}

func TestIssuedToolHashIgnoresSDKAssistantDecoration(t *testing.T) {
	output := normalizedStageOutput{Content: "provider preface", Reasoning: "private", ToolCalls: []normalizedToolCall{{
		ID: "call_1", Name: "bash", RawArgs: `{"command":"printf ok"}`,
	}}}
	want, err := directIssuedCallHash("openai", output)
	if err != nil {
		t.Fatal(err)
	}
	got, err := chatIssuedCallHash(json.RawMessage(`{
		"role":"assistant",
		"content":null,
		"reasoning_content":"sdk-normalized",
		"provider_metadata":{"ignored":true},
		"tool_calls":[{"id":"call_1","type":"function","provider_metadata":{"ignored":true},"function":{"name":"bash","arguments":"{ \"command\" : \"printf ok\" }"}}]
	}`))
	if err != nil {
		t.Fatal(err)
	}
	if got != want {
		t.Fatalf("semantic issued call hash mismatch: got %q want %q", got, want)
	}
}

func TestLogicalRequestMultiTurnValidControl(t *testing.T) {
	// Chat 2-turn multi-turn valid control
	chatTurn1Raw := []byte(`{
		"model": "preset-model",
		"messages": [
			{"role": "user", "content": "hello"},
			{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "search"}}]},
			{"role": "tool", "tool_call_id": "call_1", "content": "found 1"}
		],
		"tools": [{"type": "function", "function": {"name": "search", "parameters": {"type": "object", "maximum": 9007199254740992}}}]
	}`)
	chatTurn1Lineage, err := newChatContinuationLineage(chatTurn1Raw)
	if err != nil {
		t.Fatalf("chat turn 1 continuation lineage: %v", err)
	}

	chatTurn2Raw := []byte(`{
		"model": "preset-model",
		"messages": [
			{"role": "user", "content": "hello"},
			{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "search"}}]},
			{"role": "tool", "tool_call_id": "call_1", "content": "found 1"},
			{"role": "assistant", "tool_calls": [{"id": "call_2", "type": "function", "function": {"name": "search"}}]},
			{"role": "tool", "tool_call_id": "call_2", "content": "found 2"}
		],
		"tools": [{"type": "function", "function": {"name": "search", "parameters": {"type": "object", "maximum": 9007199254740992}}}]
	}`)
	chatTurn2Lineage, err := newChatContinuationLineage(chatTurn2Raw)
	if err != nil {
		t.Fatalf("chat turn 2 continuation lineage: %v", err)
	}
	if chatTurn2Lineage.Prefix != chatTurn1Lineage.Committed {
		t.Fatalf("chat turn 2 prefix does not match turn 1 committed: %+v != %+v", chatTurn2Lineage.Prefix, chatTurn1Lineage.Committed)
	}
	if len(chatTurn2Lineage.ResultIDs) != 1 || chatTurn2Lineage.ResultIDs[0] != "call_2" {
		t.Fatalf("chat turn 2 result IDs = %v, want [call_2]", chatTurn2Lineage.ResultIDs)
	}

	// Anthropic 2-turn multi-turn valid control
	anthropicTurn1Raw := []byte(`{
		"model": "preset-model",
		"system": [{"type": "text", "text": "sys"}],
		"messages": [
			{"role": "user", "content": "hello"},
			{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "search", "input": {}}]},
			{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "found 1"}]}
		],
		"tools": [{"name": "search", "input_schema": {"type": "object", "maximum": 9007199254740992}}]
	}`)
	anthropicTurn1Lineage, err := newAnthropicContinuationLineage(anthropicTurn1Raw)
	if err != nil {
		t.Fatalf("anthropic turn 1 continuation lineage: %v", err)
	}

	anthropicTurn2Raw := []byte(`{
		"model": "preset-model",
		"system": [{"type": "text", "text": "sys"}],
		"messages": [
			{"role": "user", "content": "hello"},
			{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "search", "input": {}}]},
			{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "found 1"}]},
			{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_2", "name": "search", "input": {}}]},
			{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_2", "content": "found 2"}]}
		],
		"tools": [{"name": "search", "input_schema": {"type": "object", "maximum": 9007199254740992}}]
	}`)
	anthropicTurn2Lineage, err := newAnthropicContinuationLineage(anthropicTurn2Raw)
	if err != nil {
		t.Fatalf("anthropic turn 2 continuation lineage: %v", err)
	}
	if anthropicTurn2Lineage.Prefix != anthropicTurn1Lineage.Committed {
		t.Fatalf("anthropic turn 2 prefix does not match turn 1 committed: %+v != %+v", anthropicTurn2Lineage.Prefix, anthropicTurn1Lineage.Committed)
	}
	if len(anthropicTurn2Lineage.ResultIDs) != 1 || anthropicTurn2Lineage.ResultIDs[0] != "tu_2" {
		t.Fatalf("anthropic turn 2 result IDs = %v, want [tu_2]", anthropicTurn2Lineage.ResultIDs)
	}
}

func TestLogicalRequestEndpointContinuationRejectionMatrix(t *testing.T) {
	tests := []struct {
		name     string
		endpoint string
		raw      []byte
	}{
		{
			name:     "chat duplicate issued assistant tool call id",
			endpoint: "chat",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f"}}, {"id": "call_1", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_1", "content": "ok"}
				],
				"tools": [{"type": "function", "function": {"name": "f"}}]
			}`),
		},
		{
			name:     "chat duplicate historical issued assistant tool call id",
			endpoint: "chat",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_1", "content": "ok"},
					{"role": "user", "content": "next"},
					{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_1", "content": "ok"}
				],
				"tools": [{"type": "function", "function": {"name": "f"}}]
			}`),
		},
		{
			name:     "chat orphan historical tool result message",
			endpoint: "chat",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "tool", "tool_call_id": "call_1", "content": "orphan"},
					{"role": "assistant", "tool_calls": [{"id": "call_2", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_2", "content": "ok"}
				],
				"tools": [{"type": "function", "function": {"name": "f"}}]
			}`),
		},
		{
			name:     "chat historical partial tool result set",
			endpoint: "chat",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f"}}, {"id": "call_2", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_1", "content": "ok"},
					{"role": "user", "content": "next"},
					{"role": "assistant", "tool_calls": [{"id": "call_3", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_3", "content": "ok"}
				],
				"tools": [{"type": "function", "function": {"name": "f"}}]
			}`),
		},
		{
			name:     "chat historical unknown tool result",
			endpoint: "chat",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_unknown", "content": "ok"},
					{"role": "assistant", "tool_calls": [{"id": "call_2", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_2", "content": "ok"}
				],
				"tools": [{"type": "function", "function": {"name": "f"}}]
			}`),
		},
		{
			name:     "chat unknown prefix message role",
			endpoint: "chat",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "alien", "content": "hi"},
					{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_1", "content": "ok"}
				],
				"tools": [{"type": "function", "function": {"name": "f"}}]
			}`),
		},
		{
			name:     "chat empty prefix message role",
			endpoint: "chat",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "", "content": "hi"},
					{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_1", "content": "ok"}
				],
				"tools": [{"type": "function", "function": {"name": "f"}}]
			}`),
		},
		{
			name:     "chat partial result set",
			endpoint: "chat",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f"}}, {"id": "call_2", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_1", "content": "ok"}
				],
				"tools": [{"type": "function", "function": {"name": "f"}}]
			}`),
		},
		{
			name:     "chat duplicate results in frontier",
			endpoint: "chat",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_1", "content": "ok"},
					{"role": "tool", "tool_call_id": "call_1", "content": "ok again"}
				],
				"tools": [{"type": "function", "function": {"name": "f"}}]
			}`),
		},
		{
			name:     "chat non-trailing tool results",
			endpoint: "chat",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f"}}]},
					{"role": "tool", "tool_call_id": "call_1", "content": "ok"},
					{"role": "user", "content": "next prompt"}
				],
				"tools": [{"type": "function", "function": {"name": "f"}}]
			}`),
		},
		{
			name:     "chat missing assistant before tool results",
			endpoint: "chat",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "tool", "tool_call_id": "call_1", "content": "ok"}
				],
				"tools": [{"type": "function", "function": {"name": "f"}}]
			}`),
		},

		{
			name:     "anthropic duplicate issued assistant tool_use id",
			endpoint: "anthropic",
			raw: []byte(`{
				"model": "preset-model",
				"system": [{"type": "text", "text": "sys"}],
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "f", "input": {}}, {"type": "tool_use", "id": "tu_1", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}]}
				],
				"tools": [{"name": "f", "input_schema": {"type": "object"}}]
			}`),
		},
		{
			name:     "anthropic duplicate historical issued assistant tool_use id",
			endpoint: "anthropic",
			raw: []byte(`{
				"model": "preset-model",
				"system": [{"type": "text", "text": "sys"}],
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}]},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}]}
				],
				"tools": [{"name": "f", "input_schema": {"type": "object"}}]
			}`),
		},
		{
			name:     "anthropic historical unknown assistant content block",
			endpoint: "anthropic",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "content": [{"type": "unsupported_block"}]},
					{"role": "user", "content": "next"}
				],
				"tools": [{"name": "f", "input_schema": {"type": "object"}}]
			}`),
		},
		{
			name:     "anthropic historical orphan tool_result block",
			endpoint: "anthropic",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_orphan", "content": "orphan"}]},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}]}
				],
				"tools": [{"name": "f", "input_schema": {"type": "object"}}]
			}`),
		},
		{
			name:     "anthropic historical partial tool_result set",
			endpoint: "anthropic",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "f", "input": {}}, {"type": "tool_use", "id": "tu_2", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}]},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_3", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_3", "content": "ok"}]}
				],
				"tools": [{"name": "f", "input_schema": {"type": "object"}}]
			}`),
		},
		{
			name:     "anthropic unknown message role inside messages",
			endpoint: "anthropic",
			raw: []byte(`{
				"model": "preset-model",
				"system": [{"type": "text", "text": "sys"}],
				"messages": [
					{"role": "alien", "content": "hi"},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}]}
				],
				"tools": [{"name": "f", "input_schema": {"type": "object"}}]
			}`),
		},
		{
			name:     "anthropic system role inside messages array",
			endpoint: "anthropic",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "system", "content": "sys"},
					{"role": "user", "content": "hi"},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}]}
				],
				"tools": [{"name": "f", "input_schema": {"type": "object"}}]
			}`),
		},
		{
			name:     "anthropic non-alternating roles",
			endpoint: "anthropic",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "user", "content": "hello again"},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}]}
				],
				"tools": [{"name": "f", "input_schema": {"type": "object"}}]
			}`),
		},
		{
			name:     "anthropic partial result set",
			endpoint: "anthropic",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "f", "input": {}}, {"type": "tool_use", "id": "tu_2", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}]}
				],
				"tools": [{"name": "f", "input_schema": {"type": "object"}}]
			}`),
		},
		{
			name:     "anthropic duplicate tool_result in frontier",
			endpoint: "anthropic",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}, {"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}]}
				],
				"tools": [{"name": "f", "input_schema": {"type": "object"}}]
			}`),
		},
		{
			name:     "anthropic mixed trailing user instruction and tool result",
			endpoint: "anthropic",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}, {"type": "text", "text": "new instruction"}]}
				],
				"tools": [{"name": "f", "input_schema": {"type": "object"}}]
			}`),
		},
		{
			name:     "anthropic malformed assistant empty tool_use id",
			endpoint: "anthropic",
			raw: []byte(`{
				"model": "preset-model",
				"messages": [
					{"role": "user", "content": "hi"},
					{"role": "assistant", "content": [{"type": "tool_use", "id": "", "name": "f", "input": {}}]},
					{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"}]}
				],
				"tools": [{"name": "f", "input_schema": {"type": "object"}}]
			}`),
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if tt.endpoint == "chat" {
				if _, err := newChatContinuationLineage(tt.raw); err == nil {
					t.Fatalf("Chat continuation %s should have failed", tt.name)
				}
			} else {
				if _, err := newAnthropicContinuationLineage(tt.raw); err == nil {
					t.Fatalf("Anthropic continuation %s should have failed", tt.name)
				}
			}
		})
	}
}

func TestLogicalRequestCommittedLineageAdvance(t *testing.T) {
	coordinator := newLogicalRequestCoordinator(logicalRequestCoordinatorOptions{IDSource: sequentialLogicalRequestIDs("advance")})

	chatInitialRaw := []byte(`{
		"model": "preset-model",
		"messages": [{"role": "user", "content": "hello"}],
		"tools": [{"type": "function", "function": {"name": "search"}}]
	}`)
	initialLineage, err := newChatRequestLineage(chatInitialRaw)
	if err != nil {
		t.Fatalf("initial lineage: %v", err)
	}

	request, err := coordinator.create(logicalRequestAdmission{
		OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: initialLineage, PresetGeneration: "gen-1",
	})
	if err != nil {
		t.Fatalf("create: %v", err)
	}

	// Turn 1
	stg1, _ := coordinator.newStageID()
	if _, err := coordinator.activateStage(request.ID, "edge-a", stg1); err != nil {
		t.Fatalf("activate stage 1: %v", err)
	}

	chatTurn1Raw := []byte(`{
		"model": "preset-model",
		"messages": [
			{"role": "user", "content": "hello"},
			{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "search"}}]},
			{"role": "tool", "tool_call_id": "call_1", "content": "found"}
		],
		"tools": [{"type": "function", "function": {"name": "search"}}]
	}`)
	turn1ContLineage, err := newChatContinuationLineage(chatTurn1Raw)
	if err != nil {
		t.Fatalf("turn 1 continuation lineage: %v", err)
	}

	if _, err := coordinator.awaitToolResults(request.ID, "edge-a", stg1, []logicalRequestExpectedTool{
		{PublicCallID: "call_1", ProviderCallID: "prov_1"},
	}, turn1ContLineage.IssuedCallHash); err != nil {
		t.Fatalf("await tool results 1: %v", err)
	}

	// Rejection test 1: wrong issued call hash
	mutatedCont := logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: "edge-a", PrincipalRef: "principal-a",
		Lineage: logicalRequestContinuationLineage{
			Prefix: turn1ContLineage.Prefix, IssuedCallHash: "wrong_hash",
			ResultIDs: turn1ContLineage.ResultIDs, Committed: turn1ContLineage.Committed,
		},
		Results: []logicalRequestToolResult{{PublicCallID: "call_1"}},
	}
	if _, err := coordinator.consumeContinuation(mutatedCont); !errors.Is(err, errLogicalRequestLineage) {
		t.Fatalf("wrong issued call hash error = %v, want %v", err, errLogicalRequestLineage)
	}

	// State must be unchanged after rejection
	snap, err := coordinator.snapshot(request.ID)
	if err != nil || snap.State != logicalRequestStateWaiting {
		t.Fatalf("snapshot mutated after rejection: %+v, %v", snap, err)
	}

	// Valid consume turn 1
	validCont1 := logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: "edge-a", PrincipalRef: "principal-a",
		Lineage: turn1ContLineage,
		Results: []logicalRequestToolResult{{PublicCallID: "call_1"}},
	}
	res1, err := coordinator.consumeContinuation(validCont1)
	if err != nil {
		t.Fatalf("consume turn 1: %v", err)
	}
	if res1.State != logicalRequestStateResumed {
		t.Fatalf("res1 state = %s, want resumed", res1.State)
	}

	// Turn 2
	stg2, _ := coordinator.newStageID()
	if _, err := coordinator.activateStage(request.ID, "edge-a", stg2); err != nil {
		t.Fatalf("activate stage 2: %v", err)
	}

	chatTurn2Raw := []byte(`{
		"model": "preset-model",
		"messages": [
			{"role": "user", "content": "hello"},
			{"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "search"}}]},
			{"role": "tool", "tool_call_id": "call_1", "content": "found"},
			{"role": "assistant", "tool_calls": [{"id": "call_2", "type": "function", "function": {"name": "search"}}]},
			{"role": "tool", "tool_call_id": "call_2", "content": "done"}
		],
		"tools": [{"type": "function", "function": {"name": "search"}}]
	}`)
	turn2ContLineage, err := newChatContinuationLineage(chatTurn2Raw)
	if err != nil {
		t.Fatalf("turn 2 continuation lineage: %v", err)
	}

	if turn2ContLineage.Prefix != turn1ContLineage.Committed {
		t.Fatalf("turn 2 prefix does not match turn 1 committed lineage: %+v != %+v", turn2ContLineage.Prefix, turn1ContLineage.Committed)
	}

	if _, err := coordinator.awaitToolResults(request.ID, "edge-a", stg2, []logicalRequestExpectedTool{
		{PublicCallID: "call_2", ProviderCallID: "prov_2"},
	}, turn2ContLineage.IssuedCallHash); err != nil {
		t.Fatalf("await tool results 2: %v", err)
	}

	// Race on turn 2
	validCont2 := logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: "edge-a", PrincipalRef: "principal-a",
		Lineage: turn2ContLineage,
		Results: []logicalRequestToolResult{{PublicCallID: "call_2"}},
	}
	const callers = 16
	start := make(chan struct{})
	var wg sync.WaitGroup
	var mu sync.Mutex
	successes := 0
	for range callers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			<-start
			_, err := coordinator.consumeContinuation(validCont2)
			if err == nil {
				mu.Lock()
				successes++
				mu.Unlock()
			}
		}()
	}
	close(start)
	wg.Wait()
	if successes != 1 {
		t.Fatalf("turn 2 race successes = %d, want 1", successes)
	}
}

func TestLogicalRequestToolMappingCollisionAndReplay(t *testing.T) {
	coordinator := newLogicalRequestCoordinator(logicalRequestCoordinatorOptions{IDSource: sequentialLogicalRequestIDs("mapping")})
	lineage := mustChatLogicalRequestLineage(t, "history", "tool")
	request, err := coordinator.create(logicalRequestAdmission{OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: lineage, PresetGeneration: "preset-gen-1"})
	if err != nil {
		t.Fatalf("create: %v", err)
	}
	stageID, err := coordinator.newStageID()
	if err != nil {
		t.Fatalf("new stage: %v", err)
	}
	if _, err := coordinator.activateStage(request.ID, "edge-a", stageID); err != nil {
		t.Fatalf("activate: %v", err)
	}
	assertActive := func(name string, wantStage string) {
		t.Helper()
		snapshot, err := coordinator.snapshot(request.ID)
		if err != nil {
			t.Fatalf("%s snapshot: %v", name, err)
		}
		if snapshot.State != logicalRequestStateActive || snapshot.ActiveStageID != wantStage || len(snapshot.ExpectedCallIDs) != 0 {
			t.Fatalf("%s unexpectedly mutated state: %+v", name, snapshot)
		}
	}
	const hash1 = "hash_mapping_1"
	for name, expected := range map[string][]logicalRequestExpectedTool{
		"duplicate public":   {{PublicCallID: "call_one", ProviderCallID: "provider_one"}, {PublicCallID: "call_one", ProviderCallID: "provider_two"}},
		"duplicate provider": {{PublicCallID: "call_one", ProviderCallID: "provider_one"}, {PublicCallID: "call_two", ProviderCallID: "provider_one"}},
	} {
		if _, err := coordinator.awaitToolResults(request.ID, "edge-a", stageID, expected, hash1); !errors.Is(err, errLogicalRequestFrontier) {
			t.Fatalf("%s error = %v, want %v", name, err, errLogicalRequestFrontier)
		}
		assertActive(name, stageID)
	}
	if _, err := coordinator.awaitToolResults(request.ID, "edge-a", stageID, []logicalRequestExpectedTool{{PublicCallID: "call_one", ProviderCallID: "provider_one"}}, hash1); err != nil {
		t.Fatalf("await valid frontier: %v", err)
	}
	if _, err := coordinator.consumeContinuation(logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: "edge-a", PrincipalRef: "principal-a",
		Lineage: logicalRequestContinuationLineage{
			Prefix: lineage, IssuedCallHash: hash1, ResultIDs: []string{"call_one"},
			Committed: logicalRequestLineage{Endpoint: lineage.Endpoint, HistoryDigest: "mapping_committed_1", ToolsetDigest: lineage.ToolsetDigest},
		},
		Results: []logicalRequestToolResult{{PublicCallID: "call_one"}},
	}); err != nil {
		t.Fatalf("consume valid frontier: %v", err)
	}
	nextStage, err := coordinator.newStageID()
	if err != nil {
		t.Fatalf("new next stage: %v", err)
	}
	if _, err := coordinator.activateStage(request.ID, "edge-a", nextStage); err != nil {
		t.Fatalf("activate next stage: %v", err)
	}
	const hash2 = "hash_mapping_2"
	for name, expected := range map[string][]logicalRequestExpectedTool{
		"replayed public":   {{PublicCallID: "call_one", ProviderCallID: "provider_two"}},
		"replayed provider": {{PublicCallID: "call_two", ProviderCallID: "provider_one"}},
	} {
		if _, err := coordinator.awaitToolResults(request.ID, "edge-a", nextStage, expected, hash2); !errors.Is(err, errLogicalRequestFrontier) {
			t.Fatalf("%s error = %v, want %v", name, err, errLogicalRequestFrontier)
		}
		assertActive(name, nextStage)
	}
}

func TestLogicalRequestBoundsDoNotMutate(t *testing.T) {
	coordinator := newLogicalRequestCoordinator(logicalRequestCoordinatorOptions{
		FrontierCapacity: 2, MappingCapacity: 2, IDSource: sequentialLogicalRequestIDs("bounds"),
	})
	lineage := mustChatLogicalRequestLineage(t, "history", "tool")
	request, err := coordinator.create(logicalRequestAdmission{OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: lineage, PresetGeneration: "preset-gen-1"})
	if err != nil {
		t.Fatalf("create: %v", err)
	}
	stageID, _ := coordinator.newStageID()
	if _, err := coordinator.activateStage(request.ID, "edge-a", stageID); err != nil {
		t.Fatalf("activate: %v", err)
	}
	const hash1 = "hash_bounds_1"
	overLimit := []logicalRequestExpectedTool{{PublicCallID: "call_one", ProviderCallID: "provider_one"}, {PublicCallID: "call_two", ProviderCallID: "provider_two"}, {PublicCallID: "call_three", ProviderCallID: "provider_three"}}
	if _, err := coordinator.awaitToolResults(request.ID, "edge-a", stageID, overLimit, hash1); !errors.Is(err, errLogicalRequestFrontier) {
		t.Fatalf("frontier limit error = %v, want %v", err, errLogicalRequestFrontier)
	}
	snapshot, err := coordinator.snapshot(request.ID)
	if err != nil || snapshot.State != logicalRequestStateActive || snapshot.ActiveStageID != stageID || len(snapshot.ExpectedCallIDs) != 0 {
		t.Fatalf("frontier limit mutated state: %+v, %v", snapshot, err)
	}
	exactLimit := overLimit[:2]
	if _, err := coordinator.awaitToolResults(request.ID, "edge-a", stageID, exactLimit, hash1); err != nil {
		t.Fatalf("exact frontier limit: %v", err)
	}
	if _, err := coordinator.consumeContinuation(logicalRequestContinuation{
		RequestID: request.ID, OwnerEdgeID: "edge-a", PrincipalRef: "principal-a",
		Lineage: logicalRequestContinuationLineage{
			Prefix: lineage, IssuedCallHash: hash1, ResultIDs: []string{"call_one", "call_two"},
			Committed: logicalRequestLineage{Endpoint: lineage.Endpoint, HistoryDigest: "bounds_committed_1", ToolsetDigest: lineage.ToolsetDigest},
		},
		Results: []logicalRequestToolResult{{PublicCallID: "call_one"}, {PublicCallID: "call_two"}},
	}); err != nil {
		t.Fatalf("consume: %v", err)
	}
	nextStage, _ := coordinator.newStageID()
	if _, err := coordinator.activateStage(request.ID, "edge-a", nextStage); err != nil {
		t.Fatalf("activate next: %v", err)
	}
	const hash2 = "hash_bounds_2"
	if _, err := coordinator.awaitToolResults(request.ID, "edge-a", nextStage, []logicalRequestExpectedTool{{PublicCallID: "call_three", ProviderCallID: "provider_three"}}, hash2); !errors.Is(err, errLogicalRequestFrontier) {
		t.Fatalf("mapping limit error = %v, want %v", err, errLogicalRequestFrontier)
	}
	snapshot, err = coordinator.snapshot(request.ID)
	if err != nil || snapshot.State != logicalRequestStateActive || snapshot.ActiveStageID != nextStage || len(snapshot.ExpectedCallIDs) != 0 {
		t.Fatalf("mapping limit mutated state: %+v, %v", snapshot, err)
	}
}

func TestLogicalRequestAdmissionRequiresPresetGeneration(t *testing.T) {
	coordinator := newLogicalRequestCoordinator(logicalRequestCoordinatorOptions{IDSource: sequentialLogicalRequestIDs("generation")})
	lineage := mustChatLogicalRequestLineage(t, "history", "tool")
	if _, err := coordinator.create(logicalRequestAdmission{OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: lineage}); err == nil {
		t.Fatal("create without preset generation succeeded")
	}
	if _, err := coordinator.create(logicalRequestAdmission{OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: lineage, PresetGeneration: "preset-gen-1"}); err != nil {
		t.Fatalf("create with preset generation: %v", err)
	}
}

func TestLogicalRequestCapacityAcceptsAfterExplicitExpiredSweep(t *testing.T) {
	now := time.Unix(100, 0)
	coordinator := newLogicalRequestCoordinator(logicalRequestCoordinatorOptions{Capacity: 1, TTL: time.Second, Now: func() time.Time { return now }, IDSource: sequentialLogicalRequestIDs("capacity")})
	lineage := mustChatLogicalRequestLineage(t, "history", "tool")
	if _, err := coordinator.create(logicalRequestAdmission{OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: lineage, PresetGeneration: "preset-gen-1"}); err != nil {
		t.Fatalf("first create: %v", err)
	}
	now = now.Add(2 * time.Second)
	if swept := coordinator.sweepExpired(now, 1); len(swept) != 1 {
		t.Fatalf("expired sweep count=%d, want 1", len(swept))
	}
	if _, err := coordinator.create(logicalRequestAdmission{OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: lineage, PresetGeneration: "preset-gen-1"}); err != nil {
		t.Fatalf("create after TTL eviction: %v", err)
	}
}

func TestLogicalRequestExpiredStateIsRejected(t *testing.T) {
	now := time.Unix(100, 0)
	coordinator := newLogicalRequestCoordinator(logicalRequestCoordinatorOptions{
		TTL: time.Second, Now: func() time.Time { return now }, IDSource: sequentialLogicalRequestIDs("expiry"),
	})
	lineage := mustChatLogicalRequestLineage(t, "history", "tool")
	request, err := coordinator.create(logicalRequestAdmission{OwnerEdgeID: "edge-a", PrincipalRef: "principal-a", Lineage: lineage, PresetGeneration: "preset-gen-1"})
	if err != nil {
		t.Fatalf("create: %v", err)
	}
	now = now.Add(2 * time.Second)
	if _, err := coordinator.snapshot(request.ID); !errors.Is(err, errLogicalRequestNotFound) {
		t.Fatalf("expired snapshot error = %v, want %v", err, errLogicalRequestNotFound)
	}
}

func mustChatLogicalRequestLineage(t *testing.T, content string, tools ...any) logicalRequestLineage {
	t.Helper()
	raw, err := json.Marshal(chatCompletionRequest{
		Model: "preset-model", Messages: []chatMessage{{Role: "user", Content: content}}, Tools: tools,
	})
	if err != nil {
		t.Fatalf("marshal Chat request lineage: %v", err)
	}
	lineage, err := newChatRequestLineage(raw)
	if err != nil {
		t.Fatalf("new Chat request lineage: %v", err)
	}
	return lineage
}

func mustRawLogicalRequestLineage(t *testing.T, build func(json.RawMessage) (logicalRequestLineage, error), raw []byte) logicalRequestLineage {
	t.Helper()
	lineage, err := build(raw)
	if err != nil {
		t.Fatalf("new raw request lineage: %v", err)
	}
	return lineage
}

func sequentialLogicalRequestIDs(prefix string) func() (string, error) {
	var mu sync.Mutex
	var next int
	return func() (string, error) {
		mu.Lock()
		defer mu.Unlock()
		next++
		return fmt.Sprintf("%s_%d", prefix, next), nil
	}
}
