Exercise shared campaign and consumer workflows

This commit is contained in:
2026-11-30 02:29:50 +00:00
parent b5b4672920
commit 706c1bb7ad
26 changed files with 417 additions and 489 deletions

View File

@@ -13,378 +13,156 @@ import (
"testing"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
"gitea.maximumdirect.net/eric/narratio/internal/artifactmodel"
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
const notariusIntegrationBinaryEnv = "NARRATIO_TEST_NOTARIUS_BINARY"
// Run with:
// NARRATIO_TEST_NOTARIUS_BINARY=/absolute/path/to/notarius GOWORK=off go test ./internal/stage -run '^TestNotariusCacheReuseIntegration$' -count=1 -v
func TestNotariusCacheReuseIntegration(t *testing.T) {
binary := strings.TrimSpace(os.Getenv(notariusIntegrationBinaryEnv))
if binary == "" {
t.Skipf("set %s to an absolute Notarius v0.8.1-compatible executable to run this integration test", notariusIntegrationBinaryEnv)
// Set both paths to exercise a selected Notarius checkout and binary with a local provider.
func TestNotariusBinaryCompatibility(t *testing.T) {
binary, repository := os.Getenv("NARRATIO_TEST_NOTARIUS_BINARY"), os.Getenv("NARRATIO_TEST_NOTARIUS_REPOSITORY")
if binary == "" || repository == "" {
t.Skip("set NARRATIO_TEST_NOTARIUS_BINARY and NARRATIO_TEST_NOTARIUS_REPOSITORY")
}
if !filepath.IsAbs(binary) {
t.Fatalf("%s = %q, want an absolute path", notariusIntegrationBinaryEnv, binary)
if !filepath.IsAbs(binary) || !filepath.IsAbs(repository) {
t.Fatal("Notarius binary and repository paths must be absolute")
}
info, err := os.Stat(binary)
if err != nil {
t.Fatalf("inspect %s: %v", notariusIntegrationBinaryEnv, err)
}
if !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 {
t.Fatalf("%s = %q, want an executable regular file", notariusIntegrationBinaryEnv, binary)
}
t.Run("reuse reference identity and forced refresh", func(t *testing.T) {
provider := newNotariusIntegrationProvider(t)
env, runManifest, fixture := newNotariusIntegrationFixture(t, binary, provider.URL(), "dnd-session")
first := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T010101Z-a0000001", false)
if got := provider.Calls(); got != 2 {
t.Fatalf("first provider calls = %d, want 2", got)
}
if first.ChunkPlan == nil || first.ChunkPlan.Action != "generated" {
t.Fatalf("first chunk plan = %#v, want generated", first.ChunkPlan)
}
mode := "auto"
env.Config.Pipeline.Notarius.Cache = &mode
second := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T010102Z-a0000002", false)
if got := provider.Calls(); got != 2 {
t.Fatalf("resumed provider calls = %d, want unchanged count 2", got)
}
assertNotariusIntegrationDecision(t, second, "extract", "spells-first", "reused", "checkpoint_reused")
assertNotariusIntegrationDecision(t, second, "extract", "spells-second", "reused", "checkpoint_reused")
oldSnapshot := notariusIntegrationSnapshotPath(t, env, runManifest, artifactpolicy.SourceInputParty)
setNotariusIntegrationReference(t, runManifest, fixture.partyPath, "The party now travels with a silver dragon.\n")
third := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T010103Z-a0000003", false)
if got := provider.Calls(); got != 4 {
t.Fatalf("changed-reference provider calls = %d, want 4", got)
}
assertNotariusIntegrationDecision(t, third, "extract", "spells-first", "executed", "checkpoint_missing")
newSnapshot := notariusIntegrationSnapshotPath(t, env, runManifest, artifactpolicy.SourceInputParty)
if newSnapshot == oldSnapshot {
t.Fatalf("changed reference retained snapshot %q", newSnapshot)
}
for _, path := range []string{oldSnapshot, newSnapshot} {
if _, err := os.Stat(path); err != nil {
t.Fatalf("snapshot %q is unavailable: %v", path, err)
}
}
setNotariusIntegrationTranscript(t, runManifest, fixture.transcriptPath, notariusIntegrationTranscript("session-unrelated", "The wizard studies Magic Missile."))
unrelated := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T010104Z-a0000004", false)
if unrelated.ChunkPlan == nil || unrelated.ChunkPlan.Action != "generated" {
t.Fatalf("unrelated chunk plan = %#v, want generated", unrelated.ChunkPlan)
}
unrelatedPlan := filepath.Join(fixture.chunkRoot, strings.TrimPrefix(unrelated.ChunkPlan.SourceDigest, "sha256:"), "plan.json")
unrelatedBefore, err := os.ReadFile(unrelatedPlan)
if err != nil {
t.Fatalf("read unrelated chunk plan: %v", err)
}
setNotariusIntegrationTranscript(t, runManifest, fixture.transcriptPath, notariusIntegrationTranscript("session-cache", "Aria casts Cure Wounds."))
forced := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T010105Z-a0000005", true)
if got := provider.Calls(); got != 8 {
t.Fatalf("forced provider calls = %d, want 8", got)
}
if len(forced.CheckpointDecisions) != 0 {
t.Fatalf("forced extraction loaded checkpoint state: %#v", forced.CheckpointDecisions)
}
if forced.ChunkPlan == nil || forced.ChunkPlan.Action != "refreshed" {
t.Fatalf("forced chunk plan = %#v, want refreshed", forced.ChunkPlan)
}
unrelatedAfter, err := os.ReadFile(unrelatedPlan)
if err != nil {
t.Fatalf("read unrelated chunk plan after refresh: %v", err)
}
if string(unrelatedAfter) != string(unrelatedBefore) {
t.Fatal("forced refresh changed the unrelated input's cached plan")
}
})
t.Run("partial failure resumes accepted predecessor", func(t *testing.T) {
provider := newNotariusIntegrationProvider(t)
provider.FailRequest(2)
env, runManifest, _ := newNotariusIntegrationFixture(t, binary, provider.URL(), "dnd-recovery")
mode := "auto"
env.Config.Pipeline.Notarius.Cache = &mode
runManifest.RunID = "20260916T020101Z-b0000001"
env.Force = false
if result, err := (extractStage{}).Run(context.Background(), env, runManifest); err == nil || result != nil {
t.Fatalf("partial extraction result = %#v error = %v, want failure", result, err)
}
if got := provider.Calls(); got != 2 {
t.Fatalf("failed invocation provider calls = %d, want 2", got)
}
provider.FailRequest(0)
recovered := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T020102Z-b0000002", false)
if got := provider.Calls(); got != 3 {
t.Fatalf("recovery provider calls = %d, want one additional call (3 total)", got)
}
assertNotariusIntegrationDecision(t, recovered, "extract", "spells-first", "reused", "checkpoint_reused")
assertNotariusIntegrationDecision(t, recovered, "extract", "spells-second", "executed", "")
})
}
type notariusIntegrationProvider struct {
server *httptest.Server
calls atomic.Int64
failAt atomic.Int64
}
func newNotariusIntegrationProvider(t *testing.T) *notariusIntegrationProvider {
t.Helper()
provider := &notariusIntegrationProvider{}
provider.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
call := provider.calls.Add(1)
if request.Method != http.MethodPost || request.URL.Path != "/v1/chat/completions" {
t.Errorf("provider request = %s %s, want POST /v1/chat/completions", request.Method, request.URL.Path)
http.Error(w, "unexpected request", http.StatusNotFound)
var calls atomic.Int64
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var request map[string]any
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, err.Error(), 400)
return
}
if provider.failAt.Load() == call {
http.Error(w, "controlled provider failure", http.StatusInternalServerError)
calls.Add(1)
encoded, _ := json.Marshal(request["response_format"])
schema := string(encoded)
format, _ := request["response_format"].(map[string]any)
spec, _ := format["json_schema"].(map[string]any)
definition, _ := spec["schema"].(map[string]any)
properties, _ := definition["properties"].(map[string]any)
has := func(name string) bool { _, ok := properties[name]; return ok }
content := ""
switch {
case has("status"):
content = `{"status":"ok"}`
case has("classification"):
content = `{"classification":"non_combat","explanation":"No combat."}`
case has("scenes"):
content = `{"scenes":[{"start_unit_id":1,"end_unit_id":2}]}`
case has("kind") && has("summary"):
content = `{"kind":"narrative","title":"Travel","summary":"The party travels."}`
case has("duplicate_groups"):
content = `{"duplicate_groups":[]}`
case has("spell_casts"):
content = `{"spell_casts":[]}`
case has("occurrences"):
content = `{"occurrences":[]}`
case has("combat_turns"):
content = `{"combat_turns":[]}`
case has("enemy_events"):
content = `{"enemy_events":[]}`
case has("items"):
content = `{"items":[]}`
case has("npcs"):
content = `{"npcs":[]}`
case has("locations"):
content = `{"locations":[]}`
default:
t.Errorf("unrecognized provider schema: %s", schema)
http.Error(w, "unknown schema", 400)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"local-completion","object":"chat.completion","created":1,"model":"local-model","choices":[{"index":0,"message":{"role":"assistant","content":"{\"spell_casts\":[]}"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":4,"total_tokens":14}}`))
_ = json.NewEncoder(w).Encode(map[string]any{"choices": []any{map[string]any{"message": map[string]any{"role": "assistant", "content": content}, "finish_reason": "stop"}}})
}))
t.Cleanup(provider.server.Close)
return provider
}
func (p *notariusIntegrationProvider) URL() string { return p.server.URL }
func (p *notariusIntegrationProvider) Calls() int64 { return p.calls.Load() }
func (p *notariusIntegrationProvider) FailRequest(request int64) { p.failAt.Store(request) }
type notariusIntegrationFixture struct {
transcriptPath string
partyPath string
chunkRoot string
}
func newNotariusIntegrationFixture(t *testing.T, binary, endpoint, pipelineID string) (*Env, *manifest.Manifest, notariusIntegrationFixture) {
t.Helper()
env, runManifest, _ := setupExtractEnv(t)
initialOutput := artifacts.SessionRunNotariusOutputRootForCampaign(
env.Config.Pipeline.Workspace.Root, runManifest.Campaign, runManifest.SessionID, runManifest.RunID,
)
if err := os.RemoveAll(initialOutput); err != nil {
t.Fatalf("remove synthetic output fixture: %v", err)
}
defer provider.Close()
env, m, _ := setupExtractEnv(t)
root := env.Config.Pipeline.Workspace.Root
profilePath := filepath.Join(root, "local-profile.yml")
if err := os.WriteFile(profilePath, []byte("id: local-test\nbackend: local\nmodel: local-model\ntimeout_seconds: 30\n"), 0o600); err != nil {
t.Fatalf("write local profile: %v", err)
}
chunkRoot := filepath.Join(root, "notarius-cache", "chunk-plans")
checkpointRoot := filepath.Join(root, "notarius-cache", "checkpoints")
configPath := filepath.Join(root, "notarius-integration.yml")
content := fmt.Sprintf(`version: 5
promptkit:
profile_file: %q
local_backend:
endpoint: %q
concurrency_limit: 1
concurrency:
total_llm: 1
stage_workers:
extract: 1
output:
directory: %q
cache:
chunk_plans:
mode: auto
directory: %q
checkpoints:
enabled: true
directory: %q
pipelines:
%s:
llm_profile: local-test
input:
module: seriatim
chunk:
module: generic
output:
module: json
steps:
- id: collect-first
artifacts:
spells-first:
extract:
module: dnd/spells
normalize:
module: dnd/spells
- id: collect-second
artifacts:
spells-second:
extract:
module: dnd/spells
normalize:
module: dnd/spells
`, profilePath, endpoint+"/v1", filepath.Join(root, "unused-output"), chunkRoot, checkpointRoot, pipelineID)
if err := os.WriteFile(configPath, []byte(content), 0o600); err != nil {
t.Fatalf("write Notarius integration config: %v", err)
}
// Select a real downstream overlay. Disable provider retries so the controlled
// failure below tests checkpoint recovery rather than transient HTTP recovery.
overlay := "integration"
overlayDir := filepath.Join(root, "overlays")
if err := os.MkdirAll(overlayDir, 0o700); err != nil {
examples := filepath.Join(repository, "examples", "dnd-complete")
configBytes, err := os.ReadFile(filepath.Join(examples, "config.yml"))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(overlayDir, overlay+".yml"), []byte("promptkit:\n transient_retries: 0\n"), 0o600); err != nil {
pipelineBytes, err := os.ReadFile(filepath.Join(examples, "pipelines", "dnd-session.yml"))
if err != nil {
t.Fatal(err)
}
transcriptPath := filepath.Join(sessionPathsForEnv(env, runManifest.SessionID).ArtifactsDir, "trimmed.from-manifest.json")
setNotariusIntegrationTranscript(t, runManifest, transcriptPath, notariusIntegrationTranscript("session-cache", "Aria casts Cure Wounds."))
partyPath := recordPreparedExtractInput(t, env, runManifest, artifactpolicy.SourceInputParty, "The party includes Aria the cleric.\n")
env.Notarius = notarius.NewSubprocessRunner()
env.Config.Pipeline.Notarius = &config.NotariusConfig{
Enabled: true, Binary: binary, ConfigPath: configPath, PipelineID: pipelineID,
ConfigOverlay: &overlay,
Timeout: "2m", WorkingDirectory: root,
References: map[string]string{"party": artifactpolicy.SourceInputParty},
Outputs: map[string]config.NotariusOutputConfig{
"spells_first": {
LaneID: "spells-first",
},
"spells_second": {
LaneID: "spells-second",
},
},
}
return env, runManifest, notariusIntegrationFixture{transcriptPath: transcriptPath, partyPath: partyPath, chunkRoot: chunkRoot}
}
func notariusIntegrationTranscript(id, text string) []byte {
return []byte(fmt.Sprintf(`{"metadata":{"id":%q,"title":"Cache integration"},"segments":[{"id":1,"start":0,"end":4,"speaker":"Aria","text":%q}]}`, id, text))
}
func setNotariusIntegrationTranscript(t *testing.T, runManifest *manifest.Manifest, path string, content []byte) {
t.Helper()
if err := os.WriteFile(path, content, 0o644); err != nil {
t.Fatalf("write integration transcript: %v", err)
}
checksum, err := artifacts.SHA256File(path)
stepBytes, err := os.ReadFile(filepath.Join(examples, "pipelines", "dnd-session.describe-session.yml"))
if err != nil {
t.Fatalf("checksum integration transcript: %v", err)
t.Fatal(err)
}
record := runManifest.Stages["trim"]
if record == nil || len(record.Outputs) != 1 {
t.Fatalf("trim record = %#v, want one output", record)
configDir := filepath.Join(root, "consumer")
if err := os.MkdirAll(filepath.Join(configDir, "pipelines"), 0755); err != nil {
t.Fatal(err)
}
record.Outputs[0].Kind = artifactmodel.TranscriptOutputKindFinalTrimmed
record.Outputs[0].SourceID = artifactmodel.SourceTranscriptFinalTrimmed
record.Outputs[0].LocalPath = path
record.Outputs[0].Checksum = checksum
}
func setNotariusIntegrationReference(t *testing.T, runManifest *manifest.Manifest, path, content string) {
t.Helper()
descriptor, ok := artifactpolicy.DescribePreparedInputSource(artifactpolicy.SourceInputParty)
if !ok {
t.Fatal("prepared party input descriptor is unavailable")
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatalf("write integration reference: %v", err)
}
checksum, err := artifacts.SHA256File(path)
if err != nil {
t.Fatalf("checksum integration reference: %v", err)
}
for index := range runManifest.Inputs {
if runManifest.Inputs[index].Kind == descriptor.ManifestKind {
runManifest.Inputs[index].Checksum = checksum
return
configBytes = append(configBytes, []byte(fmt.Sprintf("\npromptkit:\n backends: [{id: fixture, endpoint: %q}]\n profiles: [{id: fixture, backend: fixture, model: fixture, api_key_required: false}]\n", provider.URL+"/v1"))...)
pipelineBytes = []byte(strings.ReplaceAll(string(pipelineBytes), "notarius/dnd-extraction-example", "fixture"))
for name, data := range map[string][]byte{"config.yml": configBytes, "pipelines/dnd-session.yml": pipelineBytes, "pipelines/dnd-session.describe-session.yml": stepBytes} {
if err := os.WriteFile(filepath.Join(configDir, name), data, 0644); err != nil {
t.Fatal(err)
}
}
t.Fatalf("prepared party input not found in %#v", runManifest.Inputs)
}
func notariusIntegrationSnapshotPath(t *testing.T, env *Env, runManifest *manifest.Manifest, sourceID string) string {
t.Helper()
descriptor, ok := artifactpolicy.DescribePreparedInputSource(sourceID)
if !ok {
t.Fatalf("prepared input descriptor %q is unavailable", sourceID)
transcript, err := os.ReadFile(filepath.Join(repository, "examples", "dnd-minimal", "transcript.json"))
if err != nil {
t.Fatal(err)
}
for _, input := range runManifest.Inputs {
if input.Kind != descriptor.ManifestKind {
continue
}
path, err := artifacts.SessionNotariusReferenceSnapshotPath(
sessionPathsForEnv(env, runManifest.SessionID), input.Checksum, filepath.Base(input.Path),
)
transcriptPath := m.Stages["trim"].Outputs[0].LocalPath
if err := os.WriteFile(transcriptPath, transcript, 0644); err != nil {
t.Fatal(err)
}
checksum, err := artifacts.SHA256File(transcriptPath)
if err != nil {
t.Fatal(err)
}
m.Stages["trim"].Outputs[0].Checksum = checksum
party, err := os.ReadFile(filepath.Join(examples, "party.yml"))
if err != nil {
t.Fatal(err)
}
glossary, err := os.ReadFile(filepath.Join(examples, "glossary.yml"))
if err != nil {
t.Fatal(err)
}
recordPreparedExtractInput(t, env, m, artifactpolicy.SourceInputParty, string(party))
recordPreparedExtractInput(t, env, m, artifactpolicy.SourceInputGlossaryCombined, string(glossary))
outputs := map[string]config.NotariusOutputConfig{}
for _, lane := range []string{"item-registry", "npc-registry", "location-registry", "scene-descriptions", "item-occurrences", "spells", "combat-turns", "npc-occurrences", "location-occurrences", "enemy-events"} {
outputs[strings.ReplaceAll(lane, "-", "_")] = config.NotariusOutputConfig{LaneID: lane}
}
cache := "auto"
env.Config.Pipeline.Notarius = &config.NotariusConfig{Enabled: true, Binary: binary, ConfigPath: filepath.Join(configDir, "config.yml"), PipelineID: "dnd-session", Timeout: "2m", WorkingDirectory: configDir, Cache: &cache, Outputs: outputs, References: map[string]string{"party": artifactpolicy.SourceInputParty, "glossary": artifactpolicy.SourceInputGlossaryCombined, "spell_catalog": artifactpolicy.SourceInputGlossaryCombined}}
runner := notarius.NewSubprocessRunner()
env.Notarius = runner
paths := sessionPathsForEnv(env, m.SessionID)
probe, err := BuildNotariusReadiness(env.Config, paths, m, filepath.Join(root, "probe"), true, false)
if err != nil {
t.Fatal(err)
}
ready, err := runner.Preflight(context.Background(), probe.Request)
if err != nil || !ready.Ready {
t.Fatalf("readiness: %+v %v", ready, err)
}
var requestCounts []int64
for i, force := range []bool{false, false, true} {
before := calls.Load()
m.RunID = fmt.Sprintf("20260916T01010%dZ-a000000%d", i+1, i+1)
env.Force = force
result, err := (extractStage{}).Run(context.Background(), env, m)
if err != nil {
t.Fatalf("resolve integration snapshot: %v", err)
t.Fatalf("extraction %d: %v", i, err)
}
return path
}
t.Fatalf("prepared input %q not found", sourceID)
return ""
}
func runNotariusIntegrationExtraction(t *testing.T, env *Env, runManifest *manifest.Manifest, runID string, force bool) notariusIntegrationRunManifest {
t.Helper()
runManifest.RunID = runID
env.Force = force
result, err := (extractStage{}).Run(context.Background(), env, runManifest)
if err != nil {
reportPath := artifacts.SessionRunNotariusReportPathForCampaign(env.Config.Pipeline.Workspace.Root, runManifest.Campaign, runManifest.SessionID, runID)
if data, readErr := os.ReadFile(reportPath); readErr == nil {
t.Logf("failed Notarius receipt: %s", data)
requestCounts = append(requestCounts, calls.Load()-before)
if len(result.Outputs) != len(outputs) {
t.Fatalf("promoted %d lanes, want %d", len(result.Outputs), len(outputs))
}
t.Fatalf("extract run %q: %v", runID, err)
}
bundleRoot, ok := result.Metadata["bundle_root"].(string)
if !ok || bundleRoot == "" {
t.Fatalf("extract metadata bundle_root = %#v", result.Metadata["bundle_root"])
}
data, err := os.ReadFile(filepath.Join(bundleRoot, "manifest.json"))
if err != nil {
t.Fatalf("read Notarius manifest: %v", err)
}
var published notariusIntegrationRunManifest
if err := json.Unmarshal(data, &published); err != nil {
t.Fatalf("decode Notarius manifest: %v", err)
}
return published
}
type notariusIntegrationRunManifest struct {
ChunkPlan *struct {
Action string `json:"action"`
SourceDigest string `json:"source_digest"`
} `json:"chunk_plan"`
CheckpointDecisions []struct {
Stage string `json:"stage"`
LaneID string `json:"lane_id"`
Category string `json:"category"`
ReasonCode string `json:"reason_code"`
} `json:"checkpoint_decisions"`
}
func assertNotariusIntegrationDecision(t *testing.T, published notariusIntegrationRunManifest, stageName, laneID, category, reasonCode string) {
t.Helper()
for _, decision := range published.CheckpointDecisions {
if decision.Stage == stageName && decision.LaneID == laneID {
if decision.Category != category || reasonCode != "" && decision.ReasonCode != reasonCode {
t.Fatalf("checkpoint decision for %s/%s = %#v, want category %q reason %q", stageName, laneID, decision, category, reasonCode)
for _, item := range result.Outputs {
if filepath.Dir(item.AbsolutePath) != paths.ArtifactsDir {
t.Fatalf("non-flat product %q", item.AbsolutePath)
}
return
}
}
t.Fatalf("checkpoint decision for %s/%s not found in %#v", stageName, laneID, published.CheckpointDecisions)
t.Logf("provider calls for initial, reused, refreshed runs: %v", requestCounts)
if requestCounts[0] == 0 || requestCounts[1] != 0 || requestCounts[2] == 0 {
t.Fatalf("cache reuse or refresh did not produce the expected provider calls: %v", requestCounts)
}
}