Promote native Notarius lane products
This commit is contained in:
@@ -47,7 +47,13 @@ func (cleanupStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("cleanup canceled before %s: %w", target.policy, err)
|
||||
}
|
||||
if err := fileops.RemoveAllUnderRoot(target.root, target.target); err != nil {
|
||||
var err error
|
||||
if target.policy == cleanupWorkspacePolicy {
|
||||
_, err = cleanRunWithRetainedBundle(target.root, target.target, true)
|
||||
} else {
|
||||
err = fileops.RemoveAllUnderRoot(target.root, target.target)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("apply %s: %w", target.policy, err)
|
||||
}
|
||||
completedPolicies = append(completedPolicies, target.policy)
|
||||
@@ -85,6 +91,16 @@ func (cleanupStage) ValidateResume(ctx context.Context, env *Env, m *manifest.Ma
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ResumeValidation{}, fmt.Errorf("validate cleanup resume for %s: %w", target.policy, err)
|
||||
}
|
||||
if target.policy == cleanupWorkspacePolicy {
|
||||
pending, err := cleanRunWithRetainedBundle(target.root, target.target, false)
|
||||
if err != nil {
|
||||
return ResumeValidation{}, err
|
||||
}
|
||||
if pending {
|
||||
return NonResumable(fmt.Sprintf("cleanup target for %s exists", target.policy)), nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := os.Lstat(target.target); err == nil {
|
||||
return NonResumable(fmt.Sprintf("cleanup target for %s exists", target.policy)), nil
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
|
||||
100
internal/stage/cleanup_retained_bundle.go
Normal file
100
internal/stage/cleanup_retained_bundle.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
||||
)
|
||||
|
||||
// cleanRunWithRetainedBundle removes ordinary run data while preserving a
|
||||
// bundle explicitly marked for the session lifetime. A later whole-session
|
||||
// removal still removes the retained evidence.
|
||||
func cleanRunWithRetainedBundle(workspaceRoot, runRoot string, remove bool) (bool, error) {
|
||||
runRoot, err := filepath.Abs(runRoot)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
info, err := os.Lstat(runRoot)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return false, fmt.Errorf("unsafe run cleanup directory %q", runRoot)
|
||||
}
|
||||
extract := filepath.Join(runRoot, "extract")
|
||||
info, err = os.Lstat(extract)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
if remove {
|
||||
return true, fileops.RemoveAllUnderRoot(workspaceRoot, runRoot)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return false, fmt.Errorf("unsafe extract cleanup directory %q", extract)
|
||||
}
|
||||
marker := filepath.Join(extract, "notarius-retention.json")
|
||||
info, err = os.Lstat(marker)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
if remove {
|
||||
return true, fileops.RemoveAllUnderRoot(workspaceRoot, runRoot)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return false, fmt.Errorf("unsafe Notarius retention marker %q", marker)
|
||||
}
|
||||
body, err := fileops.ReadFileBounded(marker, artifacts.MaxExtractionPayloadBytes)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("read Notarius retention marker: %w", err)
|
||||
}
|
||||
var record struct {
|
||||
Role string `json:"role"`
|
||||
BundleRoot string `json:"bundle_root"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &record); err != nil || record.Role != "session_durable" {
|
||||
return false, fmt.Errorf("invalid Notarius retention marker %q", marker)
|
||||
}
|
||||
outputRoot := filepath.Join(extract, "notarius-output")
|
||||
if err := validateExtractBundleRoot(outputRoot, record.BundleRoot); err != nil {
|
||||
return false, fmt.Errorf("invalid retained Notarius bundle: %w", err)
|
||||
}
|
||||
pending := false
|
||||
for _, directory := range []struct {
|
||||
path string
|
||||
keep map[string]bool
|
||||
}{
|
||||
{runRoot, map[string]bool{"extract": true}},
|
||||
{extract, map[string]bool{"notarius-output": true, "notarius-retention.json": true}},
|
||||
} {
|
||||
entries, err := os.ReadDir(directory.path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if directory.keep[entry.Name()] {
|
||||
continue
|
||||
}
|
||||
pending = true
|
||||
if remove {
|
||||
if err := fileops.RemoveAllUnderRoot(workspaceRoot, filepath.Join(directory.path, entry.Name())); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return pending, nil
|
||||
}
|
||||
@@ -20,14 +20,11 @@ import (
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
extractSkipReason = "notarius_disabled"
|
||||
extractLaneOutputKind = "notarius_lane"
|
||||
extractIndexOutputKind = "notarius_index"
|
||||
maxDiagnosticSummaries = 100
|
||||
extractSkipReason = "notarius_disabled"
|
||||
extractLaneOutputKind = "notarius_lane"
|
||||
)
|
||||
|
||||
type extractStage struct{}
|
||||
@@ -120,11 +117,7 @@ func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (re
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve output root: %w", err)
|
||||
}
|
||||
durableBundle, err := absolutePath(artifacts.SessionNotariusBundleDirForCampaign(workspaceRoot, campaign, sessionID, runID))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve durable bundle path: %w", err)
|
||||
}
|
||||
directories := []string{filepath.Dir(receiptPath), outputRoot, filepath.Dir(durableBundle)}
|
||||
directories := []string{filepath.Dir(receiptPath), outputRoot}
|
||||
for _, directory := range directories {
|
||||
if err := fileops.EnsureWorkspaceDirectory(directory); err != nil {
|
||||
return nil, fmt.Errorf("extract: create directory %q: %w", directory, err)
|
||||
@@ -134,7 +127,6 @@ func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (re
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: materialize Notarius reference snapshots: %w", err)
|
||||
}
|
||||
|
||||
fingerprint, err := extractionFingerprint(notariusConfig, input, references.Identities)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: build configuration fingerprint: %w", err)
|
||||
@@ -152,181 +144,107 @@ func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (re
|
||||
Binary: resolvedBinary, Credentials: notariusConfig.Credentials, ConfigOverlay: notariusConfig.ConfigOverlay,
|
||||
ConfigPath: configPath, PipelineID: notariusConfig.PipelineID,
|
||||
InputPath: inputPath, OutputRoot: outputRoot, WorkingDirectory: workingDirectory,
|
||||
ReceiptPath: receiptPath, LogPath: logPath, Timeout: timeout, Cache: cache, Debug: notariusConfig.Debug, DebugDirectory: debugDirectory, References: referenceBindings,
|
||||
ReceiptPath: receiptPath, LogPath: logPath, Timeout: timeout, Cache: cache,
|
||||
Debug: notariusConfig.Debug, DebugDirectory: debugDirectory, References: referenceBindings,
|
||||
}
|
||||
stageSucceeded := false
|
||||
bundleMoved := false
|
||||
accepted := false
|
||||
defer func() {
|
||||
if stageSucceeded {
|
||||
return
|
||||
}
|
||||
if bundleMoved {
|
||||
if cleanupErr := fileops.RemoveAllUnderRoot(filepath.Dir(durableBundle), durableBundle); cleanupErr != nil {
|
||||
resultErr = errors.Join(resultErr, fmt.Errorf("extract: remove failed durable Notarius bundle: %w", cleanupErr))
|
||||
if !accepted {
|
||||
if cleanupErr := fileops.RemoveAllUnderRoot(filepath.Dir(outputRoot), outputRoot); cleanupErr != nil {
|
||||
resultErr = errors.Join(resultErr, fmt.Errorf("extract: remove failed Notarius output root: %w", cleanupErr))
|
||||
}
|
||||
}
|
||||
if cleanupErr := fileops.RemoveAllUnderRoot(filepath.Dir(outputRoot), outputRoot); cleanupErr != nil {
|
||||
resultErr = errors.Join(resultErr, fmt.Errorf("extract: remove failed Notarius output root: %w", cleanupErr))
|
||||
}
|
||||
}()
|
||||
adapterResult, err := env.Notarius.Run(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: run notarius: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(adapterResult.BundleRoot) == "" || strings.TrimSpace(adapterResult.Index.Path) == "" {
|
||||
return nil, fmt.Errorf("extract: notarius result is missing bundle or index path")
|
||||
report := adapterResult.Report
|
||||
bundle := filepath.Clean(adapterResult.BundleRoot)
|
||||
if report.Pipeline != notariusConfig.PipelineID || report.ArtifactCount < 0 || report.FallbackCount < 0 ||
|
||||
!filepath.IsAbs(bundle) || filepath.Clean(report.OutputDirectory) != bundle {
|
||||
return nil, fmt.Errorf("extract: notarius completion report is missing or incompatible")
|
||||
}
|
||||
if adapterResult.Receipt.RunID == "" || adapterResult.Receipt.PipelineID != notariusConfig.PipelineID {
|
||||
return nil, fmt.Errorf("extract: notarius receipt identity is missing or incompatible")
|
||||
if err := validateExtractBundleRoot(outputRoot, bundle); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := normalizeNotariusBundle(bundle); err != nil {
|
||||
return nil, fmt.Errorf("extract: validate Notarius bundle: %w", err)
|
||||
}
|
||||
if err := verifyExtractReferenceSnapshots(paths, references); err != nil {
|
||||
return nil, fmt.Errorf("extract: verify Notarius reference snapshots: %w", err)
|
||||
}
|
||||
|
||||
selected, err := selectRequiredNotariusLanes(env.ArtifactStore, notariusConfig.Outputs, adapterResult)
|
||||
staging, err := os.MkdirTemp(filepath.Dir(outputRoot), ".products-")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: create product staging directory: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if cleanupErr := fileops.RemoveAllUnderRoot(filepath.Dir(staging), staging); cleanupErr != nil {
|
||||
resultErr = errors.Join(resultErr, fmt.Errorf("extract: remove staged products: %w", cleanupErr))
|
||||
}
|
||||
}()
|
||||
selected, err := stageRequiredNotariusLanes(bundle, staging, notariusConfig.Outputs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
indexRelative, err := pathsafe.SlashRelativeFromRoot(adapterResult.BundleRoot, adapterResult.Index.Path)
|
||||
root, err := absolutePath(paths.Root)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve staging index relative path: %w", err)
|
||||
return nil, fmt.Errorf("extract: resolve session root: %w", err)
|
||||
}
|
||||
rejectionsRelative, err := pathsafe.SlashRelativeFromRoot(adapterResult.BundleRoot, adapterResult.Index.RejectedPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve staging rejections relative path: %w", err)
|
||||
artifactDir := filepath.Join(root, "artifacts")
|
||||
if err := checkExtractSnapshotDirectory(root, artifactDir, true); err != nil {
|
||||
return nil, fmt.Errorf("extract: validate artifact directory: %w", err)
|
||||
}
|
||||
warningsRelative, err := pathsafe.SlashRelativeFromRoot(adapterResult.BundleRoot, adapterResult.Index.WarningsPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve staging warnings relative path: %w", err)
|
||||
}
|
||||
diagnosticsRelative, err := pathsafe.SlashRelativeFromRoot(adapterResult.BundleRoot, adapterResult.Index.DiagnosticsPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve staging diagnostics relative path: %w", err)
|
||||
}
|
||||
stagingIndexChecksum, err := checksumRegularFile(adapterResult.Index.Path, false)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: validate staging index: %w", err)
|
||||
}
|
||||
|
||||
bundleRelative, err := pathsafe.SlashRelativeFromRoot(outputRoot, adapterResult.BundleRoot)
|
||||
if err != nil || bundleRelative == "." || bundleRelative == "" {
|
||||
return nil, fmt.Errorf("extract: Notarius bundle must be a proper descendant of the run output root")
|
||||
}
|
||||
if err := normalizeNotariusBundle(adapterResult.BundleRoot); err != nil {
|
||||
return nil, fmt.Errorf("extract: normalize Notarius bundle: %w", err)
|
||||
}
|
||||
if _, err := os.Lstat(durableBundle); err == nil {
|
||||
return nil, fmt.Errorf("extract: durable Notarius bundle destination already exists")
|
||||
} else if !os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("extract: inspect durable Notarius bundle destination: %w", err)
|
||||
}
|
||||
if err := os.Rename(adapterResult.BundleRoot, durableBundle); err != nil {
|
||||
return nil, fmt.Errorf("extract: install Notarius bundle: %w", err)
|
||||
}
|
||||
bundleMoved = true
|
||||
if err := os.Remove(outputRoot); err != nil && !os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("extract: remove empty Notarius output root: %w", err)
|
||||
}
|
||||
promotedIndexPath, err := pathsafe.JoinSlashRelativeUnderRoot(durableBundle, indexRelative)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve promoted index: %w", err)
|
||||
}
|
||||
promotedIndexChecksum, err := checksumRegularFile(promotedIndexPath, false)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: checksum promoted index: %w", err)
|
||||
}
|
||||
if promotedIndexChecksum != stagingIndexChecksum {
|
||||
return nil, fmt.Errorf("extract: promoted index checksum differs from staging index")
|
||||
}
|
||||
promotedRejectionsPath, err := pathsafe.JoinSlashRelativeUnderRoot(durableBundle, rejectionsRelative)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve promoted rejections: %w", err)
|
||||
}
|
||||
promotedWarningsPath, err := pathsafe.JoinSlashRelativeUnderRoot(durableBundle, warningsRelative)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve promoted warnings: %w", err)
|
||||
}
|
||||
promotedDiagnosticsPath, err := pathsafe.JoinSlashRelativeUnderRoot(durableBundle, diagnosticsRelative)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve promoted diagnostics: %w", err)
|
||||
}
|
||||
|
||||
outputs := make([]artifacts.Ref, 0, len(selected)+1)
|
||||
outputs := make([]artifacts.Ref, 0, len(selected))
|
||||
for _, lane := range selected {
|
||||
promotedPath, err := pathsafe.JoinSlashRelativeUnderRoot(durableBundle, lane.RelativePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve promoted lane %q: %w", lane.Descriptor.LaneID, err)
|
||||
destination := filepath.Join(artifactDir, lane.Filename)
|
||||
if info, statErr := os.Lstat(destination); statErr == nil {
|
||||
if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return nil, fmt.Errorf("extract: output %q is not a regular file", destination)
|
||||
}
|
||||
} else if !os.IsNotExist(statErr) {
|
||||
return nil, fmt.Errorf("extract: inspect output: %w", statErr)
|
||||
}
|
||||
checksum, err := checksumRegularFile(promotedPath, true)
|
||||
checksum, err := fileops.CopyFileAtomicWithChecksum(lane.StagedPath, destination, fileops.WorkspaceFileMode)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: validate promoted lane %q: %w", lane.Descriptor.LaneID, err)
|
||||
return nil, fmt.Errorf("extract: promote lane %q: %w", lane.LaneID, err)
|
||||
}
|
||||
if checksum != lane.StagingChecksum {
|
||||
return nil, fmt.Errorf("extract: promoted lane %q checksum differs from staging payload", lane.Descriptor.LaneID)
|
||||
}
|
||||
relativePath, err := pathsafe.SlashRelativeFromRoot(paths.Root, promotedPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: derive lane %q session-relative path: %w", lane.Descriptor.LaneID, err)
|
||||
if checksum != lane.Checksum {
|
||||
return nil, fmt.Errorf("extract: promoted lane %q checksum differs from staged bytes", lane.LaneID)
|
||||
}
|
||||
outputs = append(outputs, artifacts.Ref{
|
||||
Kind: extractLaneOutputKind, SourceID: artifacts.ExtractionArtifactSourceID(lane.Key),
|
||||
Category: "artifacts", SessionID: sessionID, RelativePath: relativePath,
|
||||
AbsolutePath: promotedPath, Checksum: checksum,
|
||||
Contract: &artifactmodel.ContractMetadata{
|
||||
MediaType: lane.Descriptor.MediaType, SchemaID: lane.Descriptor.SchemaID,
|
||||
SchemaVersion: lane.Descriptor.SchemaVersion, ModuleKey: lane.Descriptor.ModuleKey,
|
||||
},
|
||||
ExternalProvenance: &artifactmodel.ExternalProvenance{
|
||||
System: "notarius", RunID: adapterResult.Receipt.RunID,
|
||||
PipelineID: adapterResult.Receipt.PipelineID, ArtifactID: lane.Descriptor.LaneID,
|
||||
},
|
||||
Category: "artifacts", SessionID: sessionID, RelativePath: filepath.ToSlash(filepath.Join("artifacts", lane.Filename)),
|
||||
AbsolutePath: destination, Checksum: checksum, Size: lane.Size,
|
||||
ExternalProvenance: &artifactmodel.ExternalProvenance{System: "notarius", PipelineID: report.Pipeline, ArtifactID: lane.LaneID},
|
||||
})
|
||||
}
|
||||
indexSessionRelative, err := pathsafe.SlashRelativeFromRoot(paths.Root, promotedIndexPath)
|
||||
retentionPath := artifacts.SessionRunNotariusRetentionPath(paths, runID)
|
||||
retention, err := json.Marshal(map[string]any{"role": "session_durable", "bundle_root": bundle})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: derive index session-relative path: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
if err := fileops.WriteFileAtomic(retentionPath, append(retention, '\n'), fileops.WorkspaceFileMode); err != nil {
|
||||
return nil, fmt.Errorf("extract: record bundle retention: %w", err)
|
||||
}
|
||||
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))
|
||||
}
|
||||
outputs = append(outputs, artifacts.Ref{
|
||||
Kind: extractIndexOutputKind, Category: "artifacts", SessionID: sessionID,
|
||||
RelativePath: indexSessionRelative, AbsolutePath: promotedIndexPath, Checksum: promotedIndexChecksum,
|
||||
})
|
||||
|
||||
metadata := map[string]any{
|
||||
"stage": "extract",
|
||||
"notarius_enabled": true,
|
||||
"bundle_root": durableBundle,
|
||||
"receipt_path": receiptPath,
|
||||
"diagnostic_path": logPath,
|
||||
"rejections_path": promotedRejectionsPath,
|
||||
"warnings_path": promotedWarningsPath,
|
||||
"diagnostics_path": promotedDiagnosticsPath,
|
||||
"narratio_run_id": runID,
|
||||
"configuration_fingerprint": fingerprint,
|
||||
"direct_input": input.Metadata(),
|
||||
"reference_count": len(references.Identities),
|
||||
"references": extractReferenceMetadata(references.Identities),
|
||||
"receipt": map[string]any{
|
||||
"run_id": adapterResult.Receipt.RunID, "pipeline_id": adapterResult.Receipt.PipelineID,
|
||||
"normalized_output_count": adapterResult.Receipt.NormalizedOutputCount,
|
||||
"rejected_output_count": adapterResult.Receipt.RejectedOutputCount,
|
||||
"warning_group_count": adapterResult.Receipt.WarningGroupCount,
|
||||
"warning_occurrence_count": adapterResult.Receipt.WarningOccurrenceCount,
|
||||
"diagnostic_group_count": adapterResult.Receipt.DiagnosticGroupCount,
|
||||
"diagnostic_occurrence_count": adapterResult.Receipt.DiagnosticOccurrenceCount,
|
||||
"diagnostics_truncated": adapterResult.Receipt.DiagnosticsTruncated,
|
||||
"validation_status": adapterResult.Receipt.ValidationStatus,
|
||||
},
|
||||
"rejections": boundedRejectionMetadata(adapterResult.Rejections),
|
||||
"warnings": boundedWarningMetadata(adapterResult.Warnings),
|
||||
"diagnostics": boundedDiagnosticMetadata(adapterResult.Diagnostics),
|
||||
"validation_summaries": boundedValidationMetadata(adapterResult.Receipt.ValidationSummaries),
|
||||
"stage": "extract", "notarius_enabled": true, "bundle_root": bundle,
|
||||
"bundle_retention_role": "session_durable", "retention_path": retentionPath,
|
||||
"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,
|
||||
}
|
||||
result = &StageResult{
|
||||
Outputs: outputs,
|
||||
Logs: []string{receiptPath, logPath},
|
||||
Metadata: metadata,
|
||||
}
|
||||
stageSucceeded = true
|
||||
result = &StageResult{Outputs: outputs, Logs: []string{receiptPath, logPath}, Metadata: metadata}
|
||||
accepted = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -352,104 +270,14 @@ func normalizeNotariusBundle(root string) error {
|
||||
})
|
||||
}
|
||||
|
||||
type selectedNotariusLane struct {
|
||||
Key string
|
||||
Descriptor notarius.LaneDescriptor
|
||||
RelativePath string
|
||||
StagingChecksum string
|
||||
}
|
||||
|
||||
func selectRequiredNotariusLanes(
|
||||
store artifacts.Store,
|
||||
required map[string]config.NotariusOutputConfig,
|
||||
result notarius.RunResult,
|
||||
) ([]selectedNotariusLane, error) {
|
||||
keys := make([]string, 0, len(required))
|
||||
for key := range required {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
selected := make([]selectedNotariusLane, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
expected := required[key]
|
||||
for _, rejection := range result.Rejections {
|
||||
if rejection.LaneID == expected.LaneID {
|
||||
return nil, fmt.Errorf("extract: required lane %q was rejected (reason_code=%q)", expected.LaneID, rejection.ReasonCode)
|
||||
}
|
||||
}
|
||||
for _, validation := range result.Receipt.ValidationSummaries {
|
||||
if validation.LaneID == expected.LaneID && validation.Status != "complete" {
|
||||
return nil, fmt.Errorf("extract: required lane %q validation is %q", expected.LaneID, validation.Status)
|
||||
}
|
||||
}
|
||||
matches := make([]notarius.LaneDescriptor, 0, 1)
|
||||
for _, descriptor := range result.Index.Lanes {
|
||||
if descriptor.LaneID == expected.LaneID {
|
||||
matches = append(matches, descriptor)
|
||||
}
|
||||
}
|
||||
if len(matches) != 1 {
|
||||
return nil, fmt.Errorf("extract: required lane %q has %d descriptors, want exactly one", expected.LaneID, len(matches))
|
||||
}
|
||||
descriptor := matches[0]
|
||||
if descriptor.MediaType != expected.MediaType || descriptor.SchemaID != expected.SchemaID ||
|
||||
descriptor.SchemaVersion != expected.SchemaVersion ||
|
||||
(expected.ModuleKey != "" && descriptor.ModuleKey != expected.ModuleKey) {
|
||||
return nil, fmt.Errorf("extract: required lane %q descriptor contract is incompatible", expected.LaneID)
|
||||
}
|
||||
checksum, err := checksumRegularFile(descriptor.Path, true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: validate required lane %q: %w", expected.LaneID, err)
|
||||
}
|
||||
if store != nil {
|
||||
storeChecksum, err := store.Checksum(descriptor.Path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: checksum required lane %q: %w", expected.LaneID, err)
|
||||
}
|
||||
if storeChecksum != checksum {
|
||||
return nil, fmt.Errorf("extract: inconsistent staging checksum for required lane %q", expected.LaneID)
|
||||
}
|
||||
}
|
||||
relative, err := pathsafe.SlashRelativeFromRoot(result.BundleRoot, descriptor.Path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve required lane %q relative path: %w", expected.LaneID, err)
|
||||
}
|
||||
selected = append(selected, selectedNotariusLane{
|
||||
Key: key, Descriptor: descriptor, RelativePath: relative, StagingChecksum: checksum,
|
||||
})
|
||||
}
|
||||
return selected, nil
|
||||
}
|
||||
|
||||
func checksumRegularFile(path string, requireJSON bool) (string, error) {
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
|
||||
return "", fmt.Errorf("path %q must be a regular file without symlinks", path)
|
||||
}
|
||||
if info.Size() == 0 {
|
||||
return "", fmt.Errorf("path %q must be non-empty", path)
|
||||
}
|
||||
data, err := fileops.ReadFileBounded(path, artifacts.MaxExtractionPayloadBytes)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("notarius lane result exceeds or cannot be read within %d-byte limit: %w", artifacts.MaxExtractionPayloadBytes, err)
|
||||
}
|
||||
if requireJSON && !json.Valid(data) {
|
||||
return "", fmt.Errorf("path %q is not valid JSON", path)
|
||||
}
|
||||
digest := sha256.Sum256(data)
|
||||
return hex.EncodeToString(digest[:]), nil
|
||||
}
|
||||
|
||||
type fingerprintOutput struct {
|
||||
Key string `json:"key"`
|
||||
LaneID string `json:"lane_id"`
|
||||
MediaType string `json:"media_type"`
|
||||
SchemaID string `json:"schema_id"`
|
||||
SchemaVersion string `json:"schema_version"`
|
||||
ModuleKey string `json:"module_key,omitempty"`
|
||||
Filename string `json:"filename"`
|
||||
MediaType string `json:"-"`
|
||||
SchemaID string `json:"-"`
|
||||
SchemaVersion string `json:"-"`
|
||||
ModuleKey string `json:"-"`
|
||||
}
|
||||
|
||||
type fingerprintDocument struct {
|
||||
@@ -474,8 +302,7 @@ func extractionFingerprint(
|
||||
for _, key := range keys {
|
||||
output := cfg.Outputs[key]
|
||||
outputs = append(outputs, fingerprintOutput{
|
||||
Key: key, LaneID: output.LaneID, MediaType: output.MediaType,
|
||||
SchemaID: output.SchemaID, SchemaVersion: output.SchemaVersion, ModuleKey: output.ModuleKey,
|
||||
Key: key, LaneID: output.LaneID, Filename: config.ExtractionFilename(key, output),
|
||||
})
|
||||
}
|
||||
sortedReferences := append([]extractReferenceIdentity(nil), references...)
|
||||
@@ -523,76 +350,3 @@ func safePathSegment(value string) bool {
|
||||
return value != "" && value != "." && value != ".." && filepath.Base(value) == value &&
|
||||
!strings.ContainsAny(value, `/\\`)
|
||||
}
|
||||
|
||||
func boundedRejectionMetadata(values []notarius.RejectionSummary) []map[string]any {
|
||||
limit := len(values)
|
||||
if limit > maxDiagnosticSummaries {
|
||||
limit = maxDiagnosticSummaries
|
||||
}
|
||||
result := make([]map[string]any, 0, limit)
|
||||
for _, value := range values[:limit] {
|
||||
result = append(result, map[string]any{
|
||||
"stage": value.Stage, "step_id": value.StepID, "lane_id": value.LaneID,
|
||||
"module_key": value.ModuleKey, "chunk_id": value.ChunkID,
|
||||
"validator_name": value.ValidatorName, "reason_code": value.ReasonCode,
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func boundedWarningMetadata(values []notarius.WarningSummary) []map[string]any {
|
||||
limit := len(values)
|
||||
if limit > maxDiagnosticSummaries {
|
||||
limit = maxDiagnosticSummaries
|
||||
}
|
||||
result := make([]map[string]any, 0, limit)
|
||||
for _, value := range values[:limit] {
|
||||
result = append(result, map[string]any{
|
||||
"disposition": value.Disposition, "category": value.Category,
|
||||
"reason_code": value.ReasonCode, "origin": diagnosticOriginMetadata(value.Origin),
|
||||
"occurrence_count": value.OccurrenceCount,
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func boundedDiagnosticMetadata(values []notarius.DiagnosticSummary) []map[string]any {
|
||||
limit := len(values)
|
||||
if limit > maxDiagnosticSummaries {
|
||||
limit = maxDiagnosticSummaries
|
||||
}
|
||||
result := make([]map[string]any, 0, limit)
|
||||
for _, value := range values[:limit] {
|
||||
result = append(result, map[string]any{
|
||||
"disposition": value.Disposition, "category": value.Category,
|
||||
"reason_code": value.ReasonCode, "origin": diagnosticOriginMetadata(value.Origin),
|
||||
"occurrence_count": value.OccurrenceCount,
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func boundedValidationMetadata(values []notarius.ValidationSummary) []map[string]any {
|
||||
limit := len(values)
|
||||
if limit > maxDiagnosticSummaries {
|
||||
limit = maxDiagnosticSummaries
|
||||
}
|
||||
result := make([]map[string]any, 0, limit)
|
||||
for _, value := range values[:limit] {
|
||||
result = append(result, map[string]any{
|
||||
"stage": value.Stage, "step_id": value.StepID, "lane_id": value.LaneID,
|
||||
"module_key": value.ModuleKey, "chunk_id": value.ChunkID, "status": value.Status,
|
||||
"rejecting_validators": value.RejectingValidators, "reason_codes": value.ReasonCodes,
|
||||
"incomplete_validators": value.IncompleteValidators,
|
||||
"producer_attempt_count": value.ProducerAttemptCount, "terminal_action": value.TerminalAction,
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func diagnosticOriginMetadata(value notarius.DiagnosticOrigin) map[string]any {
|
||||
return map[string]any{
|
||||
"stage": value.Stage, "step_id": value.StepID, "lane_id": value.LaneID,
|
||||
"module_key": value.ModuleKey, "validator_key": value.ValidatorKey,
|
||||
}
|
||||
}
|
||||
|
||||
356
internal/stage/extract_native_test.go
Normal file
356
internal/stage/extract_native_test.go
Normal file
@@ -0,0 +1,356 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||
)
|
||||
|
||||
type extractionWarnings struct{ messages []string }
|
||||
|
||||
func (*extractionWarnings) Info(string, ...any) {}
|
||||
func (r *extractionWarnings) Warn(message string, _ ...any) { r.messages = append(r.messages, message) }
|
||||
func (*extractionWarnings) Debug(string, ...any) {}
|
||||
func (*extractionWarnings) Progress(string, ...any) {}
|
||||
|
||||
func nativeExtractFixture(t *testing.T) (*Env, *manifest.Manifest, *notarius.FakeRunner) {
|
||||
t.Helper()
|
||||
env, m, fake := setupExtractEnv(t)
|
||||
bundle := fake.Result.BundleRoot
|
||||
fake.Result = notarius.RunResult{BundleRoot: bundle, Report: notarius.CompletionReport{Pipeline: "dnd-session", ArtifactCount: 12, OutputDirectory: bundle, FallbackCount: 2}}
|
||||
if err := os.WriteFile(filepath.Join(bundle, "lanes", "npc-registry.json"), []byte(`{"npcs":[]}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return env, m, fake
|
||||
}
|
||||
|
||||
func nativeRecordResult(m *manifest.Manifest, result *StageResult) {
|
||||
records := make([]manifest.ArtifactRecord, 0, len(result.Outputs))
|
||||
for _, output := range result.Outputs {
|
||||
records = append(records, manifest.ArtifactRecord{Kind: output.Kind, SourceID: output.SourceID, LocalPath: output.AbsolutePath, ProducerRunID: m.RunID, Checksum: output.Checksum, Size: output.Size, ExternalProvenance: output.ExternalProvenance})
|
||||
}
|
||||
m.MarkStageSucceeded("extract", time.Now().UTC(), records)
|
||||
m.Stages["extract"].Metadata = result.Metadata
|
||||
}
|
||||
|
||||
func TestNativeExtractionPromotesRequiredLanesAndReusesCanonicalProducts(t *testing.T) {
|
||||
env, m, fake := nativeExtractFixture(t)
|
||||
reporter := &extractionWarnings{}
|
||||
env.Reporter = reporter
|
||||
outputs := map[string]config.NotariusOutputConfig{}
|
||||
for _, lane := range []string{"spells", "npc-registry", "npc-occurrences", "combat-turns", "item-registry", "item-occurrences", "scene-descriptions", "enemy-events", "location-registry", "location-occurrences"} {
|
||||
key := strings.ReplaceAll(lane, "-", "_")
|
||||
outputs[key] = config.NotariusOutputConfig{LaneID: lane}
|
||||
if err := os.WriteFile(filepath.Join(fake.Result.BundleRoot, "lanes", lane+".json"), []byte(`{"synthetic":true}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
outputs["spells"] = config.NotariusOutputConfig{LaneID: "spells", Filename: "custom-spells.json"}
|
||||
env.Config.Pipeline.Notarius.Outputs = outputs
|
||||
cache := "bypass"
|
||||
env.Config.Pipeline.Notarius.Cache = &cache
|
||||
result, err := (extractStage{}).Run(context.Background(), env, m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(result.Outputs) != 10 || fake.Requests[0].Cache == nil || *fake.Requests[0].Cache != "bypass" {
|
||||
t.Fatalf("outputs/request = %#v %#v", result.Outputs, fake.Requests)
|
||||
}
|
||||
if len(reporter.messages) != 1 || !strings.Contains(reporter.messages[0], "fallback") {
|
||||
t.Fatalf("warnings = %#v", reporter.messages)
|
||||
}
|
||||
for _, output := range result.Outputs {
|
||||
if output.Size == 0 || output.Checksum == "" || filepath.Dir(output.AbsolutePath) != filepath.Join(env.Config.Pipeline.Workspace.Root, "work", m.Campaign, m.SessionID, "artifacts") {
|
||||
t.Fatalf("output = %#v", output)
|
||||
}
|
||||
}
|
||||
marker := result.Metadata["retention_path"].(string)
|
||||
content, err := os.ReadFile(marker)
|
||||
if err != nil || !strings.Contains(string(content), "session_durable") {
|
||||
t.Fatalf("retention = %s, %v", content, err)
|
||||
}
|
||||
nativeRecordResult(m, result)
|
||||
encoded, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var restored manifest.Manifest
|
||||
if err := json.Unmarshal(encoded, &restored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
*m = restored
|
||||
// Reuse is based on canonical files even after the original bundle disappears.
|
||||
if err := os.RemoveAll(fake.Result.BundleRoot); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
validation, err := (extractStage{}).ValidateResume(context.Background(), env, m)
|
||||
if err != nil || !validation.Resumable {
|
||||
t.Fatalf("resume = %#v, %v", validation, err)
|
||||
}
|
||||
if len(reporter.messages) != 2 || !strings.Contains(reporter.messages[1], "fallback") {
|
||||
t.Fatalf("reuse warnings = %#v", reporter.messages)
|
||||
}
|
||||
paths := sessionPathsForEnv(env, m.SessionID)
|
||||
catalog := artifacts.NewArtifactCatalog()
|
||||
definitions := artifacts.ExtractionDefinitionsFromConfig(env.Config.Pipeline.Notarius)
|
||||
if err := catalog.RegisterExtractionArtifacts(definitions); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
catalog.HydrateExtractionArtifacts(paths, m, definitions)
|
||||
entry, ok := catalog.Lookup(artifacts.ExtractionArtifactSourceID("spells"))
|
||||
if !ok || !entry.Available || filepath.Base(entry.Path) != "custom-spells.json" {
|
||||
t.Fatalf("catalog entry = %#v", entry)
|
||||
}
|
||||
inputs, err := resolveAnalyzeInputIdentities(map[string]config.ScriptoriumInputConfig{"spells": {Source: artifacts.ExtractionArtifactSourceID("spells"), Required: true}}, analyzeExecutionContext{Env: env, Manifest: m, Paths: paths, SessionID: m.SessionID, Catalog: catalog})
|
||||
if err != nil || inputs.Paths()["spells"] != entry.Path || len(inputs.Ordered) != 1 || inputs.Ordered[0].Checksum != entry.Checksum {
|
||||
t.Fatalf("analysis input = %#v, %v", inputs, err)
|
||||
}
|
||||
rules, err := PlanPublicationOutputs(catalog, []config.PublishOutputRule{{Source: artifacts.ExtractionArtifactSourceID("spells"), Dest: "remote/archive/spells.json"}}, nil)
|
||||
if err != nil || len(rules) != 1 || rules[0].Destination != "remote/archive/spells.json" {
|
||||
t.Fatalf("publication rules = %#v, %v", rules, err)
|
||||
}
|
||||
published, err := discoverPublishOutputs(paths, m, catalog, rules, nil)
|
||||
if err != nil || len(published) != 1 || published[0].LocalPath != entry.Path {
|
||||
t.Fatalf("publication source = %#v, %v", published, err)
|
||||
}
|
||||
if err := os.WriteFile(entry.Path, []byte(`{"tampered":true}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
validation, err = (extractStage{}).ValidateResume(context.Background(), env, m)
|
||||
if err != nil || validation.Resumable {
|
||||
t.Fatalf("tampered resume = %#v, %v", validation, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeExtractionStagesAllFilesBeforePromotion(t *testing.T) {
|
||||
for _, unsafe := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "missing", true: "symlink"}[unsafe], func(t *testing.T) {
|
||||
env, m, fake := nativeExtractFixture(t)
|
||||
env.Config.Pipeline.Notarius.Outputs["missing"] = config.NotariusOutputConfig{LaneID: "missing"}
|
||||
oldPath := filepath.Join(env.Config.Pipeline.Workspace.Root, "work", m.Campaign, m.SessionID, "artifacts", "npc_registry.json")
|
||||
if err := os.WriteFile(oldPath, []byte(`{"old":true}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if unsafe {
|
||||
outside := filepath.Join(t.TempDir(), "outside.json")
|
||||
if err := os.WriteFile(outside, []byte(`{}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(fake.Result.BundleRoot, "lanes", "missing.json")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := (extractStage{}).Run(context.Background(), env, m); err == nil {
|
||||
t.Fatal("missing or unsafe lane accepted")
|
||||
}
|
||||
data, err := os.ReadFile(oldPath)
|
||||
if err != nil || string(data) != `{"old":true}` {
|
||||
t.Fatalf("prior output = %q, %v", data, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeExtractionForceAndReferenceEvidence(t *testing.T) {
|
||||
env, m, fake := nativeExtractFixture(t)
|
||||
env.Force = true
|
||||
cache := "bypass"
|
||||
env.Config.Pipeline.Notarius.Cache = &cache
|
||||
env.Config.Pipeline.Notarius.References = map[string]string{"party": artifactpolicy.SourceInputParty}
|
||||
path := recordPreparedExtractInput(t, env, m, artifactpolicy.SourceInputParty, "party-reference\n")
|
||||
result, err := (extractStage{}).Run(context.Background(), env, m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fake.Requests[0].Cache == nil || *fake.Requests[0].Cache != "refresh" {
|
||||
t.Fatalf("force cache = %#v", fake.Requests[0].Cache)
|
||||
}
|
||||
nativeRecordResult(m, result)
|
||||
if err := os.WriteFile(path, []byte("different-party\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
checksum, err := artifacts.SHA256File(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := range m.Inputs {
|
||||
if m.Inputs[i].Path == path {
|
||||
m.Inputs[i].Checksum = checksum
|
||||
m.Inputs[i].Size = int64(len("different-party\n"))
|
||||
}
|
||||
}
|
||||
validation, err := (extractStage{}).ValidateResume(context.Background(), env, m)
|
||||
if err != nil || validation.Resumable {
|
||||
t.Fatalf("changed reference resume = %#v, %v", validation, err)
|
||||
}
|
||||
// Metadata survives the same JSON representation used by the manifest store.
|
||||
body, err := json.Marshal(m.Stages["extract"].Metadata)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var restored map[string]any
|
||||
if err := json.Unmarshal(body, &restored); err != nil || ExtractionFallbackCount(restored) != 2 {
|
||||
t.Fatalf("fallback metadata = %#v, %v", restored, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeExtractionReuseIdentityIgnoresCacheAndDebug(t *testing.T) {
|
||||
env, m, _ := nativeExtractFixture(t)
|
||||
result, err := (extractStage{}).Run(context.Background(), env, m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nativeRecordResult(m, result)
|
||||
before, err := (extractStage{}).SemanticConfigFingerprint(env)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mode := "refresh"
|
||||
env.Config.Pipeline.Notarius.Cache = &mode
|
||||
env.Config.Pipeline.Notarius.Debug = true
|
||||
after, err := (extractStage{}).SemanticConfigFingerprint(env)
|
||||
if err != nil || before != after {
|
||||
t.Fatalf("operational settings changed identity: %#v %#v %v", before, after, err)
|
||||
}
|
||||
validation, err := (extractStage{}).ValidateResume(context.Background(), env, m)
|
||||
if err != nil || !validation.Resumable {
|
||||
t.Fatalf("resume after operational changes = %#v, %v", validation, err)
|
||||
}
|
||||
output := env.Config.Pipeline.Notarius.Outputs["npc_registry"]
|
||||
output.Filename = "renamed.json"
|
||||
env.Config.Pipeline.Notarius.Outputs["npc_registry"] = output
|
||||
validation, err = (extractStage{}).ValidateResume(context.Background(), env, m)
|
||||
if err != nil || validation.Resumable {
|
||||
t.Fatalf("resume after output rename = %#v, %v", validation, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeExtractionRejectsMappedLaneCollisions(t *testing.T) {
|
||||
staging, bundle := t.TempDir(), t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(bundle, "lanes"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(bundle, "lanes", "a_b.json"), []byte(`{}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
required := map[string]config.NotariusOutputConfig{"first": {LaneID: "a/b"}, "second": {LaneID: "a?b"}}
|
||||
if _, err := stageRequiredNotariusLanes(bundle, staging, required); err == nil || !strings.Contains(err.Error(), "same file") {
|
||||
t.Fatalf("collision error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeExtractionRetentionSurvivesRunCleanup(t *testing.T) {
|
||||
env, m, fake := nativeExtractFixture(t)
|
||||
result, err := (extractStage{}).Run(context.Background(), env, m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runRoot := artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, m.RunID)
|
||||
if err := os.Mkdir(filepath.Join(runRoot, "other"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(runRoot, "other", "temporary"), []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cleanRunWithRetainedBundle(env.Config.Pipeline.Workspace.Root, runRoot, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(fake.Result.BundleRoot, "chunk-map.json")); err != nil {
|
||||
t.Fatalf("retained auxiliary: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(result.Metadata["retention_path"].(string)); err != nil {
|
||||
t.Fatalf("retention marker: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(runRoot, "other")); !os.IsNotExist(err) {
|
||||
t.Fatalf("ordinary run data remains: %v", err)
|
||||
}
|
||||
pending, err := cleanRunWithRetainedBundle(env.Config.Pipeline.Workspace.Root, runRoot, false)
|
||||
if err != nil || pending {
|
||||
t.Fatalf("cleanup resume = %v, %v", pending, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeExtractionReportsPartialPromotionFailure(t *testing.T) {
|
||||
env, m, fake := nativeExtractFixture(t)
|
||||
env.Config.Pipeline.Notarius.Outputs = map[string]config.NotariusOutputConfig{"alpha": {LaneID: "alpha"}, "zeta": {LaneID: "zeta"}}
|
||||
for _, lane := range []string{"alpha", "zeta"} {
|
||||
if err := os.WriteFile(filepath.Join(fake.Result.BundleRoot, "lanes", lane+".json"), []byte(`{"new":true}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
artifactDir := filepath.Join(env.Config.Pipeline.Workspace.Root, "work", m.Campaign, m.SessionID, "artifacts")
|
||||
if err := os.WriteFile(filepath.Join(artifactDir, "alpha.json"), []byte(`{"old":true}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(artifactDir, "zeta.json"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := (extractStage{}).Run(context.Background(), env, m); err == nil {
|
||||
t.Fatal("unsafe promotion destination accepted")
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(artifactDir, "alpha.json"))
|
||||
if err != nil || string(data) != `{"new":true}` {
|
||||
t.Fatalf("first promotion = %q, %v", data, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeExtractionThroughSubprocess(t *testing.T) {
|
||||
env, m, fake := nativeExtractFixture(t)
|
||||
report, err := json.Marshal(map[string]any{"pipeline": "dnd-session", "artifact_count": 1, "output_directory": fake.Result.BundleRoot, "fallback_count": 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script := "#!/bin/sh\ncat <<'NARRATIO_REPORT'\n" + string(report) + "\nNARRATIO_REPORT\n"
|
||||
if err := os.WriteFile(env.Config.Pipeline.Notarius.Binary, []byte(script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env.Notarius = notarius.NewSubprocessRunner()
|
||||
result, err := (extractStage{}).Run(context.Background(), env, m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(result.Outputs) != 1 || ExtractionFallbackCount(result.Metadata) != 1 {
|
||||
t.Fatalf("result = %#v", result)
|
||||
}
|
||||
nativeRecordResult(m, result)
|
||||
validation, err := (extractStage{}).ValidateResume(context.Background(), env, m)
|
||||
if err != nil || !validation.Resumable {
|
||||
t.Fatalf("resume = %#v, %v", validation, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetainedBundleCleanupRejectsUnsafeMarker(t *testing.T) {
|
||||
env, m, _ := nativeExtractFixture(t)
|
||||
result, err := (extractStage{}).Run(context.Background(), env, m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
marker := result.Metadata["retention_path"].(string)
|
||||
if err := os.Remove(marker); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outside := filepath.Join(t.TempDir(), "outside")
|
||||
if err := os.WriteFile(outside, []byte(`{"role":"session_durable"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, marker); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runRoot := artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, m.RunID)
|
||||
if _, err := cleanRunWithRetainedBundle(env.Config.Pipeline.Workspace.Root, runRoot, true); err == nil {
|
||||
t.Fatal("unsafe retention marker accepted")
|
||||
}
|
||||
if _, err := os.Stat(result.Metadata["bundle_root"].(string)); err != nil {
|
||||
t.Fatalf("bundle removed after unsafe marker: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package stage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
@@ -44,13 +45,7 @@ func (extractStage) ValidateResume(_ context.Context, env *Env, m *manifest.Mani
|
||||
if record == nil || metadataString(record.Metadata, "configuration_fingerprint") != fingerprint {
|
||||
return NonResumable("Notarius invocation contract changed"), nil
|
||||
}
|
||||
definitions := make(map[string]artifacts.ExtractionArtifactDefinition, len(cfg.Outputs))
|
||||
for key, output := range cfg.Outputs {
|
||||
definitions[key] = artifacts.ExtractionArtifactDefinition{
|
||||
LaneID: output.LaneID, PipelineID: cfg.PipelineID, MediaType: output.MediaType,
|
||||
SchemaID: output.SchemaID, SchemaVersion: output.SchemaVersion, ModuleKey: output.ModuleKey,
|
||||
}
|
||||
}
|
||||
definitions := artifacts.ExtractionDefinitionsFromConfig(cfg)
|
||||
proof := artifacts.InspectExtractionEvidence(paths, m, definitions, input)
|
||||
if proof.State == artifacts.ExtractionEvidenceUnsafe {
|
||||
return ResumeValidation{}, fmt.Errorf("extract resume: %s", proof.Reason)
|
||||
@@ -58,9 +53,31 @@ func (extractStage) ValidateResume(_ context.Context, env *Env, m *manifest.Mani
|
||||
if proof.State != artifacts.ExtractionEvidenceValid {
|
||||
return NonResumable(proof.Reason), nil
|
||||
}
|
||||
if count := ExtractionFallbackCount(record.Metadata); count > 0 {
|
||||
env.Warn(fmt.Sprintf("Reusing extraction with %d Notarius fallback operations", count))
|
||||
}
|
||||
return Resumable(), nil
|
||||
}
|
||||
|
||||
// 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 ""
|
||||
|
||||
@@ -22,6 +22,8 @@ import (
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||
)
|
||||
|
||||
const extractIndexOutputKind = "notarius_index"
|
||||
|
||||
func TestExtractStageDisabledReturnsExplicitSkip(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
|
||||
106
internal/stage/notarius_lanes.go
Normal file
106
internal/stage/notarius_lanes.go
Normal file
@@ -0,0 +1,106 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
|
||||
)
|
||||
|
||||
var notariusUnsafeLaneCharacters = regexp.MustCompile(`[^a-zA-Z0-9._-]`)
|
||||
|
||||
// notariusLanePath follows the documented Notarius lane filename mapping.
|
||||
func notariusLanePath(laneID string) (string, error) {
|
||||
name := notariusUnsafeLaneCharacters.ReplaceAllString(strings.TrimSpace(laneID), "_")
|
||||
for strings.Contains(name, "..") {
|
||||
name = strings.ReplaceAll(name, "..", "__")
|
||||
}
|
||||
name = strings.Trim(name, "._")
|
||||
if name == "" {
|
||||
return "", fmt.Errorf("notarius lane ID %q cannot produce a filename", laneID)
|
||||
}
|
||||
return "lanes/" + name + ".json", nil
|
||||
}
|
||||
|
||||
type stagedNotariusLane struct {
|
||||
Key, LaneID, Filename, StagedPath, Checksum string
|
||||
Size int64
|
||||
}
|
||||
|
||||
func validateExtractBundleRoot(root, bundle string) error {
|
||||
relative, err := pathsafe.SlashRelativeFromRoot(root, bundle)
|
||||
if err != nil || !filepath.IsAbs(bundle) {
|
||||
return fmt.Errorf("extract: Notarius bundle must be beneath its output root")
|
||||
}
|
||||
current := filepath.Clean(root)
|
||||
for _, component := range append([]string{""}, strings.Split(relative, "/")...) {
|
||||
if component != "" {
|
||||
current = filepath.Join(current, component)
|
||||
}
|
||||
info, err := os.Lstat(current)
|
||||
if err != nil || info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
|
||||
return fmt.Errorf("extract: unsafe Notarius bundle directory %q", current)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// stageRequiredNotariusLanes validates every required payload before any
|
||||
// canonical product is replaced. The retained bundle is never used as an index.
|
||||
func stageRequiredNotariusLanes(bundle, staging string, required map[string]config.NotariusOutputConfig) ([]stagedNotariusLane, error) {
|
||||
keys := make([]string, 0, len(required))
|
||||
for key := range required {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
result := make([]stagedNotariusLane, 0, len(keys))
|
||||
laneOwners, filenameOwners := map[string]string{}, map[string]string{}
|
||||
for _, key := range keys {
|
||||
output := required[key]
|
||||
relative, err := notariusLanePath(output.LaneID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if previous, ok := laneOwners[relative]; ok {
|
||||
return nil, fmt.Errorf("extract: lanes %q and %q map to the same file", previous, output.LaneID)
|
||||
}
|
||||
laneOwners[relative] = output.LaneID
|
||||
filename := config.ExtractionFilename(key, output)
|
||||
if filename == "" || filename == "." || filename == ".." || filepath.Base(filename) != filename || strings.ContainsAny(filename, `/\\`) {
|
||||
return nil, fmt.Errorf("extract: invalid output filename %q", filename)
|
||||
}
|
||||
if previous, ok := filenameOwners[filename]; ok {
|
||||
return nil, fmt.Errorf("extract: outputs %q and %q have the same destination", previous, key)
|
||||
}
|
||||
filenameOwners[filename] = key
|
||||
source, err := pathsafe.JoinSlashRelativeUnderRoot(bundle, relative)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract: resolve lane %q: %w", output.LaneID, err)
|
||||
}
|
||||
info, err := os.Lstat(source)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return nil, fmt.Errorf("extract: required lane %q is missing or unsafe", output.LaneID)
|
||||
}
|
||||
data, err := fileops.ReadFileBounded(source, artifacts.MaxExtractionPayloadBytes)
|
||||
if err != nil || !json.Valid(data) {
|
||||
return nil, fmt.Errorf("extract: required lane %q is not bounded valid JSON", output.LaneID)
|
||||
}
|
||||
digest := sha256.Sum256(data)
|
||||
staged := filepath.Join(staging, fmt.Sprintf("%d.json", len(result)))
|
||||
if err := fileops.WriteFileAtomic(staged, data, fileops.WorkspaceFileMode); err != nil {
|
||||
return nil, fmt.Errorf("extract: stage lane %q: %w", output.LaneID, err)
|
||||
}
|
||||
result = append(result, stagedNotariusLane{Key: key, LaneID: output.LaneID, Filename: filename, StagedPath: staged, Checksum: hex.EncodeToString(digest[:]), Size: int64(len(data))})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
16
internal/stage/notarius_lanes_test.go
Normal file
16
internal/stage/notarius_lanes_test.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package stage
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNotariusLanePath(t *testing.T) {
|
||||
for _, test := range []struct{ id, want string }{
|
||||
{"npc-registry", "lanes/npc-registry.json"},
|
||||
{" a/b..c ", "lanes/a_b__c.json"},
|
||||
{"._...", ""},
|
||||
} {
|
||||
got, err := notariusLanePath(test.id)
|
||||
if got != test.want || (err != nil) != (test.want == "") {
|
||||
t.Errorf("notariusLanePath(%q) = %q, %v", test.id, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,13 +40,10 @@ type extractSemanticReference struct {
|
||||
}
|
||||
|
||||
type extractSemanticOutput struct {
|
||||
Key string `json:"key"`
|
||||
SourceID string `json:"source_id"`
|
||||
LaneID string `json:"lane_id"`
|
||||
MediaType string `json:"media_type"`
|
||||
SchemaID string `json:"schema_id"`
|
||||
SchemaVersion string `json:"schema_version"`
|
||||
ModuleKey string `json:"module_key,omitempty"`
|
||||
Key string `json:"key"`
|
||||
SourceID string `json:"source_id"`
|
||||
LaneID string `json:"lane_id"`
|
||||
Filename string `json:"filename"`
|
||||
}
|
||||
|
||||
type publishSemanticConfig struct {
|
||||
@@ -111,9 +108,7 @@ func (extractStage) SemanticConfigFingerprint(env *Env) (manifest.SemanticConfig
|
||||
output := cfg.Outputs[key]
|
||||
payload.Outputs = append(payload.Outputs, extractSemanticOutput{
|
||||
Key: strings.TrimSpace(key), SourceID: artifacts.ExtractionArtifactSourceID(strings.TrimSpace(key)),
|
||||
LaneID: strings.TrimSpace(output.LaneID), MediaType: strings.TrimSpace(output.MediaType),
|
||||
SchemaID: strings.TrimSpace(output.SchemaID), SchemaVersion: strings.TrimSpace(output.SchemaVersion),
|
||||
ModuleKey: strings.TrimSpace(output.ModuleKey),
|
||||
LaneID: strings.TrimSpace(output.LaneID), Filename: config.ExtractionFilename(key, output),
|
||||
})
|
||||
}
|
||||
return FingerprintSemanticConfig(extractSemanticConfigVersion, payload)
|
||||
|
||||
Reference in New Issue
Block a user