droboticflow-new/internal/api/slice_snapshot_integrity_test.go

247 lines
11 KiB
Go

package api
import (
"context"
"net/http"
"reflect"
"strings"
"testing"
"time"
"droboticflow/internal/domain"
)
func seedNewerSliceSnapshot(t *testing.T, f combinedDraftFixture) domain.HumanItemRecord {
t.Helper()
h := seedFailedSliceRetry(t, f)
draft := map[string]any{}
for k, v := range annotationWorkspacePayload(&h) {
draft[k] = v
}
draft["sliceSegments"] = []domain.SliceSegment{{ID: "a", Name: "测试切片", Start: 0, End: 3}, {ID: "b", Name: "测试切片", Start: 3, End: 4}}
draft["segments"] = []domain.AnnotationSegment{{ID: "new-action", Start: 0, End: 3, Status: "pending", Dictionary: &domain.DictionarySelection{ID: "historical-action", Kind: "action", Version: 2, Name: "历史动作", Tags: []string{"原标签"}}}}
draft["savedAt"], draft["savedVersion"] = nowISO(), h.Version
h.Subject.Payload["annotationDraft"] = draft
if err := f.store.UpsertHumanItem(f.ctx, h); err != nil {
t.Fatal(err)
}
stored, err := f.store.GetHumanItem(f.ctx, h.ID)
if err != nil || stored == nil {
t.Fatal("saved fixture unavailable", err)
}
return *stored
}
func TestFailedSliceRetryRejectsDifferentSavedSnapshot(t *testing.T) {
t.Setenv("ANNOTATION_PROCESSOR_MODE", "external")
f, _ := annotationProcessorFixture(t)
h := seedNewerSliceSnapshot(t, f)
before, _ := f.store.GetHumanItem(f.ctx, h.ID)
r := f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-confirmations", f.annotator, map[string]any{"version": h.Version, "retryFailed": true})
if r.Code != http.StatusConflict || !strings.Contains(r.Body.String(), "slice_retry_snapshot_conflict") {
t.Fatalf("stale snapshot accepted: %d %s", r.Code, r.Body.String())
}
after, _ := f.store.GetHumanItem(f.ctx, h.ID)
if !reflect.DeepEqual(before, after) {
t.Fatal("rejected retry changed either retained snapshot")
}
state, err := (&server{store: f.store}).annotationEditorStateForTask(f.ctx, f.task, after)
if err != nil || !state.CanReconfirmSavedGeneration {
t.Fatalf("explicit saved confirmation not offered: %+v %v", state, err)
}
}
func TestReconfirmSavedSlicesPreservesSelectedBoundariesAcrossRestart(t *testing.T) {
t.Setenv("ANNOTATION_PROCESSOR_MODE", "external")
f, root := annotationProcessorFixture(t)
h := seedNewerSliceSnapshot(t, f)
draft := mapValue(h.Subject.Payload["annotationDraft"])
r := f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-confirmations", f.annotator, map[string]any{"version": h.Version, "reconfirmSaved": true, "retryWorkspace": map[string]any{"segments": []any{}}, "sliceSegments": []any{}})
if r.Code != http.StatusAccepted {
t.Fatalf("explicit reconfirmation: %d %s", r.Code, r.Body.String())
}
queued, _ := f.store.GetHumanItem(f.ctx, h.ID)
if !reflect.DeepEqual(mapValue(queued.Subject.Payload["annotationDraft"]), draft) {
t.Fatal("queueing changed saved draft")
}
now := time.Now().UTC()
old, _ := f.store.ClaimAnnotationProcessing(f.ctx, "snapshot-old", now.Format(time.RFC3339Nano), now.Add(-time.Second).Format(time.RFC3339Nano))
claimed, _ := f.store.ClaimAnnotationProcessing(f.ctx, "snapshot-new", now.Format(time.RFC3339Nano), now.Add(time.Minute).Format(time.RFC3339Nano))
if old == nil || claimed == nil || claimed.ProcessingJob.Attempt != 2 {
t.Fatal("reconfirmation not recoverable after restart")
}
s := &server{store: f.store, workspaceMountPath: root, externalAnnotationProcessor: true}
s.executeAnnotationJob(context.Background(), *claimed)
done, _ := f.store.GetHumanItem(f.ctx, h.ID)
if done.ProcessingJob.Status != "completed" {
t.Fatalf("failed reconfirmation: %+v", done.ProcessingJob)
}
workspace := annotationWorkspacePayload(done)
slices := decodeMaterializationValue[domain.SliceSegment](workspace["sliceSegments"])
if len(slices) != 2 || slices[0].End != 3 || slices[1].Start != 3 {
t.Fatalf("selected boundary changed: %+v", slices)
}
if !reflect.DeepEqual(decodeMaterializationValue[domain.AnnotationSegment](workspace["segments"]), decodeMaterializationValue[domain.AnnotationSegment](draft["segments"])) {
t.Fatal("reconfirmation erased actions")
}
if stringValue(mapValue(done.Subject.Payload["sliceWorkflow"])["snapshotContentSha256"]) == "" || workspace["confirmationSnapshotSha256"] == nil {
t.Fatal("confirmation identity missing from generated result")
}
}
func TestFailedSliceRetryIgnoresAutosaveMetadataOnly(t *testing.T) {
t.Setenv("ANNOTATION_PROCESSOR_MODE", "external")
f, _ := annotationProcessorFixture(t)
h := seedFailedSliceRetry(t, f)
draft := map[string]any{}
for k, v := range annotationWorkspacePayload(&h) {
draft[k] = v
}
draft["savedAt"], draft["savedVersion"] = nowISO(), h.Version
h.Subject.Payload["annotationDraft"] = draft
if err := f.store.UpsertHumanItem(f.ctx, h); err != nil {
t.Fatal(err)
}
r := f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-confirmations", f.annotator, map[string]any{"version": h.Version, "retryFailed": true})
if r.Code != http.StatusAccepted {
t.Fatalf("metadata-only autosave blocked unchanged retry: %d %s", r.Code, r.Body.String())
}
}
func TestReconfirmSavedSlicesRejectsAmbiguousEvidence(t *testing.T) {
t.Setenv("ANNOTATION_PROCESSOR_MODE", "external")
for _, reason := range []string{"wrong-owner", "future-version", "missing-time", "stale-client"} {
t.Run(reason, func(t *testing.T) {
f, _ := annotationProcessorFixture(t)
h := seedNewerSliceSnapshot(t, f)
draft := mapValue(h.Subject.Payload["annotationDraft"])
version := h.Version
switch reason {
case "wrong-owner":
draft["userId"] = f.reviewer.ID
case "future-version":
draft["savedVersion"] = h.Version + 1
case "missing-time":
delete(draft, "savedAt")
case "stale-client":
version--
}
h.Subject.Payload["annotationDraft"] = draft
if err := f.store.UpsertHumanItem(f.ctx, h); err != nil {
t.Fatal(err)
}
before, _ := f.store.GetHumanItem(f.ctx, h.ID)
r := f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-confirmations", f.annotator, map[string]any{"version": version, "reconfirmSaved": true, "snapshotContentSha256": "forged"})
if r.Code != http.StatusConflict && r.Code != http.StatusUnprocessableEntity {
t.Fatalf("unsafe reconfirmation: %d %s", r.Code, r.Body.String())
}
after, _ := f.store.GetHumanItem(f.ctx, h.ID)
if !reflect.DeepEqual(before, after) {
t.Fatal("rejected reconfirmation changed saved data")
}
})
}
}
func TestLegacyFailedSliceRetryUsesFrozenJobRatherThanCurrentDraft(t *testing.T) {
t.Setenv("ANNOTATION_PROCESSOR_MODE", "external")
f, _ := annotationProcessorFixture(t)
h := seedNewerSliceSnapshot(t, f)
original := annotationWorkspacePayload(&h)
delete(h.Subject.Payload, "annotationWorkspace")
h.ProcessingJob = &domain.AnnotationProcessingJob{ID: "old-job", Kind: "slice", Status: "failed", Input: map[string]any{"retryFailed": true, "retryWorkspace": original, "sliceSegments": original["sliceSegments"]}}
if err := f.store.UpsertHumanItem(f.ctx, h); err != nil {
t.Fatal(err)
}
before, _ := f.store.GetHumanItem(f.ctx, h.ID)
r := f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-confirmations", f.annotator, map[string]any{"version": h.Version, "retryFailed": true})
if r.Code != http.StatusConflict || !strings.Contains(r.Body.String(), "slice_retry_snapshot_conflict") {
t.Fatalf("old frozen job input ignored: %d %s", r.Code, r.Body.String())
}
after, _ := f.store.GetHumanItem(f.ctx, h.ID)
if !reflect.DeepEqual(before, after) {
t.Fatal("rejection changed either old-job or draft evidence")
}
}
func TestDraftOnlyReconfirmationRequiresOwnedDatedSavedEvidence(t *testing.T) {
t.Setenv("ANNOTATION_PROCESSOR_MODE", "external")
for _, reason := range []string{"wrong-owner", "future-version", "missing-time"} {
t.Run(reason, func(t *testing.T) {
f, _ := annotationProcessorFixture(t)
h := seedNewerSliceSnapshot(t, f)
delete(h.Subject.Payload, "annotationWorkspace")
draft := mapValue(h.Subject.Payload["annotationDraft"])
switch reason {
case "wrong-owner":
draft["userId"] = f.reviewer.ID
case "future-version":
draft["savedVersion"] = h.Version + 1
case "missing-time":
delete(draft, "savedAt")
}
h.Subject.Payload["annotationDraft"] = draft
if err := f.store.UpsertHumanItem(f.ctx, h); err != nil {
t.Fatal(err)
}
before, _ := f.store.GetHumanItem(f.ctx, h.ID)
r := f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-confirmations", f.annotator, map[string]any{"version": h.Version, "reconfirmSaved": true})
if r.Code != http.StatusUnprocessableEntity {
t.Fatalf("unverified draft accepted without baseline: %d %s", r.Code, r.Body.String())
}
after, _ := f.store.GetHumanItem(f.ctx, h.ID)
if !reflect.DeepEqual(before, after) {
t.Fatal("invalid draft-only confirmation mutated state")
}
})
}
}
func TestPreUpgradeSliceJobCannotReplaceNewerSavedSnapshot(t *testing.T) {
t.Setenv("ANNOTATION_PROCESSOR_MODE", "external")
f, root := annotationProcessorFixture(t)
h := seedFailedSliceRetry(t, f)
r := f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-confirmations", f.annotator, map[string]any{"version": h.Version, "retryFailed": true})
if r.Code != http.StatusAccepted {
t.Fatal(r.Code, r.Body.String())
}
queued, _ := f.store.GetHumanItem(f.ctx, h.ID)
// Simulate an already queued job from an old API, without new proof fields.
delete(queued.ProcessingJob.Input, "snapshotContentSha256")
flow := mapValue(queued.Subject.Payload["sliceWorkflow"])
delete(flow, "snapshotContentSha256")
queued.Subject.Payload["sliceWorkflow"] = flow
draft := map[string]any{}
for k, v := range annotationWorkspacePayload(queued) {
draft[k] = v
}
draft["sliceSegments"] = []domain.SliceSegment{{ID: "a", Name: "测试切片", Start: 0, End: 3}, {ID: "b", Name: "测试切片", Start: 3, End: 4}}
draft["segments"] = []domain.AnnotationSegment{{ID: "new-action", Start: 0, End: 3, Status: "pending"}}
draft["savedAt"], draft["savedVersion"] = nowISO(), queued.Version
queued.Subject.Payload["annotationDraft"] = draft
if err := f.store.UpsertHumanItem(f.ctx, *queued); err != nil {
t.Fatal(err)
}
stored, _ := f.store.GetHumanItem(f.ctx, h.ID)
before := annotationWorkspacePayload(stored)
draft = mapValue(stored.Subject.Payload["annotationDraft"])
now := time.Now().UTC()
claimed, _ := f.store.ClaimAnnotationProcessing(f.ctx, "snapshot-worker", now.Format(time.RFC3339Nano), now.Add(time.Minute).Format(time.RFC3339Nano))
if claimed == nil {
t.Fatal("job unavailable")
}
s := &server{store: f.store, workspaceMountPath: root, externalAnnotationProcessor: true}
s.executeAnnotationJob(context.Background(), *claimed)
done, _ := f.store.GetHumanItem(f.ctx, h.ID)
if done.ProcessingJob.Status != "failed" {
t.Fatalf("old snapshot published: %+v", done.ProcessingJob)
}
if !reflect.DeepEqual(annotationWorkspacePayload(done), before) || !reflect.DeepEqual(mapValue(done.Subject.Payload["annotationDraft"]), draft) {
t.Fatal("obsolete completion replaced retained content")
}
revisions, err := f.store.ListSliceRevisions(f.ctx, f.task.OrganizationID, f.task.ID)
if err != nil || len(revisions) != 0 {
t.Fatalf("obsolete revision published: %d %v", len(revisions), err)
}
}