droboticflow/internal/api/slice_merge_evidence.go

289 lines
10 KiB
Go

package api
import (
"math"
"slices"
"sort"
"droboticflow/internal/domain"
)
const sliceMergeEvidenceKey = "sliceMergeEvidence"
type sliceMergeEvidence struct {
Before []domain.SliceSegment `json:"before"`
After domain.SliceSegment `json:"after"`
Revision int `json:"revision"`
Phase string `json:"phase"`
}
// Operation snapshots are client input. Only replay a chain anchored to the
// current server partition, and derive every intermediate audit/archive from
// that partition rather than accepting evidence from the snapshots.
func replayLocalSliceMerges(previous, proposed []domain.SliceSegment, operations []domain.SliceOperation) ([]domain.SliceSegment, []sliceMergeEvidence) {
hasMerge := false
for _, operation := range operations {
hasMerge = hasMerge || operation.Type == "merge" || operation.Type == "delete"
}
if !hasMerge {
return nil, nil
}
for start := len(operations) - 1; start >= 0; start-- {
if !sameSlicePartition(previous, operations[start].Before) {
continue
}
current := previous
var merges []sliceMergeEvidence
valid := true
for _, operation := range operations[start:] {
if !sameSlicePartition(current, operation.Before) || !sameSliceCoverage(current, operation.After) {
valid = false
break
}
switch operation.Type {
case "split":
valid = validLocalSliceSplit(current, operation)
case "merge", "delete":
valid = false
if len(operation.After) == len(current)-1 {
for _, candidate := range operation.After {
sources := explicitSliceMerge(current, candidate)
if len(sources) != 2 || len(operation.SegmentIDs) == 0 || len(operation.SegmentIDs) > 2 {
continue
}
valid = true
for _, id := range operation.SegmentIDs {
valid = valid && (id == sources[0].ID || id == sources[1].ID)
}
remainingBefore := slices.DeleteFunc(append([]domain.SliceSegment(nil), current...), func(v domain.SliceSegment) bool { return v.ID == sources[0].ID || v.ID == sources[1].ID })
remainingAfter := slices.DeleteFunc(append([]domain.SliceSegment(nil), operation.After...), func(v domain.SliceSegment) bool { return v.ID == candidate.ID })
valid = valid && sameSlicePartition(remainingBefore, remainingAfter)
if valid {
merges = append(merges, sliceMergeEvidence{Before: sources, After: clearedMergedSlice(candidate)})
}
break
}
}
case "adjust":
valid = len(current) == len(operation.After)
for _, old := range current {
found := false
for _, candidate := range operation.After {
found = found || (old.ID == candidate.ID && sliceDisposition(old) == sliceDisposition(candidate) && old.DiscardReason == candidate.DiscardReason)
}
valid = valid && found
}
default:
valid = false
}
if !valid {
break
}
next, issues := canonicalDispositions(current, operation.After)
if len(issues) > 0 {
valid = false
break
}
current = next
}
if valid && len(merges) > 0 && sameSlicePartition(current, proposed) {
return current, merges
}
}
return nil, nil
}
func sameSlicePartition(left, right []domain.SliceSegment) bool {
if len(left) != len(right) {
return false
}
for _, old := range left {
found := false
for _, candidate := range right {
found = found || (old.ID == candidate.ID && old.Start == candidate.Start && old.End == candidate.End && sliceDisposition(old) == sliceDisposition(candidate) && old.DiscardReason == candidate.DiscardReason)
}
if !found {
return false
}
}
return true
}
func sameSliceCoverage(previous, next []domain.SliceSegment) bool {
if len(previous) == 0 || len(next) == 0 {
return false
}
ordered := append([]domain.SliceSegment(nil), next...)
sort.Slice(ordered, func(i, j int) bool { return ordered[i].Start < ordered[j].Start })
start, end := previous[0].Start, previous[0].End
for _, old := range previous {
start, end = math.Min(start, old.Start), math.Max(end, old.End)
}
if ordered[0].Start != start || ordered[len(ordered)-1].End != end {
return false
}
seen := map[string]bool{}
for i, candidate := range ordered {
if candidate.ID == "" || seen[candidate.ID] || math.IsNaN(candidate.Start) || math.IsNaN(candidate.End) || candidate.End <= candidate.Start || (i > 0 && ordered[i-1].End != candidate.Start) {
return false
}
seen[candidate.ID] = true
}
return true
}
func validLocalSliceSplit(previous []domain.SliceSegment, operation domain.SliceOperation) bool {
if len(operation.SegmentIDs) != 1 || len(operation.After) != len(previous)+1 {
return false
}
for _, old := range previous {
if old.ID != operation.SegmentIDs[0] {
continue
}
if operation.At <= old.Start || operation.At >= old.End {
return false
}
var children, unchanged []domain.SliceSegment
for _, candidate := range operation.After {
if candidate.Start >= old.Start && candidate.End <= old.End {
if !slices.Contains(candidate.SourceIDs, old.ID) || sliceDisposition(candidate) != sliceDisposition(old) || candidate.DiscardReason != old.DiscardReason {
return false
}
children = append(children, candidate)
} else {
unchanged = append(unchanged, candidate)
}
}
remaining := slices.DeleteFunc(append([]domain.SliceSegment(nil), previous...), func(v domain.SliceSegment) bool { return v.ID == old.ID })
if len(children) != 2 || !sameSlicePartition(remaining, unchanged) {
return false
}
sort.Slice(children, func(i, j int) bool { return children[i].Start < children[j].Start })
return children[0].Start == old.Start && children[0].End == operation.At && children[1].Start == operation.At && children[1].End == old.End
}
return false
}
// A cancel-cut explicitly lists the two immediate source IDs first. Further
// lineage may describe several local merges, but never authorizes dropping an
// unrelated interval or changing the outer coverage.
func explicitSliceMerge(previous []domain.SliceSegment, candidate domain.SliceSegment) []domain.SliceSegment {
if sliceDisposition(candidate) != "keep" || candidate.DiscardReason != "" || len(candidate.SourceIDs) < 2 || candidate.SourceIDs[0] == candidate.SourceIDs[1] || (candidate.ID != candidate.SourceIDs[0] && candidate.ID != candidate.SourceIDs[1]) {
return nil
}
var sources []domain.SliceSegment
for _, old := range previous {
if old.Start >= candidate.Start && old.End <= candidate.End && old.End > old.Start {
if !slices.Contains(candidate.SourceIDs, old.ID) {
return nil
}
sources = append(sources, old)
} else if old.Start < candidate.End && old.End > candidate.Start {
return nil
}
}
if len(sources) < 2 {
return nil
}
sort.Slice(sources, func(i, j int) bool { return sources[i].Start < sources[j].Start })
if sources[0].Start != candidate.Start || sources[len(sources)-1].End != candidate.End {
return nil
}
for i := 1; i < len(sources); i++ {
if sources[i-1].End != sources[i].Start {
return nil
}
}
return sources
}
func clearedMergedSlice(candidate domain.SliceSegment) domain.SliceSegment {
return domain.SliceSegment{ID: candidate.ID, Name: candidate.Name, Start: candidate.Start, End: candidate.End, StartTimestampUS: candidate.StartTimestampUS, EndTimestampUS: candidate.EndTimestampUS, SourceIDs: append([]string(nil), candidate.SourceIDs...), DeliveryDisposition: "keep", AnnotationStatus: domain.SliceAnnotationPending}
}
// Undoing a saved merge may recover only an exact partition recorded by this
// server in this editing epoch. Its audit identity and archived actions come
// from the evidence, never the client snapshot.
func previousForSliceMergeUndo(item *domain.HumanItemRecord, previous, proposed []domain.SliceSegment) []domain.SliceSegment {
result := append([]domain.SliceSegment(nil), previous...)
phase := stringValue(mapValue(item.Subject.Payload["sliceWorkflow"])["phase"])
records := decodeMaterializationValue[sliceMergeEvidence](item.Subject.Payload[sliceMergeEvidenceKey])
for n := len(records) - 1; n >= 0; n-- {
record := records[n]
if record.Revision != item.CurrentRevision || record.Phase != phase {
continue
}
current := -1
for i, old := range result {
if old.ID == record.After.ID && old.Start == record.After.Start && old.End == record.After.End && !old.IsDiscarded() {
current = i
break
}
}
if current < 0 {
continue
}
recovered := []domain.SliceSegment{}
matches := true
for _, candidate := range proposed {
if candidate.End <= record.After.Start || candidate.Start >= record.After.End {
continue
}
if candidate.Start < record.After.Start || candidate.End > record.After.End {
matches = false
break
}
found := false
for _, old := range record.Before {
if candidate.ID == old.ID && candidate.Start == old.Start && candidate.End == old.End && sliceDisposition(candidate) == sliceDisposition(old) && candidate.DiscardReason == old.DiscardReason {
found = true
break
}
}
if !found && len(explicitSliceMerge(record.Before, candidate)) == 0 {
matches = false
break
}
recovered = append(recovered, candidate)
}
sort.Slice(recovered, func(i, j int) bool { return recovered[i].Start < recovered[j].Start })
if len(recovered) < 2 || recovered[0].Start != record.After.Start || recovered[len(recovered)-1].End != record.After.End {
matches = false
}
for i := 1; i < len(recovered); i++ {
if recovered[i-1].End != recovered[i].Start {
matches = false
}
}
if !matches {
continue
}
result = append(result[:current], result[current+1:]...)
result = append(result, record.Before...)
}
return result
}
func recordSliceMerges(item *domain.HumanItemRecord, previous, next []domain.SliceSegment, localMerges ...sliceMergeEvidence) {
phase := stringValue(mapValue(item.Subject.Payload["sliceWorkflow"])["phase"])
records := decodeMaterializationValue[sliceMergeEvidence](item.Subject.Payload[sliceMergeEvidenceKey])
for _, merge := range localMerges {
merge.Revision, merge.Phase = item.CurrentRevision, phase
records = append(records, merge)
}
for _, candidate := range next {
if sources := explicitSliceMerge(previous, candidate); len(sources) > 0 {
records = append(records, sliceMergeEvidence{Before: sources, After: candidate, Revision: item.CurrentRevision, Phase: phase})
}
}
// Matches the workbench's 100-step undo window. Permanent disposition/reset
// audits remain separate and are not truncated here.
if len(records) > 100 {
records = records[len(records)-100:]
}
if len(records) > 0 {
item.Subject.Payload[sliceMergeEvidenceKey] = records
}
}