Avoid redundant decoded graph clones

This commit is contained in:
2026-08-09 01:34:26 +00:00
parent 1456aa51cc
commit d36d4e7689
5 changed files with 29 additions and 17 deletions

View File

@@ -93,11 +93,11 @@ func (c *Codec) Decode(content []byte) (Document, error) {
if err := decoder.Decode(&trailing); err != io.EOF {
return Document{}, fmt.Errorf("decode evidence context: multiple JSON values")
}
canonical, err := canonicalize(value)
canonical, err := canonicalizeOwned(value)
if err != nil {
return Document{}, fmt.Errorf("decode evidence context: %w", err)
}
return clone(canonical)
return canonical, nil
}
func (c *Codec) schemaBytes() ([]byte, error) {
@@ -171,7 +171,10 @@ func canonicalize(value Document) (Document, error) {
if err != nil {
return Document{}, err
}
value = owned
return canonicalizeOwned(owned)
}
func canonicalizeOwned(value Document) (Document, error) {
if err := requireIdentity("source_id", value.SourceID); err != nil {
return Document{}, err
}
@@ -230,10 +233,7 @@ func canonicalizeContext(sourceID string, selected map[string]struct{}, seenUnit
}
positions := make(map[int]int, len(value.Units))
for unitIndex := range value.Units {
unit, err := cloneSourceUnit(value.Units[unitIndex])
if err != nil {
return Context{}, fmt.Errorf("%s.units[%d]: %w", prefix, unitIndex, err)
}
unit := value.Units[unitIndex]
if unit.ID <= 0 || strings.TrimSpace(unit.Kind) == "" || strings.TrimSpace(unit.Text) == "" {
return Context{}, fmt.Errorf("%s.units[%d] has invalid required fields", prefix, unitIndex)
}
@@ -251,7 +251,6 @@ func canonicalizeContext(sourceID string, selected map[string]struct{}, seenUnit
}
positions[unit.ID] = unitIndex
seenUnits[unit.ID] = struct{}{}
value.Units[unitIndex] = unit
}
if value.ContextRef.StartUnitID != value.Units[0].ID || value.ContextRef.EndUnitID != value.Units[len(value.Units)-1].ID {
return Context{}, fmt.Errorf("%s.context_ref must identify the first and last units", prefix)