diff --git a/.scratch/legacy-slice-undo-20261015/spec.md b/.scratch/legacy-slice-undo-20261015/spec.md new file mode 100644 index 00000000..b83eec84 --- /dev/null +++ b/.scratch/legacy-slice-undo-20261015/spec.md @@ -0,0 +1,63 @@ +# Legacy editable task slice undo + +Status: resolved + +Baseline52dcb53a. User reports repeated slice_edit_restoration_unavailable; +real handler diagnostic reproduced normal edit200, undo409 with missing workflow, +and undo200 when only phase=annotate was added. Existing client keeps history on +failed write, so repeated undo retries the same rejected snapshot. + +Honor ADR0001/0007: owned editable first-pass/rework tasks may undo persisted +structure edits in the same task/phase. Infer legacy readiness only from current +server-owned partition/generation evidence when sliceWorkflow is absent; do not +accept a client-invented phase or mutate old records to fabricate completion. +Explicit incomplete workflow, queued/running/failed jobs, pending submission, +review ownership/stage and version/frame/coverage/archive guards remain enforced. +No schema migration, bulk backfill, online writes, push, PR or deployment. +Verify real HTTP undo/redo/CAS and local snapshot replica, keep unrelated root +changes intact. Previous production deployment approval is consumed. + + +## Answer + +The restoration endpoint required an explicit slice/annotate workflow phase; +the application endpoint already allowed pre-workflow records. Diagnostics and +permanent regression cases reproduce edit200 → undo409 on unchanged legacy +record; adding only phase changed undo to200 before the fix. + +Restoration now retains explicit phase/initial-slice behavior, and for absent +workflow recognizes a valid server-owned slice partition backed by existing +materialization/revision evidence, or a complete non-full-video action partition +using existing confirmation readiness. Generation evidence also allows partially +edited and all-discarded tracks. Evidence is read before decoding the incoming +snapshot; the client cannot manufacture eligibility. No workflow marker is +written. Explicit incomplete workflow remains rejected. Queued/running/processing +and failed workflow/jobs are blocked consistently with the edit-application +endpoint. Existing ownership/stage, pending submission, CAS, frame/coverage, +status and canonical discard archive validation is retained. + +Verification: + +- New HTTP regression failed before change in all4 first-pass/rework + stored + workspace/draft cases; now edit → undo → redo → undo succeeds, stale versions + reject without writes, and a new handler reads the persisted result. +- Additional16 scenarios cover generated all-discarded/partial tracks, absent + server evidence, full-video proof requirement, incomplete/failed workflow, + queued/running/processing/failed jobs, pending submission, review and nonowner. + Rejected records are compared to their actual normalized stored preimage. +- Focused API legacy confirmation/restoration/application/discard regressions + pass. Lint and Go build./... pass; full Go baseline gate rerun has70 exact + known failures and no new failures. First run had one worker concurrent claim + case failure; isolated rerun passed, worker/store/domain sources are byte + unchanged from52dcb53a. Both gate logs retained, baseline not edited. +- Actual local snapshot27018 + API3005, separate synthetic rework task + legacy-undo-20261015-task: split8→9 at version2; undo9→8/version3; + redo8→9/version4; undo9→8/version5. Fresh GET retains8 slices, original action + content unchanged, workflow marker remains absent. Existing demo not modified. +- Logs in this worktree local-data/undo-phase-fix; local replica artifacts under + main-root local-data/verification/legacy-undo-20261015 (ignored). Original local + API/processor restored after gate; updated API3005 remains for trials. + +Compatibility: no new request fields/schema or production migration. Rollback +reverts legacy undo eligibility while keeping saved snapshots readable; it does +not undo customer edits. No production write, push, PR update or deployment. diff --git a/docs/adr/0001-annotation-undo-stage-boundary.md b/docs/adr/0001-annotation-undo-stage-boundary.md index 82c408c8..6451578b 100644 --- a/docs/adr/0001-annotation-undo-stage-boundary.md +++ b/docs/adr/0001-annotation-undo-stage-boundary.md @@ -3,3 +3,6 @@ 标注员需要撤销误切、误删以及已经保存的描述,但切片生成和送检会触发异步产物发布、当前版本替换及审核阶段流转。撤销因此限于当前任务、当前编辑阶段;已保存内容通过受当前版本与归属校验保护的写入恢复,开始生成、送检或切换任务截断历史(2026-10-13 修订:原列于截断触发项中的“重新切片”已随入口停用移除,结构编辑撤销扩展到逐片标注阶段,见 [ADR 0007](0007-inplace-slice-editing-replaces-reslice.md)),避免把普通编辑撤销扩大为媒体版本恢复或审核流程回滚。 这一取舍保留了日常纠错能力,同时要求服务端写入成功后才宣告撤销成功;首版撤销历史仅保留在当前页面会话,刷新后从后端已保存内容恢复,不恢复撤销栈。用户于 2026-09-17 的两轮设计确认中接受此边界;详细交互与验收见 [标注键盘工作流设计](../../.scratch/annotation-keyboard-workflow/spec.md)。 + + +2026-10-15 旧任务兼容补充:缺少 `sliceWorkflow` 的历史任务,若服务端保存的完整切片分区有可靠生成记录,或非全视频任务有完整标注分区证据,可在当前标注员、当前阶段内撤销/重做。判定只读取服务端记录,不以客户端撤销快照充当证明,也不补写阶段标记。显式但不完整的工作流、生成中/失败处理任务、待完成送检和审核阶段仍禁止恢复;版本、归属、真实帧、覆盖及舍弃审计校验保持生效。 diff --git a/internal/api/slice_edit_legacy_undo_test.go b/internal/api/slice_edit_legacy_undo_test.go new file mode 100644 index 00000000..b9763c29 --- /dev/null +++ b/internal/api/slice_edit_legacy_undo_test.go @@ -0,0 +1,157 @@ +package api + +import ( + "encoding/json" + "net/http" + "testing" + + "droboticflow/internal/domain" +) + +func TestLegacySliceEditUndoRedoAfterSuccessfulEdit(t *testing.T) { + for _, rework := range []bool{false, true} { + for _, key := range []string{"annotationWorkspace", "annotationDraft"} { + t.Run(map[bool]string{false: "first-pass", true: "rework"}[rework]+"/"+key, func(t *testing.T) { + f := continuousFixture(t) + item := f.item + item.CurrentRevision = 1 + if rework { + item.ReviewRound = 1 + task := f.task + task.Status = domain.AnnotationTaskStatusRework + if err := f.store.UpsertAnnotationTask(f.ctx, task); err != nil { + t.Fatal(err) + } + } + delete(item.Subject.Payload, "sliceWorkflow") + original := []domain.SliceSegment{{ID: "whole", Name: "测试切片", Start: 0, End: 10}} + split := []domain.SliceSegment{{ID: "left", Name: "测试切片", Start: 0, End: 5}, {ID: "right", Name: "测试切片", Start: 5, End: 10}} + actions := []domain.AnnotationSegment{{ID: "a", Start: 0, End: 5, Status: "pending"}, {ID: "b", Start: 5, End: 10, Status: "described", Description: "保留描述"}} + item.Subject.Payload[key] = map[string]any{"sliceSegments": original, "segments": actions} + if err := f.store.UpsertHumanItem(f.ctx, item); err != nil { + t.Fatal(err) + } + path := "/api/plugins/annotation-qa/tasks/" + f.task.ID + body := combinedAnnotationDraftInput{Version: item.Version, SliceSegments: split, Segments: actions} + r := f.request("POST", path+"/slice-edit-applications", f.annotator, sliceEditApplicationInput{ApplicationID: "legacy-split", combinedAnnotationDraftInput: body}) + if r.Code != 200 { + t.Fatalf("edit %d %s", r.Code, r.Body.String()) + } + var response struct { + Item domain.HumanItemRecord `json:"item"` + Workspace combinedAnnotationDraftInput `json:"workspace"` + } + if err := json.Unmarshal(r.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + for _, target := range [][]domain.SliceSegment{original, split, original} { + body.Version = response.Item.Version + body.SliceSegments = target + r = f.request("POST", path+"/slice-edit-restorations", f.annotator, body) + if r.Code != 200 { + t.Fatalf("undo/redo %d %s", r.Code, r.Body.String()) + } + if err := json.Unmarshal(r.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + if len(response.Workspace.SliceSegments) != len(target) || len(response.Workspace.Segments) != 2 || response.Workspace.Segments[1].Description != "保留描述" { + t.Fatal("snapshot or actions lost") + } + if response.Item.Subject.Payload["sliceWorkflow"] != nil { + t.Fatal("legacy restore invented workflow") + } + // A lost response cannot be retried with the old version and overwrite the new state. + stale := f.request("POST", path+"/slice-edit-restorations", f.annotator, body) + if stale.Code != http.StatusConflict { + t.Fatalf("stale accepted %d", stale.Code) + } + saved, _ := f.store.GetHumanItem(f.ctx, item.ID) + if saved.Version != response.Item.Version { + t.Fatal("stale changed version") + } + f.handler = NewHandler(f.store, nil) + } + }) + } + } +} + +func TestLegacySliceUndoUsesStoredEvidenceAndKeepsSafetyGuards(t *testing.T) { + for _, scenario := range []string{"all-discarded-generated", "partial-generated", "client-only-evidence", "no-actions-no-generation", "full-video-no-generation", "explicit-missing-phase", "explicit-materializing", "workflow-failed", "job-queued", "job-running", "job-processing", "job-failed", "explicit-phase-job-failed", "submission", "review-stage", "nonowner"} { + t.Run(scenario, func(t *testing.T) { + f := continuousFixture(t) + item := f.item + item.CurrentRevision = 1 + delete(item.Subject.Payload, "sliceWorkflow") + slices := []domain.SliceSegment{{ID: "whole", Name: "测试切片", Start: 0, End: 10}} + actions := []domain.AnnotationSegment{{ID: "a", Start: 0, End: 10, Status: "pending"}} + item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": slices, "segments": actions} + want := http.StatusConflict + switch scenario { + case "all-discarded-generated": + slices[0].DeliveryDisposition = "discard" + slices[0].DiscardReason = "历史舍弃" + actions = nil + item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": slices, "segments": actions} + item.Subject.Payload["materialization"] = map[string]any{"status": "completed", "revision": 1, "artifactId": "server-generated", "runId": f.task.RunID} + want = 200 + case "partial-generated": + actions = actions[:1] + actions[0].End = 4 + item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": slices, "segments": actions} + item.Subject.Payload["materialization"] = map[string]any{"status": "completed", "revision": 1, "artifactId": "server-generated", "runId": f.task.RunID} + want = 200 + case "client-only-evidence": + delete(item.Subject.Payload, "annotationWorkspace") + case "no-actions-no-generation": + item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": slices} + case "full-video-no-generation": + task := f.task + task.SourceIsFullVideo = true + if err := f.store.UpsertAnnotationTask(f.ctx, task); err != nil { + t.Fatal(err) + } + case "explicit-missing-phase": + item.Subject.Payload["sliceWorkflow"] = map[string]any{"status": "completed"} + case "explicit-materializing": + item.Subject.Payload["sliceWorkflow"] = map[string]any{"phase": "materializing"} + case "workflow-failed": + item.Subject.Payload["sliceWorkflow"] = map[string]any{"phase": "annotate", "status": "failed"} + case "job-queued", "job-running", "job-processing", "job-failed": + item.ProcessingJob = &domain.AnnotationProcessingJob{Status: scenario[4:]} + case "explicit-phase-job-failed": + item.Subject.Payload["sliceWorkflow"] = map[string]any{"phase": "annotate"} + item.ProcessingJob = &domain.AnnotationProcessingJob{Status: "failed"} + case "submission": + item.PendingCombinedSubmissionID = "pending" + case "review-stage": + item.CurrentStageID = domain.FanyuV58StageQualityReview + case "nonowner": + item.AssignedUserID = f.admin.ID + } + if err := f.store.UpsertHumanItem(f.ctx, item); err != nil { + t.Fatal(err) + } + storedBefore, err := f.store.GetHumanItem(f.ctx, item.ID) + if err != nil { + t.Fatal(err) + } + before, _ := json.Marshal(storedBefore) + r := f.request("POST", "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-edit-restorations", f.annotator, combinedAnnotationDraftInput{Version: item.Version, SliceSegments: slices, Segments: actions}) + if r.Code != want { + t.Fatalf("want %d got %d %s", want, r.Code, r.Body.String()) + } + saved, _ := f.store.GetHumanItem(f.ctx, item.ID) + if want == 200 { + if saved.Version != item.Version+1 || saved.Subject.Payload["sliceWorkflow"] != nil { + t.Fatal("restore failed or invented workflow") + } + } else { + after, _ := json.Marshal(saved) + if string(before) != string(after) { + t.Fatal("rejected restore mutated server state") + } + } + }) + } +} diff --git a/internal/api/slice_edit_restoration.go b/internal/api/slice_edit_restoration.go index 26b67b18..b74b2b44 100644 --- a/internal/api/slice_edit_restoration.go +++ b/internal/api/slice_edit_restoration.go @@ -35,24 +35,34 @@ func (s *server) handleSliceEditRestoration(w http.ResponseWriter, r *http.Reque workflow := mapValue(item.Subject.Payload["sliceWorkflow"]) busy := false if job := item.ProcessingJob; job != nil { - busy = job.Status == "queued" || job.Status == "running" || job.Status == "processing" + busy = job.Status == "queued" || job.Status == "running" || job.Status == "processing" || job.Status == "failed" } - // Newly claimed captures have no workflow until the first generation. They - // are editable, but an incomplete workflow or generated media is not enough - // evidence to infer slicing after the phase field has been lost. + // Explicit workflow markers stay authoritative. For pre-workflow records, + // use server-owned persisted evidence, never the incoming undo snapshot. initialSlice := len(workflow) == 0 && item.CurrentRevision == 0 && len(mapValue(item.Subject.Payload["materialization"])) == 0 && item.ProcessingJob == nil - // Ticket 07 (spec §3.5): in-place structure edits also happen in the - // annotate pass (unlocked by ticket 02), so their undo/redo replays there - // too. Materializing/processing states still refuse — a snapshot write - // must never race a generation. - editablePhase := func() bool { - switch stringValue(workflow["phase"]) { - case "slice", "annotate": - return true + phase := stringValue(workflow["phase"]) + editablePhase := phase == "slice" || phase == "annotate" || initialSlice + blocked := busy + switch stringValue(workflow["status"]) { + case "processing", "running", "materializing", "queued", "failed": + blocked = true + } + if !editablePhase && !blocked && item.Subject.Payload["sliceWorkflow"] == nil { + storedSlices := decodeMaterializationValue[domain.SliceSegment](annotationWorkspacePayload(item)["sliceSegments"]) + if len(storedSlices) > 0 && len(validateSliceSegments(storedSlices, *task)) == 0 && len(validateCompleteSliceCoverage(storedSlices, *task)) == 0 { + // Generation evidence also covers all-discarded or partially edited + // tracks, which need not satisfy final annotation confirmation yet. + editablePhase, err = s.hasLegacyAnnotationGenerationEvidence(r.Context(), *task, item) + if err == nil && !editablePhase && !task.SourceIsFullVideo { + editablePhase, err = s.legacyAnnotationConfirmationReady(r.Context(), *task, item) + } + if err != nil { + renderError(w, 500, err) + return + } } - return initialSlice - }() - if !editablePhase || stringValue(workflow["status"]) == "processing" || stringValue(workflow["status"]) == "running" || stringValue(workflow["status"]) == "materializing" || stringValue(workflow["status"]) == "queued" || busy { + } + if !editablePhase || blocked { renderJSON(w, 409, map[string]string{"code": "slice_edit_restoration_unavailable", "error": "仅可在可编辑的切片或标注阶段撤销或重做切片"}) return }