🐛 Preserve discard evidence and persist slice undo history

This commit is contained in:
eust-w 2026-09-22 00:47:33 +08:00
parent 94a98efc03
commit d84b83c94d
10 changed files with 1300 additions and 11 deletions

View File

@ -34,3 +34,9 @@
后端从同一任务已保存的切片解析继承关系,覆盖客户端提交的审计字段;不会凭空接受新舍弃原因。支持连续多次未保存切分及其撤销、重新保存。原始归档描述继续保留;恢复子片段时只激活其当前时间范围内的内容,裁切后的描述使用不同 ID,避免跨越相邻子片段或 ID 冲突。已生成媒体的标注阶段仍固定切片边界。
回归入口补充:`TestDiscardedSlice*`、`TestDiscardInheritance*` 与 `tests/browser/discarded-slice-editing.mjs`。浏览器通过真实保存接口验证舍弃后继续编辑及刷新回读,仅允许显式指定隔离验收项目。
2026-09-22 撤销修正:舍弃操作保存整组分区时,将此前切片编辑标记为已持久化;撤销和重做这些编辑通过 `POST /api/plugins/annotation-qa/tasks/{id}/slice-edit-restorations` 保存权威工作区,成功后才推进历史。未保存编辑继续在当前页面撤销。接口仅允许当前领取人在可编辑切片阶段操作,校验版本、完整覆盖和帧边界,不触发切片生成;历史审计字段由服务端当前证据覆盖,舍弃判断仍只能通过显式舍弃/恢复接口变更。
恢复舍弃片段时,完整原始归档与本次实际恢复的描述由服务端分别保存;再次舍弃时,未改动的恢复结果可以恢复完整归档,实际编辑或删除则覆盖已暴露的范围,避免旧描述复活。切片合回父片段时采用子片段当前证据;恢复证据受阶段和媒体版本限制。该修正预防新的归档丢失,不自动重建此前已经丢失的历史内容。
补充回归:`TestPR5ReviewArchiveBoundaryUndo`、`TestArchive*`、`TestSliceEditRestoration*` 和 `tests/frontend/annotation-history.test.mjs`。本地隔离内存 API 与浏览器已验证切分→舍弃→连续撤销→重做→再次撤销→刷新,页面与 API 分区一致;这不替代公司环境验收。

View File

