Add D&D item event normalization
This commit is contained in:
131
internal/modules/dnd/validate/itemevents/invariants/validator.go
Normal file
131
internal/modules/dnd/validate/itemevents/invariants/validator.go
Normal file
@@ -0,0 +1,131 @@
|
||||
// Package invariants validates normalized D&D item-event artifacts.
|
||||
package invariants
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
itemeventmodel "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/itemevents"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
|
||||
itemeventshape "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/validate/itemevents/shape"
|
||||
)
|
||||
|
||||
const (
|
||||
Key = "normalize/dnd/item-events/invariants"
|
||||
ReasonCode = "invalid_normalized_item_event_invariants"
|
||||
policy = "dnd.item_events.normalize_invariants.v1"
|
||||
)
|
||||
|
||||
type Options struct{}
|
||||
type Validator struct{}
|
||||
|
||||
var _ contracts.TypedValidator[dnd.ItemEventList] = (*Validator)(nil)
|
||||
var _ pipeline.CheckpointFingerprintProvider = (*Validator)(nil)
|
||||
|
||||
func New(Options) *Validator { return &Validator{} }
|
||||
func (v *Validator) Name() string { return Key }
|
||||
func (v *Validator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
func (v *Validator) CheckpointFingerprints() []pipeline.CheckpointFingerprint {
|
||||
return []pipeline.CheckpointFingerprint{{Name: "policy", Value: policy}}
|
||||
}
|
||||
|
||||
func (v *Validator) Validate(_ context.Context, req contracts.TypedValidationRequest[dnd.ItemEventList]) (contracts.ValidationResult, error) {
|
||||
if err := Validate(req.Source, req.Value); err != nil {
|
||||
return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCode, Message: err.Error()}, nil
|
||||
}
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
|
||||
// Validate checks only invariants introduced by item-event normalization.
|
||||
// Shape and source-reference failures remain owned by their earlier validators.
|
||||
func Validate(doc *source.SourceDocument, value dnd.ItemEventList) error {
|
||||
if itemeventshape.Validate(value) != nil {
|
||||
return nil
|
||||
}
|
||||
index := source.NewDocumentIndex(doc)
|
||||
if !sourceRefsValid(index, value) {
|
||||
return nil
|
||||
}
|
||||
issues := issuesFor(shared.NewSourceRefOrderFromIndex(index), value)
|
||||
if len(issues) == 0 {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%s", diagnostics.Aggregate("invalid normalized item event invariants", issues))
|
||||
}
|
||||
|
||||
func issuesFor(order shared.SourceRefOrder, value dnd.ItemEventList) []string {
|
||||
issues := make([]string, 0)
|
||||
seenIdentity := make(map[string]int)
|
||||
for eventIndex, event := range value.Events {
|
||||
prefix := fmt.Sprintf("events[%d]", eventIndex)
|
||||
if event.Name != itemeventmodel.DisplayValue(event.Name) {
|
||||
issues = append(issues, prefix+".name is not display-normalized")
|
||||
}
|
||||
if event.From != itemeventmodel.DisplayValue(event.From) {
|
||||
issues = append(issues, prefix+".from is not display-normalized")
|
||||
}
|
||||
if event.To != itemeventmodel.DisplayValue(event.To) {
|
||||
issues = append(issues, prefix+".to is not display-normalized")
|
||||
}
|
||||
for refIndex := 1; refIndex < len(event.SourceRefs); refIndex++ {
|
||||
previous := event.SourceRefs[refIndex-1]
|
||||
current := event.SourceRefs[refIndex]
|
||||
if order.Less(current, previous) {
|
||||
issues = append(issues, fmt.Sprintf("%s.source_refs are not in canonical order at index %d", prefix, refIndex))
|
||||
} else if current == previous {
|
||||
issues = append(issues, fmt.Sprintf("%s.source_refs[%d] duplicates the previous reference", prefix, refIndex))
|
||||
}
|
||||
}
|
||||
key := itemeventmodel.ExactIdentity(order, event)
|
||||
if previous, exists := seenIdentity[key]; exists {
|
||||
issues = append(issues, fmt.Sprintf("%s duplicates item event %d under normalized identity", prefix, previous))
|
||||
} else {
|
||||
seenIdentity[key] = eventIndex
|
||||
}
|
||||
}
|
||||
for eventIndex := 1; eventIndex < len(value.Events); eventIndex++ {
|
||||
if itemeventmodel.Less(order, value.Events[eventIndex], value.Events[eventIndex-1]) {
|
||||
issues = append(issues, fmt.Sprintf("events[%d] is out of canonical order", eventIndex))
|
||||
}
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
func sourceRefsValid(index source.DocumentIndex, value dnd.ItemEventList) bool {
|
||||
for _, event := range value.Events {
|
||||
if !itemeventmodel.ValidSourceRefs(index, event.SourceRefs) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func Spec() pipeline.ValidatorSpec {
|
||||
return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
|
||||
}
|
||||
|
||||
func Register(registry *pipeline.ValidatorRegistry) error {
|
||||
return pipeline.RegisterTypedValidatorBuilder(registry, dnd.ItemEventListKind, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.TypedValidator[dnd.ItemEventList], error) {
|
||||
options, err := DecodeOptions(request.Options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return New(options), nil
|
||||
})
|
||||
}
|
||||
|
||||
func DecodeOptions(options map[string]any) (Options, error) {
|
||||
if err := pipeline.RejectUnknownOptions(options); err != nil {
|
||||
return Options{}, err
|
||||
}
|
||||
return Options{}, nil
|
||||
}
|
||||
|
||||
func validateOptions(options map[string]any) error { _, err := DecodeOptions(options); return err }
|
||||
@@ -0,0 +1,129 @@
|
||||
package invariants
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
normalizeitemevents "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/normalize/itemevents"
|
||||
)
|
||||
|
||||
func TestValidatorApprovesNormalizerOutput(t *testing.T) {
|
||||
doc := invariantDocument()
|
||||
input := dnd.ItemEventList{Events: []dnd.ItemEvent{
|
||||
{Name: " Coin ", Kind: dnd.ItemEventKindDiscovered, SourceRefs: []source.SourceRef{{SourceID: doc.ID, StartUnitID: 20, EndUnitID: 20}}},
|
||||
{Name: "Arrow", Kind: dnd.ItemEventKindDiscovered, SourceRefs: []source.SourceRef{{SourceID: doc.ID, StartUnitID: 10, EndUnitID: 10}}},
|
||||
}}
|
||||
normalized, err := normalizeitemevents.New(normalizeitemevents.Options{}).Normalize(context.Background(), contracts.TypedNormalizeRequest[dnd.ItemEventList]{Source: doc, MergeOutput: contracts.MergeArtifact[dnd.ItemEventList]{Value: input}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemEventList]{Source: doc, Value: normalized.Value})
|
||||
if err != nil || !result.Approved {
|
||||
t.Fatalf("Validate() = %#v, %v; want approval", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRejectsOwnedNormalizedInvariants(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*dnd.ItemEventList)
|
||||
want string
|
||||
}{
|
||||
{name: "name whitespace", mutate: func(value *dnd.ItemEventList) { value.Events[0].Name = " Coin " }, want: ".name is not display-normalized"},
|
||||
{name: "from whitespace", mutate: func(value *dnd.ItemEventList) {
|
||||
value.Events[0].Kind = dnd.ItemEventKindLost
|
||||
value.Events[0].From = " Aria "
|
||||
}, want: ".from is not display-normalized"},
|
||||
{name: "to whitespace", mutate: func(value *dnd.ItemEventList) {
|
||||
value.Events[0].Kind = dnd.ItemEventKindAcquired
|
||||
value.Events[0].To = " Aria "
|
||||
}, want: ".to is not display-normalized"},
|
||||
{name: "reference order", mutate: func(value *dnd.ItemEventList) {
|
||||
value.Events[0].SourceRefs = []source.SourceRef{{SourceID: "session", StartUnitID: 20, EndUnitID: 20}, {SourceID: "session", StartUnitID: 10, EndUnitID: 10}}
|
||||
}, want: "not in canonical order"},
|
||||
{name: "duplicate reference", mutate: func(value *dnd.ItemEventList) {
|
||||
value.Events[0].SourceRefs = append(value.Events[0].SourceRefs, value.Events[0].SourceRefs[0])
|
||||
}, want: "duplicates the previous reference"},
|
||||
{name: "list order", mutate: func(value *dnd.ItemEventList) { value.Events = []dnd.ItemEvent{value.Events[1], value.Events[0]} }, want: "out of canonical order"},
|
||||
{name: "duplicate event", mutate: func(value *dnd.ItemEventList) { value.Events = append(value.Events, value.Events[0]) }, want: "duplicates item event"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
value := normalizedList()
|
||||
test.mutate(&value)
|
||||
err := Validate(invariantDocument(), value)
|
||||
if err == nil || !strings.Contains(err.Error(), test.want) {
|
||||
t.Fatalf("Validate() error = %v, want %q", err, test.want)
|
||||
}
|
||||
result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemEventList]{Source: invariantDocument(), Value: value})
|
||||
if err != nil || result.Approved || result.ReasonCode != ReasonCode {
|
||||
t.Fatalf("validator result = %#v, %v", result, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateUsesSourceDocumentOrderAndDefersEarlierFailures(t *testing.T) {
|
||||
doc := &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 30}, {ID: 10}}}
|
||||
value := dnd.ItemEventList{Events: []dnd.ItemEvent{{
|
||||
Name: "Coin", Kind: dnd.ItemEventKindDiscovered,
|
||||
SourceRefs: []source.SourceRef{{SourceID: doc.ID, StartUnitID: 10, EndUnitID: 10}, {SourceID: doc.ID, StartUnitID: 30, EndUnitID: 30}},
|
||||
}}}
|
||||
if err := Validate(doc, value); err == nil || !strings.Contains(err.Error(), "not in canonical order") {
|
||||
t.Fatalf("Validate() error = %v, want document-order rejection", err)
|
||||
}
|
||||
shapeInvalid := normalizedList()
|
||||
shapeInvalid.Events[0].Name = " "
|
||||
if err := Validate(invariantDocument(), shapeInvalid); err != nil {
|
||||
t.Fatalf("shape failure must be deferred, got %v", err)
|
||||
}
|
||||
sourceInvalid := normalizedList()
|
||||
sourceInvalid.Events[0].SourceRefs[0].StartUnitID = 999
|
||||
if err := Validate(invariantDocument(), sourceInvalid); err != nil {
|
||||
t.Fatalf("source-reference failure must be deferred, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatorContractAndBoundedDiagnostics(t *testing.T) {
|
||||
value := normalizedList()
|
||||
value.Events = make([]dnd.ItemEvent, 30)
|
||||
for index := range value.Events {
|
||||
value.Events[index] = normalizedList().Events[0]
|
||||
value.Events[index].Name = strings.Repeat("火", 300)
|
||||
}
|
||||
result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemEventList]{Source: invariantDocument(), Value: value})
|
||||
if err != nil || result.Approved || !utf8.ValidString(result.Message) || len([]byte(result.Message)) > 4096 || !strings.Contains(result.Message, "additional issue(s) omitted") {
|
||||
t.Fatalf("bounded result = %#v, %v", result, err)
|
||||
}
|
||||
if got := New(Options{}).CheckpointFingerprints(); !reflect.DeepEqual(got, []pipeline.CheckpointFingerprint{{Name: "policy", Value: policy}}) {
|
||||
t.Fatalf("CheckpointFingerprints() = %#v", got)
|
||||
}
|
||||
if spec := Spec(); spec.Key != Key || spec.ExecutionClass != contracts.ExecutionClassDeterministic {
|
||||
t.Fatalf("Spec() = %#v", spec)
|
||||
}
|
||||
registry := pipeline.NewValidatorRegistry()
|
||||
if err := Register(registry); err != nil {
|
||||
t.Fatalf("Register() error = %v", err)
|
||||
}
|
||||
if _, err := DecodeOptions(map[string]any{"unexpected": true}); err == nil {
|
||||
t.Fatal("DecodeOptions() accepted unknown option")
|
||||
}
|
||||
}
|
||||
|
||||
func normalizedList() dnd.ItemEventList {
|
||||
return dnd.ItemEventList{Events: []dnd.ItemEvent{
|
||||
{Name: "Arrow", Kind: dnd.ItemEventKindDiscovered, SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 10, EndUnitID: 10}}},
|
||||
{Name: "Coin", Kind: dnd.ItemEventKindDiscovered, SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 20, EndUnitID: 20}}},
|
||||
}}
|
||||
}
|
||||
|
||||
func invariantDocument() *source.SourceDocument {
|
||||
return &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 10}, {ID: 20}}}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ func (v *Validator) Validate(_ context.Context, req contracts.TypedValidationReq
|
||||
issues := make([]string, 0)
|
||||
for eventIndex, event := range req.Value.Events {
|
||||
if itemevents.ValidSourceRefs(index, event.SourceRefs) {
|
||||
if req.Stage != string(pipeline.StageExtract) || refsFitChunk(req.Chunk, event.SourceRefs) {
|
||||
if req.Stage != string(pipeline.StageExtract) || refsFitChunk(req.Source, req.Chunk, event.SourceRefs) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,7 @@ func (v *Validator) Validate(_ context.Context, req contracts.TypedValidationReq
|
||||
issues = append(issues, fmt.Sprintf("events[%d].source_refs[%d]: %s", eventIndex, refIndex, diagnostics.Truncate(err.Error())))
|
||||
continue
|
||||
}
|
||||
if req.Stage == string(pipeline.StageExtract) && !chunkContainsRef(req.Chunk, ref) {
|
||||
if req.Stage == string(pipeline.StageExtract) && !chunkContainsRef(req.Source, req.Chunk, ref) {
|
||||
issues = append(issues, fmt.Sprintf("events[%d].source_refs[%d]: source reference is outside the current extraction chunk", eventIndex, refIndex))
|
||||
}
|
||||
}
|
||||
@@ -66,26 +66,34 @@ func (v *Validator) Validate(_ context.Context, req contracts.TypedValidationReq
|
||||
return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCode, Message: diagnostics.Aggregate("invalid item event source references", issues)}, nil
|
||||
}
|
||||
|
||||
func refsFitChunk(chunk *source.Chunk, refs []source.SourceRef) bool {
|
||||
func refsFitChunk(doc *source.SourceDocument, chunk *source.Chunk, refs []source.SourceRef) bool {
|
||||
for _, ref := range refs {
|
||||
if !chunkContainsRef(chunk, ref) {
|
||||
if !chunkContainsRef(doc, chunk, ref) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func chunkContainsRef(chunk *source.Chunk, ref source.SourceRef) bool {
|
||||
func chunkContainsRef(doc *source.SourceDocument, chunk *source.Chunk, ref source.SourceRef) bool {
|
||||
if chunk == nil || ref.SourceID != chunk.SourceID {
|
||||
return false
|
||||
}
|
||||
startFound := false
|
||||
endFound := false
|
||||
for _, unit := range chunk.Units {
|
||||
startFound = startFound || unit.ID == ref.StartUnitID
|
||||
endFound = endFound || unit.ID == ref.EndUnitID
|
||||
start, startOK := source.UnitIndex(doc, ref.StartUnitID)
|
||||
end, endOK := source.UnitIndex(doc, ref.EndUnitID)
|
||||
if !startOK || !endOK || start > end {
|
||||
return false
|
||||
}
|
||||
return startFound && endFound
|
||||
units := make(map[int]struct{}, len(chunk.Units))
|
||||
for _, unit := range chunk.Units {
|
||||
units[unit.ID] = struct{}{}
|
||||
}
|
||||
for position := start; position <= end; position++ {
|
||||
if _, found := units[doc.Units[position].ID]; !found {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func Spec() pipeline.ValidatorSpec {
|
||||
|
||||
@@ -51,6 +51,14 @@ func TestValidatorEnforcesChunkOnlyDuringExtraction(t *testing.T) {
|
||||
t.Fatalf("out-of-chunk evidence = %#v, %v", result, err)
|
||||
}
|
||||
|
||||
noncontiguousChunk := &source.Chunk{ID: "chunk-1", SourceID: doc.ID, Units: []source.SourceUnit{doc.Units[0], doc.Units[2]}}
|
||||
spansMissingUnit := validList()
|
||||
spansMissingUnit.Events[0].SourceRefs = []source.SourceRef{{SourceID: doc.ID, StartUnitID: 1, EndUnitID: 3}}
|
||||
result, err = New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemEventList]{Stage: string(pipeline.StageExtract), Source: doc, Chunk: noncontiguousChunk, Value: spansMissingUnit})
|
||||
if err != nil || result.Approved || !strings.Contains(result.Message, "outside the current extraction chunk") {
|
||||
t.Fatalf("partially contained evidence = %#v, %v", result, err)
|
||||
}
|
||||
|
||||
multiRange := validList()
|
||||
multiRange.Events[0].SourceRefs = []source.SourceRef{{SourceID: doc.ID, StartUnitID: 1, EndUnitID: 2}, {SourceID: doc.ID, StartUnitID: 3, EndUnitID: 4}}
|
||||
result, err = New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemEventList]{Source: doc, Value: multiRange})
|
||||
|
||||
Reference in New Issue
Block a user