Share typed extraction control evidence
This commit is contained in:
@@ -12,9 +12,8 @@ import (
|
||||
const MaxExtractionPayloadBytes int64 = 64 * 1024 * 1024
|
||||
|
||||
const (
|
||||
extractStageName = "extract"
|
||||
extractionLaneKind = "notarius_lane"
|
||||
extractionMetadataRun = "narratio_run_id"
|
||||
extractStageName = "extract"
|
||||
extractionLaneKind = "notarius_lane"
|
||||
)
|
||||
|
||||
// HydrateExtractionArtifacts marks extraction sources available only when the current
|
||||
@@ -89,8 +88,3 @@ func safeExtractionPathSegment(value string) bool {
|
||||
return value != "" && value != "." && value != ".." && filepath.Base(value) == value &&
|
||||
!strings.ContainsAny(value, `/\\`)
|
||||
}
|
||||
|
||||
func extractionMetadataString(metadata map[string]any, key string) string {
|
||||
value, _ := metadata[key].(string)
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
|
||||
@@ -62,7 +62,8 @@ func inspectExtractionEvidence(
|
||||
if !extractionInputMatchesMetadata(r.Metadata, input) {
|
||||
return ExtractionEvidence{State: ExtractionEvidenceObsolete, Reason: "extract result does not match the current trimmed transcript"}
|
||||
}
|
||||
runID := extractionMetadataString(r.Metadata, extractionMetadataRun)
|
||||
metadata := DecodeExtractionMetadata(r.Metadata)
|
||||
runID := metadata.RunID
|
||||
if !safeExtractionPathSegment(runID) {
|
||||
return ExtractionEvidence{State: ExtractionEvidenceObsolete, Reason: "extract result has an invalid producing run ID"}
|
||||
}
|
||||
@@ -71,11 +72,10 @@ func inspectExtractionEvidence(
|
||||
return ExtractionEvidence{State: ExtractionEvidenceUnsafe, Reason: "session root cannot be resolved"}
|
||||
}
|
||||
artifactRoot := filepath.Join(root, "artifacts")
|
||||
completion, ok := r.Metadata["completion"].(map[string]any)
|
||||
if !ok || extractionMetadataString(completion, "pipeline") == "" {
|
||||
if !metadata.CompletionPresent || metadata.Completion.Pipeline == "" {
|
||||
return ExtractionEvidence{State: ExtractionEvidenceObsolete, Reason: "extract result has no native completion identity"}
|
||||
}
|
||||
pipelineID := extractionMetadataString(completion, "pipeline")
|
||||
pipelineID := metadata.Completion.Pipeline
|
||||
expected := make(map[string]ExtractionArtifactDefinition, len(configured))
|
||||
filenames := make(map[string]string, len(configured))
|
||||
for key, definition := range configured {
|
||||
|
||||
@@ -63,14 +63,10 @@ func (identity ExtractionInputIdentity) Metadata() map[string]any {
|
||||
}
|
||||
|
||||
func extractionInputMatchesMetadata(metadata map[string]any, current ExtractionInputIdentity) bool {
|
||||
stored, ok := metadata[extractionMetadataInput].(map[string]any)
|
||||
if !ok || strings.TrimSpace(current.Checksum) == "" || strings.TrimSpace(current.SourceID) == "" {
|
||||
decoded := DecodeExtractionMetadata(metadata)
|
||||
if !decoded.InputPresent || strings.TrimSpace(current.Checksum) == "" || strings.TrimSpace(current.SourceID) == "" {
|
||||
return false
|
||||
}
|
||||
for key, want := range current.Metadata() {
|
||||
if extractionMetadataString(stored, key) != want {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
stored := decoded.Input
|
||||
return stored.Checksum == current.Checksum && stored.SourceID == current.SourceID && stored.ProducerStage == current.ProducerStage && stored.OutputKind == current.OutputKind && stored.ProducerRunID == current.ProducerRunID && stored.Provenance == current.Provenance
|
||||
}
|
||||
|
||||
122
internal/artifacts/extraction_metadata.go
Normal file
122
internal/artifacts/extraction_metadata.go
Normal file
@@ -0,0 +1,122 @@
|
||||
package artifacts
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ExtractionReferenceIdentity identifies one prepared reference in metadata and fingerprints.
|
||||
type ExtractionReferenceIdentity struct {
|
||||
Selector string `json:"selector"`
|
||||
SourceID string `json:"source_id"`
|
||||
Path string `json:"path"`
|
||||
Checksum string `json:"checksum"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
}
|
||||
|
||||
// ExtractionCompletion is the native completion evidence and its diagnostic fields.
|
||||
type ExtractionCompletion struct {
|
||||
Pipeline string
|
||||
ArtifactCount int
|
||||
OutputDirectory string
|
||||
DebugDirectory string
|
||||
FallbackCount int
|
||||
}
|
||||
|
||||
// ExtractionMetadata is the persisted control evidence for generated extraction.
|
||||
type ExtractionMetadata struct {
|
||||
RunID string
|
||||
ConfigurationFingerprint string
|
||||
Input ExtractionInputIdentity
|
||||
InputPresent bool
|
||||
References []ExtractionReferenceIdentity
|
||||
ReferenceCount int
|
||||
Completion ExtractionCompletion
|
||||
CompletionPresent bool
|
||||
}
|
||||
|
||||
func extractionString(fields map[string]any, key string) string {
|
||||
value, _ := fields[key].(string)
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
|
||||
func extractionNumber(value any) int64 {
|
||||
switch v := value.(type) {
|
||||
case int:
|
||||
return int64(v)
|
||||
case int64:
|
||||
return v
|
||||
case float64:
|
||||
if v >= 0 && v == float64(int64(v)) {
|
||||
return int64(v)
|
||||
}
|
||||
case json.Number:
|
||||
n, err := v.Int64()
|
||||
if err == nil {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func extractionFallbackCount(value any) int {
|
||||
switch v := value.(type) {
|
||||
case int:
|
||||
return v
|
||||
case float64:
|
||||
if v > 0 && v == float64(int(v)) {
|
||||
return int(v)
|
||||
}
|
||||
case json.Number:
|
||||
parsed, err := v.Int64()
|
||||
if err == nil && parsed > 0 && int64(int(parsed)) == parsed {
|
||||
return int(parsed)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// DecodeExtractionMetadata reads known fields from direct or JSON-decoded maps.
|
||||
func DecodeExtractionMetadata(metadata map[string]any) ExtractionMetadata {
|
||||
out := ExtractionMetadata{RunID: extractionString(metadata, "narratio_run_id"), ConfigurationFingerprint: extractionString(metadata, "configuration_fingerprint"), ReferenceCount: int(extractionNumber(metadata["reference_count"]))}
|
||||
if input, ok := metadata[extractionMetadataInput].(map[string]any); ok {
|
||||
out.InputPresent = true
|
||||
out.Input = ExtractionInputIdentity{Checksum: extractionString(input, "checksum"), SourceID: extractionString(input, "source_id"), ProducerStage: extractionString(input, "producer_stage"), OutputKind: extractionString(input, "output_kind"), ProducerRunID: extractionString(input, "producer_run_id"), Provenance: extractionString(input, "provenance")}
|
||||
}
|
||||
if completion, ok := metadata["completion"].(map[string]any); ok {
|
||||
out.CompletionPresent = true
|
||||
out.Completion = ExtractionCompletion{Pipeline: extractionString(completion, "pipeline"), ArtifactCount: int(extractionNumber(completion["artifact_count"])), OutputDirectory: extractionString(completion, "output_directory"), DebugDirectory: extractionString(completion, "debug_directory"), FallbackCount: extractionFallbackCount(completion["fallback_count"])}
|
||||
}
|
||||
appendReference := func(row map[string]any) {
|
||||
out.References = append(out.References, ExtractionReferenceIdentity{Selector: extractionString(row, "selector"), SourceID: extractionString(row, "source_id"), Path: extractionString(row, "path"), Checksum: extractionString(row, "checksum"), SizeBytes: extractionNumber(row["size_bytes"])})
|
||||
}
|
||||
switch rows := metadata["references"].(type) {
|
||||
case []map[string]any:
|
||||
for _, row := range rows {
|
||||
appendReference(row)
|
||||
}
|
||||
case []any:
|
||||
for _, raw := range rows {
|
||||
if row, ok := raw.(map[string]any); ok {
|
||||
appendReference(row)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// EncodeExtractionMetadata preserves the existing generated evidence map shape.
|
||||
func EncodeExtractionMetadata(e ExtractionMetadata) map[string]any {
|
||||
refs := make([]map[string]any, 0, len(e.References))
|
||||
for _, r := range e.References {
|
||||
refs = append(refs, map[string]any{"selector": r.Selector, "source_id": r.SourceID, "path": r.Path, "checksum": r.Checksum, "size_bytes": r.SizeBytes})
|
||||
}
|
||||
completion := map[string]any{"pipeline": e.Completion.Pipeline, "artifact_count": e.Completion.ArtifactCount, "output_directory": e.Completion.OutputDirectory}
|
||||
if e.Completion.DebugDirectory != "" {
|
||||
completion["debug_directory"] = e.Completion.DebugDirectory
|
||||
}
|
||||
if e.Completion.FallbackCount > 0 {
|
||||
completion["fallback_count"] = e.Completion.FallbackCount
|
||||
}
|
||||
return map[string]any{"narratio_run_id": e.RunID, "configuration_fingerprint": e.ConfigurationFingerprint, "direct_input": e.Input.Metadata(), "reference_count": e.ReferenceCount, "references": refs, "completion": completion}
|
||||
}
|
||||
46
internal/artifacts/extraction_metadata_test.go
Normal file
46
internal/artifacts/extraction_metadata_test.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package artifacts
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExtractionMetadataRoundTrip(t *testing.T) {
|
||||
source := ExtractionMetadata{RunID: "run", ConfigurationFingerprint: "fingerprint", Input: ExtractionInputIdentity{Checksum: "checksum", SourceID: "source", ProducerStage: "trim", OutputKind: "transcript", ProducerRunID: "input-run", Provenance: "manifest"}, References: []ExtractionReferenceIdentity{{Selector: "people", SourceID: "party", Path: "inputs/party.yml", Checksum: "sum", SizeBytes: 12}}, ReferenceCount: 1, Completion: ExtractionCompletion{Pipeline: "pipeline", ArtifactCount: 2, OutputDirectory: "/output", FallbackCount: 2}}
|
||||
direct := EncodeExtractionMetadata(source)
|
||||
before := DecodeExtractionMetadata(direct)
|
||||
body, err := json.Marshal(direct)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var decoded map[string]any
|
||||
if err := json.Unmarshal(body, &decoded); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := DecodeExtractionMetadata(decoded); !reflect.DeepEqual(got, before) {
|
||||
t.Fatalf("decoded = %+v, want %+v", got, before)
|
||||
}
|
||||
decoder := json.NewDecoder(strings.NewReader(string(body)))
|
||||
decoder.UseNumber()
|
||||
var numberMap map[string]any
|
||||
if err := decoder.Decode(&numberMap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := DecodeExtractionMetadata(numberMap); !reflect.DeepEqual(got, before) {
|
||||
t.Fatalf("number decoded = %+v, want %+v", got, before)
|
||||
}
|
||||
if !extractionInputMatchesMetadata(decoded, source.Input) {
|
||||
t.Fatal("persisted input did not match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractionFallbackMetadataRejectsInvalidNumbers(t *testing.T) {
|
||||
for _, value := range []any{float64(-1), float64(1.5), json.Number("-1"), "2", nil} {
|
||||
got := DecodeExtractionMetadata(map[string]any{"completion": map[string]any{"fallback_count": value}}).Completion.FallbackCount
|
||||
if got != 0 {
|
||||
t.Fatalf("fallback count for %v = %d", value, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -217,21 +217,21 @@ func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (re
|
||||
ExternalProvenance: &artifactmodel.ExternalProvenance{System: "notarius", PipelineID: report.Pipeline, ArtifactID: lane.LaneID},
|
||||
})
|
||||
}
|
||||
completion := map[string]any{"pipeline": report.Pipeline, "artifact_count": report.ArtifactCount, "output_directory": bundle}
|
||||
if report.DebugDirectory != "" {
|
||||
completion["debug_directory"] = report.DebugDirectory
|
||||
}
|
||||
if report.FallbackCount > 0 {
|
||||
completion["fallback_count"] = report.FallbackCount
|
||||
env.Warn(fmt.Sprintf("Notarius completed with %d fallback operations", report.FallbackCount))
|
||||
}
|
||||
metadata := map[string]any{
|
||||
"stage": "extract", "notarius_enabled": true, "bundle_root": bundle,
|
||||
"diagnostic_path": logPath, "narratio_run_id": runID,
|
||||
"configuration_fingerprint": fingerprint, "direct_input": input.Metadata(),
|
||||
"reference_count": len(references.Identities), "references": extractReferenceMetadata(references.Identities),
|
||||
"completion": completion,
|
||||
metadataReferences := references.Identities
|
||||
if len(metadataReferences) > config.MaxNotariusReferenceBindings {
|
||||
metadataReferences = metadataReferences[:config.MaxNotariusReferenceBindings]
|
||||
}
|
||||
metadata := map[string]any{"stage": "extract", "notarius_enabled": true, "bundle_root": bundle, "diagnostic_path": logPath}
|
||||
for key, value := range artifacts.EncodeExtractionMetadata(artifacts.ExtractionMetadata{
|
||||
RunID: runID, ConfigurationFingerprint: fingerprint, Input: input, References: metadataReferences, ReferenceCount: len(references.Identities),
|
||||
Completion: artifacts.ExtractionCompletion{Pipeline: report.Pipeline, ArtifactCount: report.ArtifactCount, OutputDirectory: bundle, DebugDirectory: report.DebugDirectory, FallbackCount: report.FallbackCount},
|
||||
}) {
|
||||
metadata[key] = value
|
||||
}
|
||||
|
||||
result = &StageResult{Outputs: outputs, Logs: []string{reportPath, logPath}, Metadata: metadata}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -20,13 +20,7 @@ import (
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
|
||||
)
|
||||
|
||||
type extractReferenceIdentity struct {
|
||||
Selector string `json:"selector"`
|
||||
SourceID string `json:"source_id"`
|
||||
Path string `json:"path"`
|
||||
Checksum string `json:"checksum"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
}
|
||||
type extractReferenceIdentity = artifacts.ExtractionReferenceIdentity
|
||||
|
||||
func materializeExtractReferenceSnapshots(
|
||||
paths artifacts.SessionPaths,
|
||||
@@ -296,21 +290,3 @@ func resolveExtractReferences(
|
||||
}
|
||||
return resolved, nil
|
||||
}
|
||||
|
||||
func extractReferenceMetadata(identities []extractReferenceIdentity) []map[string]any {
|
||||
limit := len(identities)
|
||||
if limit > config.MaxNotariusReferenceBindings {
|
||||
limit = config.MaxNotariusReferenceBindings
|
||||
}
|
||||
metadata := make([]map[string]any, 0, limit)
|
||||
for _, identity := range identities[:limit] {
|
||||
metadata = append(metadata, map[string]any{
|
||||
"selector": identity.Selector,
|
||||
"source_id": identity.SourceID,
|
||||
"path": identity.Path,
|
||||
"checksum": identity.Checksum,
|
||||
"size_bytes": identity.SizeBytes,
|
||||
})
|
||||
}
|
||||
return metadata
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package stage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
@@ -46,7 +45,7 @@ func (extractStage) ValidateResume(_ context.Context, env *Env, m *manifest.Mani
|
||||
return ResumeValidation{}, fmt.Errorf("extract resume: build configuration fingerprint: %w", err)
|
||||
}
|
||||
record := m.Stages[(extractStage{}).Name()]
|
||||
if record == nil || metadataString(record.Metadata, "configuration_fingerprint") != fingerprint {
|
||||
if record == nil || artifacts.DecodeExtractionMetadata(record.Metadata).ConfigurationFingerprint != fingerprint {
|
||||
return NonResumable("Notarius invocation contract changed"), nil
|
||||
}
|
||||
proof := artifacts.InspectExtractionEvidence(paths, m, definitions, input)
|
||||
@@ -64,27 +63,5 @@ func (extractStage) ValidateResume(_ context.Context, env *Env, m *manifest.Mani
|
||||
|
||||
// ExtractionFallbackCount reports the positive native emitting-operation count.
|
||||
func ExtractionFallbackCount(metadata map[string]any) int {
|
||||
completion, _ := metadata["completion"].(map[string]any)
|
||||
switch value := completion["fallback_count"].(type) {
|
||||
case int:
|
||||
return value
|
||||
case float64:
|
||||
if value > 0 && value == float64(int(value)) {
|
||||
return int(value)
|
||||
}
|
||||
case json.Number:
|
||||
parsed, err := value.Int64()
|
||||
if err == nil && parsed > 0 && int64(int(parsed)) == parsed {
|
||||
return int(parsed)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func metadataString(metadata map[string]any, key string) string {
|
||||
if metadata == nil {
|
||||
return ""
|
||||
}
|
||||
value, _ := metadata[key].(string)
|
||||
return strings.TrimSpace(value)
|
||||
return artifacts.DecodeExtractionMetadata(metadata).Completion.FallbackCount
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user