@ -1395,6 +1395,7 @@ func NewHandlerWithConfig(dataStore store.Store, aiService ai.Service, appConfig
router.Post("/api/plugins/annotation-qa/tasks", instance.handleAnnotationTaskCreate)
router.Put("/api/plugins/annotation-qa/tasks/{id}/drafts", instance.handleCombinedAnnotationDraftPut)
router.Post("/api/plugins/annotation-qa/tasks/{id}/annotation-confirmations", instance.handleAnnotationConfirmationCreate)
router.Post("/api/plugins/annotation-qa/tasks/{id}/slice-edit-restorations", instance.handleSliceEditRestoration)
router.Post("/api/plugins/annotation-qa/tasks/{id}/slice-dispositions", instance.handleSliceDisposition)
router.Post("/api/plugins/annotation-qa/tasks/{id}/slice-confirmations", instance.handleSliceConfirmationCreate)
router.Post("/api/plugins/annotation-qa/tasks/{id}/slice-reset", instance.handleSliceResetCreate)

View File

@ -5,6 +5,7 @@ import (
"fmt"
"math"
"net/http"
"reflect"
stdslices "slices"
"strings"
@ -55,6 +56,7 @@ func (s *server) canonicalSliceDispositionState(ctx context.Context, item *domai
}
}
next, issues := canonicalDispositions(previous, slices)
applySliceArchiveEdits(next, currentSliceArchiveEdits(item))
// Generated media owns its boundaries. Only the slicing stage can repartition
// discarded evidence; changing its decision remains an explicit operation.
if stringValue(mapValue(item.Subject.Payload["sliceWorkflow"])["phase"]) == "annotate" {
@ -81,9 +83,15 @@ func canonicalDispositions(previous, slices []domain.SliceSegment) ([]domain.Sli
old := map[string]domain.SliceSegment{}
proposed := map[string]domain.SliceSegment{}
for _, p := range previous {
if _, duplicate := old[p.ID]; duplicate {
return nil, []validationIssue{{Field: "sliceSegments", Message: "已保存的切片 ID 重复"}}
}
old[p.ID] = p
}
for _, candidate := range slices {
if _, duplicate := proposed[candidate.ID]; duplicate {
return nil, []validationIssue{{Field: "sliceSegments", Message: "切片 ID 必须唯一"}}
}
proposed[candidate.ID] = candidate
}
next := append([]domain.SliceSegment(nil), slices...)
@ -110,7 +118,7 @@ func canonicalDispositions(previous, slices []domain.SliceSegment) ([]domain.Sli
if (!exists && c.IsDiscarded()) || (exists && (sliceDisposition(p) != sliceDisposition(c) || p.DiscardReason != c.DiscardReason)) {
issues = append(issues, validationIssue{Field: fmt.Sprintf("sliceSegments.%d.deliveryDisposition", i), Code: "explicit_disposition_required", Message: "请通过舍弃/恢复操作保存切片用途"})
}
if c.IsDiscarded() && exists {
if exists {
next[i].SourceIDs = append([]string(nil), p.SourceIDs...)
if inherited {
next[i].SourceIDs = append([]string{p.ID}, next[i].SourceIDs...)
@ -131,19 +139,28 @@ func canonicalDispositions(previous, slices []domain.SliceSegment) ([]domain.Sli
next[i].DiscardReasonNote = p.DiscardReasonNote
next[i].DiscardedByUserID = p.DiscardedByUserID
next[i].DiscardedAt = p.DiscardedAt
next[i].DiscardedAnnotations = p.DiscardedAnnotations
next[i].DiscardedAnnotations = append([]domain.AnnotationSegment(nil), p.DiscardedAnnotations...)
}
for _, p := range previous {
if p.IsDiscarded() && !seen[p.ID] {
// Undoing a split can reunite a child with its original discarded
// parent, but cannot silently absorb it into a kept/differently judged slice.
rejoined := false
for _, candidate := range next {
for i, candidate := range next {
if candidate.IsDiscarded() && stdslices.Contains(p.SourceIDs, candidate.ID) &&
candidate.Start <= p.Start && candidate.End >= p.End &&
candidate.DiscardReason == p.DiscardReason &&
candidate.DiscardReasonLabelID == p.DiscardReasonLabelID &&
candidate.DiscardReasonVersion == p.DiscardReasonVersion {
// The child may have been restored and edited since the split.
// Its current archive owns its interval, even when a parent still
// retains an older, wider original for boundary undo.
childEvidence := restoredDiscardAnnotations(p)
parentWindow := candidate
parentWindow.Start, parentWindow.End = p.Start, p.End
if !sameArchiveContent(restoredDiscardAnnotations(parentWindow), childEvidence) {
next[i].DiscardedAnnotations = append(archiveOutsideIntervals(candidate.DiscardedAnnotations, candidate.ID, p), childEvidence...)
}
rejoined = true
break
}
@ -156,6 +173,148 @@ func canonicalDispositions(previous, slices []domain.SliceSegment) ([]domain.Sli
return next, issues
}
// Server-owned recovery evidence is separate from the public discard archive:
// a kept slice has no discarded annotations. Workspace snapshot writes must not
// replace this payload field with client evidence. One entry per slice bounds
// storage, and revision/phase checks prevent replay across materialization.
const sliceRestoreEvidenceKey = "sliceRestoreEvidence"
type sliceRestoreEvidence struct {
Slice domain.SliceSegment `json:"slice"`
Restored []domain.AnnotationSegment `json:"restored"`
Revision int `json:"revision"`
Phase string `json:"phase"`
}
func sameRestoredAnnotations(active, restored []domain.AnnotationSegment) bool {
remaining := append([]domain.AnnotationSegment(nil), active...)
unchanged := len(remaining) == len(restored)
for _, expected := range restored {
found := -1
for i, a := range remaining {
if reflect.DeepEqual(a, expected) {
found = i
break
}
}
if found < 0 {
unchanged = false
break
}
remaining = append(remaining[:found], remaining[found+1:]...)
}
return unchanged
}
func discardArchiveAfterRestore(e sliceRestoreEvidence, next domain.SliceSegment, active []domain.AnnotationSegment) []domain.AnnotationSegment {
if sameRestoredAnnotations(active, e.Restored) {
return append([]domain.AnnotationSegment(nil), e.Slice.DiscardedAnnotations...)
}
// Edits/deletions supersede only the exposed and current intervals.
return append(append([]domain.AnnotationSegment(nil), active...), archiveOutsideIntervals(e.Slice.DiscardedAnnotations, next.ID, e.Slice, next)...)
}
// Only a changed restore->discard writes ownership. Inherited archive records
// are not writes. Empty replacement content is an authoritative deletion.
const sliceArchiveEditsKey = "sliceArchiveEdits"
type sliceArchiveEdit struct {
Owner domain.SliceSegment `json:"owner"`
Intervals []domain.SliceSegment `json:"intervals"`
Annotations []domain.AnnotationSegment `json:"annotations"`
Version int `json:"version"`
Revision int `json:"revision"`
Phase string `json:"phase"`
}
func currentSliceArchiveEdits(item *domain.HumanItemRecord) []sliceArchiveEdit {
var result []sliceArchiveEdit
phase := stringValue(mapValue(item.Subject.Payload["sliceWorkflow"])["phase"])
for _, edit := range decodeMaterializationValue[sliceArchiveEdit](item.Subject.Payload[sliceArchiveEditsKey]) {
if edit.Revision == item.CurrentRevision && edit.Phase == phase {
result = append(result, edit)
}
}
stdslices.SortStableFunc(result, func(a, b sliceArchiveEdit) int {
if a.Version < b.Version {
return -1
}
if a.Version > b.Version {
return 1
}
return 0
})
return result
}
func applySliceArchiveEdits(slices []domain.SliceSegment, edits []sliceArchiveEdit) {
for _, edit := range edits {
for i := range slices {
target := &slices[i]
// The owner and its saved ancestors may recover this write. Do not turn
// a sibling's inherited full archive or client SourceIDs into ownership.
if !target.IsDiscarded() || (target.ID != edit.Owner.ID && !stdslices.Contains(edit.Owner.SourceIDs, target.ID)) {
continue
}
for _, interval := range edit.Intervals {
replacement := interval
replacement.ID = edit.Owner.ID
replacement.DiscardedAnnotations = edit.Annotations
content := restoredDiscardAnnotations(replacement)
window := *target
window.Start, window.End = interval.Start, interval.End
if sameArchiveContent(restoredDiscardAnnotations(window), content) {
continue
}
target.DiscardedAnnotations = append(archiveOutsideIntervals(target.DiscardedAnnotations, target.ID, interval), content...)
}
}
}
}
func sameArchiveContent(a, b []domain.AnnotationSegment) bool {
if len(a) != len(b) {
return false
}
for i := range a {
left, right := a[i], b[i]
left.ID, right.ID = "", ""
if !reflect.DeepEqual(left, right) {
return false
}
}
return true
}
func archiveOutsideIntervals(originals []domain.AnnotationSegment, sliceID string, intervals ...domain.SliceSegment) []domain.AnnotationSegment {
var archive []domain.AnnotationSegment
for _, original := range originals {
parts := []domain.AnnotationSegment{original}
for _, interval := range intervals {
var kept []domain.AnnotationSegment
for _, a := range parts {
if a.End <= interval.Start || a.Start >= interval.End {
kept = append(kept, a)
continue
}
for _, bounds := range [][2]float64{{a.Start, math.Min(a.End, interval.Start)}, {math.Max(a.Start, interval.End), a.End}} {
if bounds[1] <= bounds[0] {
continue
}
part := a
part.Start, part.End = bounds[0], bounds[1]
part.ID = fmt.Sprintf("%s@%s:%g:%g", original.ID, sliceID, part.Start, part.End)
part.StartTimestampUS, part.EndTimestampUS = 0, 0
kept = append(kept, part)
}
}
parts = kept
}
archive = append(archive, parts...)
}
return archive
}
// Keep the original archive intact for boundary undo. Restoring a child only
// reactivates the part of that evidence inside its current interval.
func restoredDiscardAnnotations(slice domain.SliceSegment) []domain.AnnotationSegment {
@ -276,6 +435,27 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
}
before := slices[idx]
next := before
evidence := decodeMaterializationValue[sliceRestoreEvidence](item.Subject.Payload[sliceRestoreEvidenceKey])
phase := stringValue(workflow["phase"])
archiveEdits := currentSliceArchiveEdits(item)
var retainedEvidence []sliceRestoreEvidence
var recovery *sliceRestoreEvidence
for _, e := range evidence {
if e.Revision != item.CurrentRevision || e.Phase != phase {
continue
}
if e.Slice.ID == next.ID {
copy := e
recovery = &copy
} else {
for _, candidate := range slices {
if candidate.ID == e.Slice.ID && !candidate.IsDiscarded() {
retainedEvidence = append(retainedEvidence, e)
break
}
}
}
}
// Blank annotations are valid. Keep an allocated empty slice so restore
// (including restore with no archived descriptions) serializes [] not null.
segments := append([]domain.AnnotationSegment{}, body.Segments...)
@ -295,9 +475,10 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
next.DiscardedAt = nowISO()
next.AnnotationStatus = domain.SliceAnnotationPending
kept := []domain.AnnotationSegment{}
var archived []domain.AnnotationSegment
for _, a := range segments {
if a.Start >= next.Start && a.End <= next.End {
next.DiscardedAnnotations = append(next.DiscardedAnnotations, a)
archived = append(archived, a)
} else if a.Start < next.End && a.End > next.Start {
renderValidationError(w, validationIssue{Field: "segments", Message: "描述跨越切片边界,请先修正"})
return
@ -305,10 +486,41 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
kept = append(kept, a)
}
}
if !before.IsDiscarded() && recovery != nil {
next.DiscardedAnnotations = discardArchiveAfterRestore(*recovery, next, archived)
if !sameRestoredAnnotations(archived, recovery.Restored) {
intervals := []domain.SliceSegment{{Start: recovery.Slice.Start, End: recovery.Slice.End}, {Start: next.Start, End: next.End}}
if intervals[0].Start <= intervals[1].End && intervals[1].Start <= intervals[0].End {
intervals = []domain.SliceSegment{{Start: math.Min(recovery.Slice.Start, next.Start), End: math.Max(recovery.Slice.End, next.End)}}
}
archiveEdits = append(archiveEdits, sliceArchiveEdit{Owner: domain.SliceSegment{ID: next.ID, SourceIDs: append([]string(nil), next.SourceIDs...)}, Intervals: intervals, Annotations: append([]domain.AnnotationSegment(nil), archived...), Version: item.Version + 1, Revision: item.CurrentRevision, Phase: phase})
}
} else {
next.DiscardedAnnotations = append(next.DiscardedAnnotations, archived...)
}
if archiveIssues := validateDraftCombinedAnnotationEvents(next.DiscardedAnnotations, *task); len(archiveIssues) > 0 {
renderValidationError(w, archiveIssues...)
return
}
segments = kept
} else {
if before.IsDiscarded() {
segments = append(segments, restoredDiscardAnnotations(before)...)
restored := restoredDiscardAnnotations(before)
used := map[string]bool{}
for _, a := range segments {
used[a.ID] = true
}
for i := range restored {
base := restored[i].ID
for n := 1; used[restored[i].ID]; n++ {
restored[i].ID = fmt.Sprintf("%s@%s:%d", base, next.ID, n)
}
used[restored[i].ID] = true
}
segments = append(segments, restored...)
retainedEvidence = append(retainedEvidence, sliceRestoreEvidence{Slice: before, Restored: restored, Revision: item.CurrentRevision, Phase: phase})
} else if recovery != nil {
retainedEvidence = append(retainedEvidence, *recovery)
}
next.DeliveryDisposition = "keep"
next.DiscardReason = ""
@ -322,6 +534,8 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
next.AnnotationStatus = domain.SliceAnnotationPending
}
slices[idx] = next
applySliceArchiveEdits(slices, archiveEdits)
next = slices[idx]
// Disposition is an incremental edit, not confirmation of the whole slicing
// plan. Other slices may still have draft names; confirmation validates them.
issues = validateDraftCombinedAnnotationEvents(segments, *task)
@ -338,6 +552,8 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
history, _ := normalizeStructuredValue(item.Subject.Payload["sliceDispositionHistory"]).([]any)
history = append(history, map[string]any{"sliceId": next.ID, "before": before, "after": next, "actorUserId": p.User.ID, "at": nowISO(), "itemVersion": item.Version + 1})
item.Subject.Payload["sliceDispositionHistory"] = history
item.Subject.Payload[sliceRestoreEvidenceKey] = retainedEvidence
item.Subject.Payload[sliceArchiveEditsKey] = archiveEdits
item.Subject.Payload["annotationWorkspace"] = workspace
delete(item.Subject.Payload, "annotationDraft")
if body.Disposition == "discard" {

View File

@ -0,0 +1,473 @@
package api
import (
"droboticflow/internal/domain"
"encoding/json"
"fmt"
"testing"
)
func TestPR5ReviewArchiveBoundaryUndo(t *testing.T) {
f := randomClaimFixture(t, 0)
body := dispositionFixturePayload(t, f)
save := func(step string) {
t.Helper()
r := f.request("POST", "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-dispositions", f.annotator, body)
if r.Code != 200 {
t.Fatalf("%s: %d %s", step, r.Code, r.Body.String())
}
var got struct {
Item domain.HumanItemRecord `json:"item"`
Workspace combinedAnnotationDraftInput `json:"workspace"`
}
if err := json.Unmarshal(r.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
body.combinedAnnotationDraftInput = got.Workspace
body.Version = got.Item.Version
t.Logf("%s: active=%+v archive=%+v", step, body.Segments, body.SliceSegments[1].DiscardedAnnotations)
}
save("discard [3,7]")
body.SliceSegments[1].End = 5
body.SliceSegments[2].Start = 5
body.Disposition = "keep"
save("shorten and restore [3,5]")
body.Disposition = "discard"
save("undo restore")
body.SliceSegments[1].End = 7
body.SliceSegments[2].Start = 7
body.Disposition = "keep"
save("undo boundary and restore [3,7]")
if len(body.Segments) != 1 || body.Segments[0].Start != 3 || body.Segments[0].End != 7 {
t.Fatalf("lost original [3,7] archive: %+v", body.Segments)
}
}
// Every step reloads the stored item through HTTP, not just the POST response.
func archiveRoundTrip(t *testing.T, f combinedDraftFixture, body *sliceDispositionInput) {
t.Helper()
path := "/api/plugins/annotation-qa/tasks/" + f.task.ID
r := f.request("POST", path+"/slice-dispositions", f.annotator, *body)
if r.Code != 200 {
t.Fatalf("%s: %d %s", body.Disposition, r.Code, r.Body.String())
}
archiveReadback(t, f, body)
}
func archiveReadback(t *testing.T, f combinedDraftFixture, body *sliceDispositionInput) {
t.Helper()
r := f.request("GET", "/api/plugins/annotation-qa/tasks/"+f.task.ID, f.admin, nil)
if r.Code != 200 {
t.Fatalf("GET: %d %s", r.Code, r.Body.String())
}
var got struct {
HumanItem domain.HumanItemRecord `json:"humanItem"`
}
if err := json.Unmarshal(r.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
raw, err := json.Marshal(annotationWorkspacePayload(&got.HumanItem))
if err != nil {
t.Fatal(err)
}
body.combinedAnnotationDraftInput = combinedAnnotationDraftInput{}
if err := json.Unmarshal(raw, &body.combinedAnnotationDraftInput); err != nil {
t.Fatal(err)
}
body.Version = got.HumanItem.Version
}
func TestArchiveRecoveryRepeatedCyclesAndCurrentDescriptions(t *testing.T) {
for _, change := range []string{"unchanged", "edit", "delete", "replace-id", "invalid"} {
t.Run(change, func(t *testing.T) {
f := randomClaimFixture(t, 0)
f.handler = NewHandler(bsonDispositionStore{Store: f.store}, nil)
body := dispositionFixturePayload(t, f)
archiveRoundTrip(t, f, &body)
body.SliceSegments[1].End = 5
body.SliceSegments[2].Start = 5
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
switch change {
case "edit":
body.Segments[0].Description = "new text"
case "delete":
body.Segments = nil
case "replace-id":
body.Segments[0].ID = "replacement"
case "invalid":
body.Segments[0].IsInvalid = true
}
for cycle := 0; cycle < 3; cycle++ {
// Both the public archive and client snapshots are untrusted.
body.SliceSegments[1].DiscardedAnnotations = []domain.AnnotationSegment{{ID: "forged", Start: 3, End: 7, Description: "forged"}}
body.Disposition = "discard"
archiveRoundTrip(t, f, &body)
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
}
body.Disposition = "discard"
archiveRoundTrip(t, f, &body)
body.SliceSegments[1].End = 7
body.SliceSegments[2].Start = 7
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
if change == "unchanged" {
if len(body.Segments) != 1 || body.Segments[0].Start != 3 || body.Segments[0].End != 7 || body.Segments[0].Description != "old text" {
t.Fatalf("lost original: %+v", body.Segments)
}
} else {
// Only never-exposed [5,7] retains the old description.
expected := 2
if change == "delete" {
expected = 1
}
if len(body.Segments) != expected {
t.Fatalf("incorrect recovery: %+v", body.Segments)
}
for _, a := range body.Segments {
if a.Description == "forged" {
t.Fatal("client evidence accepted")
}
if a.Start == 3 {
if a.End != 5 || (change == "edit" && a.Description != "new text") || (change == "invalid" && !a.IsInvalid) || (change == "replace-id" && a.ID != "replacement") || change == "delete" {
t.Fatalf("stale text resurrected: %+v", a)
}
} else if a.Start != 5 || a.End != 7 || a.Description != "old text" {
t.Fatalf("unexposed archive lost: %+v", a)
}
}
}
})
}
}
func TestArchiveRecoveryAcrossWorkspaceCanonicalization(t *testing.T) {
f := randomClaimFixture(t, 0)
f.item.Subject.Payload["sliceWorkflow"] = map[string]any{"phase": "slice", "status": "editing"}
if err := f.store.UpsertHumanItem(f.ctx, f.item); err != nil {
t.Fatal(err)
}
body := dispositionFixturePayload(t, f)
archiveRoundTrip(t, f, &body)
persist := func(end float64) {
t.Helper()
body.SliceSegments[1].End = end
body.SliceSegments[2].Start = end
body.SliceSegments[1].DiscardedAnnotations = nil
r := f.request("POST", "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-edit-restorations", f.annotator, body.combinedAnnotationDraftInput)
if r.Code != 200 {
t.Fatalf("restore snapshot: %d %s", r.Code, r.Body.String())
}
archiveReadback(t, f, &body)
}
persist(5)
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
// A kept workspace write must preserve the private recovery evidence too.
persist(5)
body.Disposition = "discard"
archiveRoundTrip(t, f, &body)
persist(7)
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
if len(body.Segments) != 1 || body.Segments[0].End != 7 {
t.Fatalf("snapshot lost archive: %+v", body.Segments)
}
}
func TestArchiveRecoverySeparatesSlicesWithReusedAnnotationID(t *testing.T) {
f := randomClaimFixture(t, 0)
body := dispositionFixturePayload(t, f)
archiveRoundTrip(t, f, &body)
body.SliceID = "c"
body.Segments = []domain.AnnotationSegment{{ID: "old-description", Start: 7, End: 10, Description: "other text", Source: "manual"}}
archiveRoundTrip(t, f, &body)
for cycle := 0; cycle < 3; cycle++ {
for _, id := range []string{"b", "c"} {
body.SliceID = id
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
}
if len(body.Segments) != 2 || body.Segments[0].Description != "old text" || body.Segments[1].Description != "other text" || body.Segments[0].ID == body.Segments[1].ID {
t.Fatalf("cross-contamination: %+v", body.Segments)
}
for _, id := range []string{"b", "c"} {
body.SliceID = id
body.Disposition = "discard"
archiveRoundTrip(t, f, &body)
}
}
}
func TestArchiveInheritanceRetainsOriginalAndRejectsDuplicateSliceIDs(t *testing.T) {
parent := domain.SliceSegment{ID: "b", Start: 3, End: 5, DeliveryDisposition: "discard", DiscardReason: "reason", DiscardedAnnotations: []domain.AnnotationSegment{{ID: "old", Start: 3, End: 7, Description: "old"}}}
child := parent
child.ID = "child"
child.Start = 4
child.End = 8
child.SourceIDs = []string{"b"}
left := parent
left.End = 4
got, issues := canonicalDispositions([]domain.SliceSegment{parent}, []domain.SliceSegment{left, child})
if len(issues) > 0 || len(got[1].DiscardedAnnotations) != 1 || got[1].DiscardedAnnotations[0].End != 7 {
t.Fatalf("split and drag lost original evidence: %+v %v", got, issues)
}
if _, issues := canonicalDispositions([]domain.SliceSegment{parent}, []domain.SliceSegment{parent, parent}); len(issues) == 0 {
t.Fatal("duplicate slice IDs accepted")
}
}
func TestArchiveRejoinUsesEditedOrDeletedChildEvidence(t *testing.T) {
for _, deleted := range []bool{false, true} {
t.Run(fmt.Sprint(deleted), func(t *testing.T) {
f := randomClaimFixture(t, 0)
body := dispositionFixturePayload(t, f)
archiveRoundTrip(t, f, &body)
parent := body.SliceSegments[1]
left, right := parent, parent
left.End = 5
right.Start = 5
right.ID = "child"
right.SourceIDs = []string{"b"}
body.SliceSegments = []domain.SliceSegment{body.SliceSegments[0], left, right, body.SliceSegments[2]}
body.SliceID = "child"
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
if deleted {
body.Segments = nil
} else {
body.Segments[0].Description = "child edit"
}
// Older client snapshots may omit or forge lineage after restore.
body.SliceSegments[2].SourceIDs = []string{"unrelated"}
body.Disposition = "discard"
archiveRoundTrip(t, f, &body)
body.SliceSegments = []domain.SliceSegment{body.SliceSegments[0], parent, body.SliceSegments[3]}
body.SliceID = "b"
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
expected := 2
if deleted {
expected = 1
}
if len(body.Segments) != expected {
t.Fatalf("rejoin lost child decision: %+v", body.Segments)
}
for _, a := range body.Segments {
if a.End > 5 && (deleted || a.Description != "child edit") {
t.Fatalf("stale parent evidence resurrected: %+v", body.Segments)
}
}
})
}
}
func TestArchiveRecoveryExpiresAtRevisionBoundary(t *testing.T) {
f := randomClaimFixture(t, 0)
body := dispositionFixturePayload(t, f)
archiveRoundTrip(t, f, &body)
body.SliceSegments[1].End = 5
body.SliceSegments[2].Start = 5
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
item, err := f.store.GetHumanItem(f.ctx, f.item.ID)
if err != nil {
t.Fatal(err)
}
item.CurrentRevision++
if err := f.store.UpsertHumanItem(f.ctx, *item); err != nil {
t.Fatal(err)
}
body.Disposition = "discard"
archiveRoundTrip(t, f, &body)
body.SliceSegments[1].End = 7
body.SliceSegments[2].Start = 7
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
if len(body.Segments) != 1 || body.Segments[0].End != 5 {
t.Fatalf("replayed a previous revision: %+v", body.Segments)
}
}
func TestArchiveMultipleCutsDragAndUndoAllCuts(t *testing.T) {
for _, change := range []string{"unchanged", "edit", "delete"} {
t.Run(change, func(t *testing.T) {
f := randomClaimFixture(t, 0)
body := dispositionFixturePayload(t, f)
archiveRoundTrip(t, f, &body)
original := body.SliceSegments[1]
body.SliceSegments[1].End = 5
body.SliceSegments[2].Start = 5
archiveRoundTrip(t, f, &body)
// Split the saved [3,5] parent and drag the new child beyond its old
// boundary in one request. The archive still has original [3,7].
left, child := body.SliceSegments[1], body.SliceSegments[1]
left.End = 4
child.ID = "child"
child.Start = 4
child.End = 6
child.SourceIDs = []string{"b"}
tail := body.SliceSegments[2]
tail.Start = 6
body.SliceSegments = []domain.SliceSegment{body.SliceSegments[0], left, child, tail}
body.SliceID = "child"
archiveRoundTrip(t, f, &body)
child = body.SliceSegments[2]
child.End = 5
grandchild := child
grandchild.ID = "grandchild"
grandchild.Start = 5
grandchild.End = 7
grandchild.SourceIDs = []string{"child", "b"}
tail.Start = 7
body.SliceSegments = []domain.SliceSegment{body.SliceSegments[0], body.SliceSegments[1], child, grandchild, tail}
body.SliceID = "grandchild"
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
if len(body.Segments) != 1 || body.Segments[0].Start != 5 || body.Segments[0].End != 7 {
t.Fatalf("grandchild lost full original: %+v", body.Segments)
}
if change == "edit" {
body.Segments[0].Description = "edited grandchild"
}
if change == "delete" {
body.Segments = nil
}
body.Disposition = "discard"
archiveRoundTrip(t, f, &body)
// Undo the inner cut, then all cuts, then the initial shortening.
child = body.SliceSegments[2]
child.End = 7
body.SliceSegments = []domain.SliceSegment{body.SliceSegments[0], body.SliceSegments[1], child, body.SliceSegments[4]}
body.SliceID = "child"
archiveRoundTrip(t, f, &body)
body.SliceSegments = []domain.SliceSegment{body.SliceSegments[0], original, body.SliceSegments[3]}
body.SliceID = "b"
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
total := 0.0
for _, a := range body.Segments {
total += a.End - a.Start
if a.Start < 3 || a.End > 7 {
t.Fatalf("archive crossed original bounds: %+v", a)
}
if a.End > 5 && (change == "delete" || (change == "edit" && a.Description != "edited grandchild")) {
t.Fatalf("stale ancestor evidence: %+v", body.Segments)
}
}
expected := 4.0
if change == "delete" {
expected = 2
}
if total != expected {
t.Fatalf("cuts lost evidence: %+v", body.Segments)
}
if change == "unchanged" && (len(body.Segments) != 1 || body.Segments[0].ID != "old-description") {
t.Fatalf("original fragmented/lost: %+v", body.Segments)
}
})
}
}
func TestArchiveRejoinPreservesEditedDormantChildThroughHTTP(t *testing.T) {
for _, change := range []string{"edit", "delete", "parent-edit", "overlapping-parent-edit"} {
t.Run(change, func(t *testing.T) {
f := randomClaimFixture(t, 0)
f.handler = NewHandler(bsonDispositionStore{Store: f.store}, nil)
f.item.Subject.Payload["sliceWorkflow"] = map[string]any{"phase": "slice", "status": "editing"}
if err := f.store.UpsertHumanItem(f.ctx, f.item); err != nil {
t.Fatal(err)
}
body := dispositionFixturePayload(t, f)
archiveRoundTrip(t, f, &body)
parent := body.SliceSegments[1]
left, child := parent, parent
left.End = 5
child.ID = "child"
child.Start = 5
child.SourceIDs = []string{"b"}
body.SliceSegments = []domain.SliceSegment{body.SliceSegments[0], left, child, body.SliceSegments[2]}
body.SliceID = "child"
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
if change == "delete" {
body.Segments = nil
} else {
body.Segments[0].Description = "new text"
}
body.Disposition = "discard"
archiveRoundTrip(t, f, &body)
restore := func() {
t.Helper()
r := f.request("POST", "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-edit-restorations", f.annotator, body.combinedAnnotationDraftInput)
if r.Code != 200 {
t.Fatalf("restore snapshot: %d %s", r.Code, r.Body.String())
}
archiveReadback(t, f, &body)
}
if change == "parent-edit" || change == "overlapping-parent-edit" {
if change == "overlapping-parent-edit" {
body.SliceSegments[1].End = 6
body.SliceSegments[2].Start = 6
restore()
}
body.SliceID = "b"
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
for i := range body.Segments {
body.Segments[i].Description = "parent newer"
}
body.Disposition = "discard"
archiveRoundTrip(t, f, &body)
body.SliceSegments[1].End = 5
body.SliceSegments[2].Start = 5
restore()
}
body.SliceSegments[2].End = 6
body.SliceSegments[3].Start = 6
restore()
// Original client archive is deliberately stale; the server must retain
// both child-owned dormant writes and independent newer parent writes.
body.SliceSegments = []domain.SliceSegment{body.SliceSegments[0], parent, body.SliceSegments[3]}
body.SliceSegments[2].Start = 7
body.Statuses = nil
restore()
body.SliceID = "b"
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
for cycle := 0; cycle < 2; cycle++ {
total := 0.0
for _, a := range body.Segments {
total += a.End - a.Start
parentEnd := 5.0
if change == "overlapping-parent-edit" {
parentEnd = 6
}
if a.Start < parentEnd {
expected := "old text"
if change == "parent-edit" || change == "overlapping-parent-edit" {
expected = "parent newer"
}
if a.End > parentEnd || a.Description != expected {
t.Fatalf("independent parent edit overwritten: %+v", body.Segments)
}
} else if change == "delete" || a.Description != "new text" {
t.Fatalf("updated dormant child archive lost: %+v", body.Segments)
}
}
expected := 4.0
if change == "delete" {
expected = 2
}
if total != expected {
t.Fatalf("archive coverage lost: %+v", body.Segments)
}
body.Disposition = "discard"
archiveRoundTrip(t, f, &body)
body.Disposition = "keep"
archiveRoundTrip(t, f, &body)
}
})
}
}

View File

@ -0,0 +1,128 @@
package api
import (
"fmt"
"net/http"
"droboticflow/internal/domain"
"github.com/go-chi/chi/v5"
)
// handleSliceEditRestoration writes an editing snapshot, never a generation or
// disposition command. The current server disposition remains authoritative.
func (s *server) handleSliceEditRestoration(w http.ResponseWriter, r *http.Request) {
task, err := s.store.GetAnnotationTask(r.Context(), chi.URLParam(r, "id"))
if err != nil {
renderError(w, 500, err)
return
}
if task == nil {
renderJSON(w, 404, map[string]string{"error": "Annotation task not found"})
return
}
principal, memberships, ok := s.ensureAnnotationTaskAccess(w, r, *task)
if !ok {
return
}
if principal == nil || principal.User.Role != domain.UserRoleAnnotator || !membershipHasRole(memberships, *task, domain.AnnotationRoleAnnotator) {
renderJSON(w, 403, map[string]string{"error": "annotator assignment is required"})
return
}
item, ok := s.requireLegacyHumanItemClaim(w, r, *task, domain.FanyuV58StageAnnotationCombined)
if !ok || rejectPendingCombinedSubmission(w, item) {
return
}
workflow := mapValue(item.Subject.Payload["sliceWorkflow"])
busy := false
if job := item.ProcessingJob; job != nil {
busy = job.Status == "queued" || job.Status == "running" || job.Status == "processing"
}
if stringValue(workflow["phase"]) != "slice" || stringValue(workflow["status"]) == "processing" || stringValue(workflow["status"]) == "running" || stringValue(workflow["status"]) == "materializing" || stringValue(workflow["status"]) == "queued" || busy {
renderJSON(w, 409, map[string]string{"code": "slice_edit_restoration_unavailable", "error": "仅可在可编辑的切片阶段撤销或重做切片"})
return
}
var body combinedAnnotationDraftInput
if !decodeJSON(w, r, &body) {
return
}
if body.Version != item.Version {
renderJSON(w, 409, map[string]string{"code": "version_conflict", "error": "Human item version conflict"})
return
}
proposed := body.normalizedSliceSegments()
slices, issues := s.canonicalSliceDispositionState(r.Context(), item, proposed)
// Historical audit fields may be stale after an explicit discard/restore.
// The canonicalizer replaces them with current server-owned evidence.
for i, candidate := range proposed {
if !candidate.IsDiscarded() && candidate.DiscardReason != "" {
issues = append(issues, validationIssue{Field: fmt.Sprintf("sliceSegments.%d.discardReason", i), Code: "explicit_disposition_required", Message: "请通过舍弃操作设置原因,保留片段不能携带舍弃原因"})
}
}
if len(issues) > 0 {
renderValidationError(w, issues...)
return
}
if task.SourceIsFullVideo || stringValue(workflow["boundaryContract"]) == "hardware-frame-v1" {
timeline, err := s.annotationFrameTimelineForTask(r.Context(), *task, "left")
if err != nil {
renderJSON(w, 422, map[string]string{"error": err.Error()})
return
}
if task.SourceIsFullVideo {
task.CoverageStartSecond = floatValue(timeline["rangeStartSecond"])
task.CoverageEndSecond = floatValue(timeline["rangeEndSecond"])
task.CoverageMode = "full_common_range"
}
grid := annotationBoundaryGrid{Seconds: timeline["boundariesSeconds"].([]float64), Timestamps: timeline["boundaryTimestampUs"].([]int64)}
resolve := func(start, end *float64, startUS, endUS *int64, field string) {
a, firstErr := grid.resolve(*start)
b, lastErr := grid.resolve(*end)
if firstErr != nil || lastErr != nil || b <= a {
issues = append(issues, validationIssue{Field: field, Message: "切片和动作边界必须与有效帧对齐"})
return
}
*start, *end = grid.Seconds[a], grid.Seconds[b]
*startUS, *endUS = grid.Timestamps[a], grid.Timestamps[b]
}
for i := range slices {
v := &slices[i]
resolve(&v.Start, &v.End, &v.StartTimestampUS, &v.EndTimestampUS, "sliceSegments")
}
for i := range body.Segments {
v := &body.Segments[i]
resolve(&v.Start, &v.End, &v.StartTimestampUS, &v.EndTimestampUS, "segments")
}
}
issues = append(issues, validateSliceSegments(slices, *task)...)
issues = append(issues, validateCompleteSliceCoverage(slices, *task)...)
issues = append(issues, validateDraftCombinedAnnotationEvents(body.Segments, *task)...)
issues = append(issues, validateDraftStatuses(body.normalizedStatuses(), slices)...)
template, err := s.store.GetAnnotationTemplate(r.Context(), task.TemplateID)
if err != nil {
renderError(w, 500, err)
return
}
issues = append(issues, validateDraftFanyuV5CombinedSemanticSegments(body.Segments, slices, annotationTemplateWithTaskSnapshot(template, task))...)
if len(issues) > 0 {
renderValidationError(w, issues...)
return
}
now := nowISO()
workspace := map[string]any{"sliceSegments": slices, "operations": body.normalizedOperations(), "segments": body.normalizedSegments(), "statuses": body.normalizedStatuses(), "userId": principal.User.ID, "savedAt": now}
item.Subject.Payload["annotationWorkspace"] = workspace
delete(item.Subject.Payload, "annotationDraft")
expected := item.Version
item.Version++
item.UpdatedAt = now
won, err := s.store.UpdateHumanItemVersioned(r.Context(), *item, expected)
if err != nil {
renderError(w, 500, err)
return
}
if !won {
renderJSON(w, 409, map[string]string{"code": "version_conflict", "error": "Human item version conflict"})
return
}
_ = s.appendHumanEvent(r.Context(), *item, "slice_edit_restored", principal.User.ID, map[string]any{"sliceCount": len(slices)})
renderJSON(w, 200, map[string]any{"item": item, "workspace": workspace})
}

View File

@ -0,0 +1,324 @@
package api
import (
"encoding/json"
"net/http"
"testing"
"time"
"droboticflow/internal/domain"
)
func sliceRestorationFixture(t *testing.T) combinedDraftFixture {
t.Helper()
f := newCombinedDraftFixture(t)
f.item.Subject.Payload["sliceWorkflow"] = map[string]any{"phase": "slice", "status": "editing"}
f.item.Subject.Payload["annotationDraft"] = map[string]any{"obsolete": true}
if err := f.store.UpsertHumanItem(f.ctx, f.item); err != nil {
t.Fatal(err)
}
return f
}
func readSliceRestoration(t *testing.T, f combinedDraftFixture) (domain.HumanItemRecord, combinedAnnotationDraftInput) {
t.Helper()
r := f.request(http.MethodGet, "/api/plugins/annotation-qa/tasks/"+f.task.ID, f.admin, nil)
if r.Code != 200 {
t.Fatalf("GET %d: %s", r.Code, r.Body.String())
}
var got struct {
HumanItem domain.HumanItemRecord `json:"humanItem"`
}
if err := json.Unmarshal(r.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
raw, _ := json.Marshal(got.HumanItem.Subject.Payload["annotationWorkspace"])
var workspace combinedAnnotationDraftInput
if err := json.Unmarshal(raw, &workspace); err != nil {
t.Fatal(err)
}
return got.HumanItem, workspace
}
func TestSliceEditRestorationPersistsUndoRedoThroughHTTP(t *testing.T) {
f := sliceRestorationFixture(t)
path := "/api/plugins/annotation-qa/tasks/" + f.task.ID
body := dispositionFixturePayload(t, f)
// Persist split, discard, then explicit restore before undoing the partition.
for _, disposition := range []string{"discard", "keep"} {
body.Disposition = disposition
r := f.request(http.MethodPost, path+"/slice-dispositions", f.annotator, body)
if r.Code != 200 {
t.Fatalf("%s: %d %s", disposition, r.Code, r.Body.String())
}
item, workspace := readSliceRestoration(t, f)
body.combinedAnnotationDraftInput = workspace
body.Version = item.Version
}
split := body.combinedAnnotationDraftInput
original := combinedAnnotationDraftInput{SliceSegments: []domain.SliceSegment{{ID: "whole", Name: "默认切片", Start: 0, End: 10}}, Segments: split.Segments, Statuses: map[string]domain.SliceAnnotationStatus{"whole": domain.SliceAnnotationPending}}
for _, snapshot := range []combinedAnnotationDraftInput{original, split, original} {
before, _ := readSliceRestoration(t, f)
snapshot.Version = before.Version
r := f.request(http.MethodPost, path+"/slice-edit-restorations", f.annotator, snapshot)
if r.Code != 200 {
t.Fatalf("restore: %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)
}
item, workspace := readSliceRestoration(t, f)
if item.Version != before.Version+1 || response.Item.Version != item.Version || len(workspace.SliceSegments) != len(snapshot.SliceSegments) || len(response.Workspace.SliceSegments) != len(snapshot.SliceSegments) {
t.Fatalf("snapshot not persisted: %+v", workspace)
}
if len(workspace.Segments) != 1 || workspace.Segments[0].Description != "old text" {
t.Fatalf("lost restored evidence: %+v", workspace.Segments)
}
if item.Subject.Payload["annotationDraft"] != nil || item.CurrentStageID != before.CurrentStageID || item.ProcessingJob != nil || stringValue(mapValue(item.Subject.Payload["sliceWorkflow"])["phase"]) != "slice" {
t.Fatalf("unexpected transition: %+v", item)
}
}
}
func TestSliceEditRestorationRejectsUnsafeWritesThroughHTTP(t *testing.T) {
for _, scenario := range []string{"stale", "nonowner", "unclaimed", "reviewer", "admin", "stage", "annotate", "materializing", "missing-phase", "processing", "running", "queued", "job-queued", "job-running", "submission", "coverage", "bounds", "duplicate", "event-bounds", "event-crosses-slice", "unknown-status", "invalid-status", "forged-disposition", "forged-reason", "hardware-contract"} {
t.Run(scenario, func(t *testing.T) {
f := sliceRestorationFixture(t)
item := f.item
body := combinedAnnotationDraftInput{Version: item.Version, SliceSegments: []domain.SliceSegment{{ID: "whole", Start: 0, End: 10}}, Segments: []domain.AnnotationSegment{}}
user := f.annotator
want := http.StatusConflict
workflow := mapValue(item.Subject.Payload["sliceWorkflow"])
switch scenario {
case "stale":
body.Version--
case "nonowner":
item.AssignedUserID = f.admin.ID
case "unclaimed":
item.Status = domain.HumanItemReady
case "reviewer":
user = f.reviewer
want = 403
case "admin":
user = f.admin
want = 403
case "stage":
item.CurrentStageID = "quality_review"
case "annotate", "materializing":
workflow["phase"] = scenario
case "missing-phase":
delete(workflow, "phase")
case "processing", "running", "queued":
workflow["status"] = scenario
workflow["leaseExpiresAt"] = time.Now().Add(time.Hour).Format(time.RFC3339Nano)
case "job-queued":
item.ProcessingJob = &domain.AnnotationProcessingJob{ID: "job", Status: "queued"}
case "job-running":
item.ProcessingJob = &domain.AnnotationProcessingJob{ID: "job", Status: "running"}
case "submission":
item.PendingCombinedSubmissionID = fanyuV5CombinedSubmissionID(item.ID, item.Version-1)
item.PendingCombinedPayloadSHA = "snapshot"
item.ProcessingJob = &domain.AnnotationProcessingJob{ID: item.PendingCombinedSubmissionID, Status: "queued", Kind: "submit"}
default:
want = http.StatusBadRequest
switch scenario {
case "coverage":
body.SliceSegments[0].End = 9
case "bounds":
body.SliceSegments[0].Start = -1
case "duplicate":
body.SliceSegments = append(body.SliceSegments, body.SliceSegments[0])
case "event-bounds":
body.Segments = []domain.AnnotationSegment{{ID: "event", Start: 9, End: 11}}
case "event-crosses-slice":
body.SliceSegments = []domain.SliceSegment{{ID: "a", Start: 0, End: 5}, {ID: "b", Start: 5, End: 10}}
body.Segments = []domain.AnnotationSegment{{ID: "event", Start: 4, End: 6}}
case "unknown-status":
body.Statuses = map[string]domain.SliceAnnotationStatus{"missing": domain.SliceAnnotationPending}
case "invalid-status":
body.Statuses = map[string]domain.SliceAnnotationStatus{"whole": "made-up"}
case "forged-disposition":
body.SliceSegments[0].DeliveryDisposition = "discard"
body.SliceSegments[0].DiscardReason = "forged"
case "forged-reason":
body.SliceSegments[0].DiscardReason = "forged"
case "hardware-contract":
workflow["boundaryContract"] = "hardware-frame-v1"
want = http.StatusUnprocessableEntity
}
}
item.Subject.Payload["sliceWorkflow"] = workflow
if err := f.store.UpsertHumanItem(f.ctx, item); err != nil {
t.Fatal(err)
}
before, _ := readSliceRestoration(t, f)
r := f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-edit-restorations", user, body)
if r.Code != want {
t.Fatalf("want %d got %d: %s", want, r.Code, r.Body.String())
}
after, _ := readSliceRestoration(t, f)
a, _ := json.Marshal(before)
b, _ := json.Marshal(after)
if string(a) != string(b) {
t.Fatalf("rejected request mutated item\nbefore %s\nafter %s", a, b)
}
})
}
}
func TestSliceEditRestorationConcurrentSnapshotsHaveOneWinner(t *testing.T) {
f := sliceRestorationFixture(t)
body := combinedAnnotationDraftInput{Version: f.item.Version, SliceSegments: []domain.SliceSegment{{ID: "whole", Start: 0, End: 10}}}
start := make(chan struct{})
results := make(chan int, 2)
for i := 0; i < 2; i++ {
go func() {
<-start
results <- f.request(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-edit-restorations", f.annotator, body).Code
}()
}
close(start)
a, b := <-results, <-results
if !((a == 200 && b == 409) || (a == 409 && b == 200)) {
t.Fatalf("concurrent statuses %d %d", a, b)
}
item, workspace := readSliceRestoration(t, f)
if item.Version != f.item.Version+1 || len(workspace.SliceSegments) != 1 {
t.Fatalf("bad winning state: %+v", item)
}
}
func TestSliceEditRestorationPreservesDiscardAuthority(t *testing.T) {
f := sliceRestorationFixture(t)
path := "/api/plugins/annotation-qa/tasks/" + f.task.ID
body := dispositionFixturePayload(t, f)
r := f.request(http.MethodPost, path+"/slice-dispositions", f.annotator, body)
if r.Code != 200 {
t.Fatalf("discard: %d %s", r.Code, r.Body.String())
}
item, saved := readSliceRestoration(t, f)
for _, scenario := range []string{"restore-disposition", "change-reason", "drop-discard"} {
t.Run(scenario, func(t *testing.T) {
raw, _ := json.Marshal(saved)
var payload combinedAnnotationDraftInput
if err := json.Unmarshal(raw, &payload); err != nil {
t.Fatal(err)
}
payload.Version = item.Version
switch scenario {
case "restore-disposition":
payload.SliceSegments[1].DeliveryDisposition = "keep"
payload.SliceSegments[1].DiscardReason = ""
case "change-reason":
payload.SliceSegments[1].DiscardReason = "forged"
case "drop-discard":
payload.SliceSegments = []domain.SliceSegment{{ID: "whole", Start: 0, End: 10}}
}
rejected := f.request(http.MethodPost, path+"/slice-edit-restorations", f.annotator, payload)
if rejected.Code != 400 {
t.Fatalf("forged %d %s", rejected.Code, rejected.Body.String())
}
latest, _ := readSliceRestoration(t, f)
if latest.Version != item.Version {
t.Fatal("forgery changed version")
}
})
}
saved.Version = item.Version
// An unchanged discarded snapshot round-trips without revalidating dictionary names.
saved.Operations = []domain.SliceOperation{{Type: "split", SegmentIDs: []string{"a", "b", "c"}}}
r = f.request(http.MethodPost, path+"/slice-edit-restorations", f.annotator, saved)
if r.Code != 200 {
t.Fatalf("saved discard: %d %s", r.Code, r.Body.String())
}
_, workspace := readSliceRestoration(t, f)
if len(workspace.Operations) != 1 || workspace.Operations[0].Type != "split" || len(workspace.SliceSegments[1].DiscardedAnnotations) != 1 || workspace.SliceSegments[1].DiscardedAnnotations[0].Description != "old text" || workspace.SliceSegments[1].DiscardedByUserID != f.annotator.ID {
t.Fatalf("discard evidence lost: %+v", workspace)
}
}
func TestSliceEditRestorationHardwareFrameContract(t *testing.T) {
f, _ := annotationProcessorFixture(t)
item := f.item
item.Subject.Payload["sliceWorkflow"] = map[string]any{"phase": "slice", "status": "editing", "boundaryContract": "hardware-frame-v1"}
if err := f.store.UpsertHumanItem(f.ctx, item); err != nil {
t.Fatal(err)
}
path := "/api/plugins/annotation-qa/tasks/" + f.task.ID
payload := combinedAnnotationDraftInput{Version: item.Version, SliceSegments: []domain.SliceSegment{{ID: "whole", Start: 0, End: 4}}, Segments: []domain.AnnotationSegment{{ID: "event", Start: 0.125, End: 0.25}}}
// Both slice and event edges must resolve against the real stereo PTS grid.
for _, target := range []string{"slice", "event"} {
bad := payload
bad.SliceSegments = append([]domain.SliceSegment(nil), payload.SliceSegments...)
bad.Segments = append([]domain.AnnotationSegment(nil), payload.Segments...)
if target == "slice" {
bad.SliceSegments[0].End = 3.99
} else {
bad.Segments[0].Start = 0.12
}
r := f.request(http.MethodPost, path+"/slice-edit-restorations", f.annotator, bad)
if r.Code != 400 {
t.Fatalf("off-grid %s: %d %s", target, r.Code, r.Body.String())
}
}
r := f.request(http.MethodPost, path+"/slice-edit-restorations", f.annotator, payload)
if r.Code != 200 {
t.Fatalf("aligned: %d %s", r.Code, r.Body.String())
}
latest, workspace := readSliceRestoration(t, f)
if latest.Version != item.Version+1 || workspace.SliceSegments[0].StartTimestampUS != 1000000 || workspace.SliceSegments[0].EndTimestampUS != 5000000 || workspace.Segments[0].StartTimestampUS != 1125000 || workspace.Segments[0].EndTimestampUS != 1250000 {
t.Fatalf("frame timestamps: %+v", workspace)
}
}
func TestSliceEditRestorationCanonicalizesHistoricalAuditThroughHTTP(t *testing.T) {
f := sliceRestorationFixture(t)
path := "/api/plugins/annotation-qa/tasks/" + f.task.ID
body := dispositionFixturePayload(t, f)
var historical combinedAnnotationDraftInput
for index, disposition := range []string{"discard", "keep", "discard"} {
body.Disposition = disposition
if index == 2 {
body.Segments[0].Description = "new authoritative evidence"
}
r := f.request(http.MethodPost, path+"/slice-dispositions", f.annotator, body)
if r.Code != 200 {
t.Fatalf("disposition: %d %s", r.Code, r.Body.String())
}
item, workspace := readSliceRestoration(t, f)
if index == 0 {
historical = workspace
}
body.combinedAnnotationDraftInput = workspace
body.Version = item.Version
}
current := body.SliceSegments[1]
if current.DiscardedAt == historical.SliceSegments[1].DiscardedAt {
t.Fatal("fixture must produce a new discard timestamp")
}
historical.Version = body.Version
// Historical timestamps and archive are stale; even arbitrary client audit
// identity/reason snapshots must be replaced by the current server evidence.
historical.SliceSegments[1].DiscardedByUserID = "forged"
historical.SliceSegments[1].DiscardReasonLabelID = "forged"
historical.SliceSegments[1].DiscardReasonVersion = 999
historical.SliceSegments[1].DiscardReasonName = "forged"
historical.SliceSegments[1].DiscardReasonNote = "forged"
r := f.request(http.MethodPost, path+"/slice-edit-restorations", f.annotator, historical)
if r.Code != 200 {
t.Fatalf("historical snapshot: %d %s", r.Code, r.Body.String())
}
item, workspace := readSliceRestoration(t, f)
actual := workspace.SliceSegments[1]
a, _ := json.Marshal(current)
b, _ := json.Marshal(actual)
if string(a) != string(b) || item.Version != body.Version+1 {
t.Fatalf("audit was not canonicalized: want %s got %s", a, b)
}
}

View File

@ -14,7 +14,12 @@ export function createAnnotationHistory({ now = () => performance.now() } = {})
const startedAtRevision = revision;
pending = true;
try {
if ((await restore(structuredClone(entry[direction === "undo" ? "before" : "after"]))) !== true) return false;
if (
(await restore(structuredClone(entry[direction === "undo" ? "before" : "after"]), {
persisted: entry.persisted === true,
})) !== true
)
return false;
if (startedAtRevision !== revision) return false;
source.pop();
(direction === "undo" ? future : past).push(entry);
@ -36,6 +41,11 @@ export function createAnnotationHistory({ now = () => performance.now() } = {})
revision++;
future = [];
},
// A workspace save also persists earlier slice edits. Keep this on the
// entry so both undo and redo wait for a write, even after crossing a save.
markPersisted() {
for (const entry of past) entry.persisted = true;
},
record(entry) {
revision++;
past.push(structuredClone(entry));

View File

@ -2121,6 +2121,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
after: { kind: "annotation", state: { ...before, segments: nextSegments, editor: null }, persisted },
});
}
editHistoryRef.current.markPersisted();
annotationBaselineRef.current = annotationWorkspaceFingerprint(
sliceSegments,
sliceOperations,
@ -2387,6 +2388,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
setSliceStatuses(workspace.statuses);
setSliceOperations(workspace.operations);
if (recordHistory) {
editHistoryRef.current.markPersisted();
const savedSlice = workspace.sliceSegments.find((slice) => slice.id === sliceId);
if (savedSlice) editHistoryRef.current.record({ before, after: snapshot(savedSlice) });
}
@ -2407,6 +2409,65 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
}
};
const restorePersistedSliceEdit = async (snapshot: SliceEditSnapshot) => {
if (!detail?.humanItem || !selectedClaimedByMe || combinedEditorPhase !== "slice") return null;
const taskId = detail.task.id;
const version = detailRef.current?.humanItem?.version ?? detail.humanItem.version;
const payload = {
version,
sliceSegments: snapshot.slices,
operations: snapshot.operations,
segments: snapshot.segments,
statuses: snapshot.statuses,
};
const token = beginAnnotationMutation(taskId);
if (!token) return null;
try {
const result = await settleAuthoritativeMutation({
scope: annotationMutationScopeRef.current,
token,
currentContext: currentAnnotationMutationContext,
write: () => annotationOperationsApi.restoreSliceEdit(taskId, payload),
read: () => annotationOperationsApi.getTask(taskId),
isApplied: (authoritative: AnnotationTaskDetail) => {
const workspace = annotationDraftFromHumanItem(authoritative.humanItem);
return Boolean(
authoritative.humanItem?.version === version + 1 &&
authoritative.humanItem.assignedUserId === currentUser?.id &&
authoritative.humanItem.currentStageId === detail.humanItem?.currentStageId &&
workspace &&
annotationWorkspaceMatches(workspace, payload),
);
},
});
if (result.status === "stale") return null;
if (result.status !== "confirmed") {
setError(
`${getActionErrorMessage(result.error, "恢复切片编辑失败")} 撤销历史和当前内容已保留,请核对服务器状态后重试。`,
);
return null;
}
const item = result.reconciled ? result.authoritative.humanItem : result.response.item;
const workspace = result.reconciled
? annotationDraftFromHumanItem(item)
: normalizeAnnotationWorkspace(result.response.workspace);
if (!item || !workspace) return null;
const savedItem = { ...item, display: item.display || detail.humanItem.display };
confirmedAnnotationWorkspaceRef.current = { taskId, workspace: structuredClone(workspace) };
setDetail((current) => (current ? { ...current, humanItem: savedItem } : current));
setHumanPools((current) => ({ ...current, mine: current.mine.map((i) => (i.id === item.id ? savedItem : i)) }));
annotationBaselineRef.current = annotationWorkspaceFingerprint(
workspace.sliceSegments,
workspace.operations,
workspace.segments,
workspace.statuses,
);
return workspace;
} finally {
endAnnotationMutation(token);
}
};
const restoreEdit = async (direction: "undo" | "redo") => {
if (
!exactFrameEditing ||
@ -2419,7 +2480,10 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
)
return;
await editHistoryRef.current[direction](
async (snapshot: SliceEditSnapshot | AnnotationEditSnapshot | DispositionEditSnapshot) => {
async (
snapshot: SliceEditSnapshot | AnnotationEditSnapshot | DispositionEditSnapshot,
{ persisted }: { persisted: boolean },
) => {
if ("kind" in snapshot && snapshot.kind === "disposition") {
try {
// Replay through the explicit server operation so audit evidence,
@ -2465,10 +2529,12 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
}));
return true;
}
setSliceSegments(snapshot.slices);
setSliceOperations(snapshot.operations);
setSegments(snapshot.segments);
setSliceStatuses(snapshot.statuses);
const workspace = persisted ? await restorePersistedSliceEdit(snapshot) : null;
if (persisted && !workspace) return false;
setSliceSegments(workspace?.sliceSegments ?? snapshot.slices);
setSliceOperations(workspace?.operations ?? snapshot.operations);
setSegments(workspace?.segments ?? snapshot.segments);
setSliceStatuses(workspace?.statuses ?? snapshot.statuses);
setSliceBoundaryDrafts({});
setError("");
setHistoryReveal((previous) => ({ ...snapshot.location, revision: (previous?.revision ?? 0) + 1 }));

View File

@ -197,6 +197,21 @@ export const annotationOperationsApi = {
{ method: "POST", headers: { Prefer: "respond-async" } },
payload,
),
restoreSliceEdit: (
taskId: string,
payload: {
version: number;
sliceSegments: SliceSegment[];
operations: SliceOperation[];
segments: AnnotationSegment[];
statuses: Record<string, NonNullable<SliceSegment["annotationStatus"]>>;
},
) =>
apiRequest<{ item: HumanItem; workspace: Omit<typeof payload, "version"> }>(
`/api/plugins/annotation-qa/tasks/${taskId}/slice-edit-restorations`,
{ method: "POST" },
payload,
),
saveCombinedDraft: (
taskId: string,
payload: {

View File

@ -2,6 +2,56 @@ import assert from "node:assert/strict";
import test from "node:test";
import * as historyModule from "../../src/lib/annotation-history.js";
test("saving a workspace keeps slice undo and redo durable while later draft edits stay local", async () => {
let time = 0;
const history = historyModule.createAnnotationHistory({ now: () => time });
history.record({ before: "one slice", after: "two slices" });
history.markPersisted();
history.record({ before: "two slices", after: "three slices" });
const restored = [];
const restore = async (value, { persisted }) => {
restored.push({ value, persisted });
return true;
};
assert.equal(await history.undo(restore), true);
time += 1000;
assert.equal(await history.undo(restore), true);
time += 1000;
assert.equal(await history.redo(restore), true);
time += 1000;
assert.equal(await history.redo(restore), true);
assert.deepEqual(restored, [
{ value: "two slices", persisted: false },
{ value: "one slice", persisted: true },
{ value: "two slices", persisted: true },
{ value: "three slices", persisted: false },
]);
});
test("a failed persisted undo keeps the same durable edit available for retry", async () => {
let time = 0;
const history = historyModule.createAnnotationHistory({ now: () => time });
history.record({ before: "one slice", after: "two slices" });
history.markPersisted();
assert.equal(
await history.undo(async (_, context) => {
assert.equal(context.persisted, true);
return false;
}),
false,
);
time += 1000;
assert.equal(await history.redo(async () => true), false);
assert.equal(
await history.undo(async (value, context) => {
assert.equal(value, "one slice");
assert.equal(context.persisted, true);
return true;
}),
true,
);
});
// The restoration callback is the production boundary: callers apply an entire
// edit and report confirmation. Tests observe restored data, never stack layout.
test("undo restores a deleted slice's coverage, dictionary name and status; redo reapplies it", async () => {