Merge imported products into local session state

This commit is contained in:
2026-12-02 16:24:33 +00:00
parent ad8a5df97b
commit e7fada4372
26 changed files with 638 additions and 1254 deletions

View File

@@ -57,7 +57,6 @@ type RestoreAction struct {
Conflict bool
ConflictKind RestoreConflictKind
Reason string
VerifiedContent []byte
}
// A committed identity declares its size even when it is zero. Legacy raw
@@ -78,6 +77,7 @@ type RestorePlan struct {
Satisfied []string
Remaining []string
candidate *manifest.Manifest
baseline *manifest.Manifest
}
// RestorePlanOptions control restore planning scope and classification.
@@ -89,15 +89,7 @@ type RestorePlanOptions struct {
var errRestoreProductNotFound = errors.New("restore product source is unavailable")
func buildRestorePlan(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, store storage.ObjectStore, opts RestorePlanOptions) (*RestorePlan, error) {
return buildRestorePlanWithInventory(ctx, cfg, current, store, opts, false)
}
func buildInventoryRestorePlan(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, store storage.ObjectStore, opts RestorePlanOptions) (*RestorePlan, error) {
return buildRestorePlanWithInventory(ctx, cfg, current, store, opts, true)
}
func buildRestorePlanWithInventory(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, store storage.ObjectStore, opts RestorePlanOptions, inventory bool) (*RestorePlan, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
@@ -119,12 +111,7 @@ func buildRestorePlanWithInventory(ctx context.Context, cfg *config.Config, curr
defer func() { _ = sessionRoot.Close() }()
}
var actions []RestoreAction
if inventory {
actions, err = buildInventoryRestoreActions(ctx, cfg, current, store, sessionPaths, sessionRoot, opts)
} else {
actions, err = buildCurrentRestoreActions(ctx, cfg, current, store, sessionPaths, sessionRoot, opts)
}
actions, err := buildInventoryRestoreActions(ctx, cfg, current, store, sessionPaths, sessionRoot, opts)
if err != nil {
return nil, err
}
@@ -150,10 +137,8 @@ func buildRestorePlanWithInventory(ctx context.Context, cfg *config.Config, curr
})
plan := &RestorePlan{Actions: actions}
if inventory {
if err := projectInventoryCoverage(ctx, cfg, plan); err != nil {
return nil, err
}
if err := projectInventoryCoverage(ctx, cfg, plan); err != nil {
return nil, err
}
for _, action := range actions {
switch action.Kind {
@@ -178,14 +163,24 @@ func projectInventoryCoverage(ctx context.Context, cfg *config.Config, plan *Res
if err != nil {
return err
}
if local != nil {
identity := invocationIdentity{Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID}
if err := identity.validateSessionManifest(local); err != nil {
return fmt.Errorf("validate local restore baseline: %w", err)
}
}
plan.candidate, err = cloneManifestForPlan(local, cfg)
if err != nil {
return fmt.Errorf("clone local restore baseline: %w", err)
}
plan.baseline, err = cloneManifestForPlan(local, cfg)
if err != nil {
return fmt.Errorf("clone existing local state: %w", err)
}
covered := make(map[string]bool)
available := make(map[string]bool)
pathsBySource := make(map[string]string)
products := newRestoreProductPaths(nil)
products := newRestoreProductPaths()
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
configured := artifacts.ConfiguredArtifactDefinitions(cfg.ConcreteArtifacts())
extraction := artifacts.ExtractionDefinitionsFromConfig(cfg.Pipeline.Notarius)
@@ -203,10 +198,10 @@ func projectInventoryCoverage(ctx context.Context, cfg *config.Config, plan *Res
catalog.HydrateExtractionArtifacts(paths, local, extraction)
if local != nil && local.SuppliedProducts != nil {
for source, record := range local.SuppliedProducts.Products {
canonical, pathErr := products.relativePath(cfg, nil, paths.Root, source)
pathsBySource[source] = record.Path
canonical, pathErr := products.relativePath(cfg, paths.Root, source)
if pathErr == nil && artifacts.ValidateSuppliedProduct(paths, source, canonical, record) == nil {
available[source] = true
pathsBySource[source] = canonical
}
}
}
@@ -282,33 +277,22 @@ func projectInventoryCoverage(ctx context.Context, cfg *config.Config, plan *Res
return nil
}
func buildCurrentRestoreActions(
ctx context.Context,
cfg *config.Config,
current *RemoteCurrentState,
store storage.ObjectStore,
sessionPaths artifacts.SessionPaths,
sessionRoot *os.Root,
opts RestorePlanOptions,
) ([]RestoreAction, error) {
return buildCommittedRestoreActions(ctx, cfg, current, store, sessionPaths, sessionRoot, opts)
}
// buildInventoryRestoreActions maps product identities through the current
// catalog. Remote destinations identify transfer objects, not local names.
func buildInventoryRestoreActions(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, store storage.ObjectStore, sessionPaths artifacts.SessionPaths, sessionRoot *os.Root, opts RestorePlanOptions) ([]RestoreAction, error) {
if current == nil || current.Commit == nil {
return nil, fmt.Errorf("committed remote inventory is required")
}
products := newRestoreProductPaths(nil)
products := newRestoreProductPaths()
var actions []RestoreAction
for _, artifact := range current.Commit.Artifacts {
var rel string
var include bool
var err error
if artifact.Type == artifacts.RemoteArtifactTypePublishedOutput {
if _, err := artifacts.ParsePublishedOutputObjectKey(current.SessionPrefix, artifact.DestinationKey); err != nil {
return nil, fmt.Errorf("map committed object %q: %w", artifact.DestinationKey, err)
}
if _, classifyErr := artifactpolicy.ClassifySource(artifact.Source); classifyErr == nil {
rel, err = products.relativePath(cfg, nil, sessionPaths.Root, artifact.Source)
rel, err = products.relativePath(cfg, sessionPaths.Root, artifact.Source)
if err == nil {
include = true
} else if !errors.Is(err, errRestoreProductNotFound) {
@@ -349,146 +333,41 @@ func buildInventoryRestoreActions(ctx context.Context, cfg *config.Config, curre
return actions, nil
}
func buildCommittedRestoreActions(
ctx context.Context,
cfg *config.Config,
current *RemoteCurrentState,
store storage.ObjectStore,
sessionPaths artifacts.SessionPaths,
sessionRoot *os.Root,
opts RestorePlanOptions,
) ([]RestoreAction, error) {
if current == nil || current.Commit == nil {
return nil, fmt.Errorf("committed remote current state is required")
}
actions := make([]RestoreAction, 0, len(current.Commit.Artifacts))
products := newRestoreProductPaths(current.Manifest)
for _, artifact := range current.Commit.Artifacts {
rel, include, err := restoreLocalRelativePathForCommittedArtifact(current.SessionPrefix, artifact, opts.IncludeAudio)
if err != nil {
return nil, fmt.Errorf("map committed object %q: %w", artifact.DestinationKey, err)
}
if artifact.Type == artifacts.RemoteArtifactTypePublishedOutput && current.Manifest != nil {
identity, _ := artifacts.ParsePublishedOutputObjectKey(current.SessionPrefix, artifact.DestinationKey)
if _, sourceErr := artifactpolicy.ClassifySource(artifact.Source); sourceErr == nil {
productPath, productErr := products.relativePath(cfg, current.Manifest, sessionPaths.Root, artifact.Source)
if productErr != nil && (!strings.HasPrefix(identity.Destination, config.PathAudioDirSegment+"/") || !errors.Is(productErr, errRestoreProductNotFound)) {
return nil, fmt.Errorf("map committed source %q: %w", artifact.Source, productErr)
}
if productErr == nil {
rel, include = productPath, true
}
}
}
if !include {
continue
}
localPath, err := joinWithinSessionRoot(sessionPaths.Root, rel)
if err != nil {
return nil, fmt.Errorf("map committed object %q: %w", artifact.DestinationKey, err)
}
action, err := classifyRestoreAction(ctx, store, storage.ObjectInfo{
Key: artifact.DestinationKey, Size: artifact.Size, ETag: artifact.Generation,
}, artifact.SHA256, rel, localPath, sessionRoot, opts.Force)
if err != nil {
return nil, fmt.Errorf("classify committed object %q: %w", artifact.DestinationKey, err)
}
if artifact.Type == artifacts.RemoteArtifactTypeSessionManifest && artifact.DestinationKey == current.CurrentManifestKey {
action.VerifiedContent = append([]byte(nil), current.ManifestData...)
}
actions = append(actions, action)
}
return actions, nil
}
// restoreProductPaths resolves sources using the current concrete catalog.
type restoreProductPaths struct{ catalog *artifacts.ArtifactCatalog }
// restoreProductPaths indexes evidence once, retaining duplicates for the
// per-source agreement checks. Unselected paths are not validated here.
type restoreProductPaths struct {
bySource map[string][]string
fallback *artifacts.ArtifactCatalog
}
func newRestoreProductPaths() *restoreProductPaths { return &restoreProductPaths{} }
func newRestoreProductPaths(m *manifest.Manifest) *restoreProductPaths {
index := &restoreProductPaths{bySource: make(map[string][]string)}
if m == nil {
return index
}
for _, record := range m.Stages {
if record == nil {
continue
}
for _, output := range record.Outputs {
index.bySource[output.SourceID] = append(index.bySource[output.SourceID], output.LocalPath)
}
for _, artifact := range record.AnalyzeArtifacts {
if artifact.Output != nil {
output := artifact.Output
index.bySource[output.SourceID] = append(index.bySource[output.SourceID], output.LocalPath)
}
}
}
return index
}
// relativePath takes local product identity from the committed session
// evidence; the remote publication destination is only an object key.
func (index *restoreProductPaths) relativePath(cfg *config.Config, m *manifest.Manifest, destinationRoot, source string) (string, error) {
producerRoot, hasProducerRoot := restoredManifestSessionRoot(m)
var result string
for _, value := range index.bySource[source] {
local, err := rebaseRestoredLocalReference("published output", value, producerRoot, hasProducerRoot, destinationRoot)
if err != nil {
func (index *restoreProductPaths) relativePath(cfg *config.Config, destinationRoot, source string) (string, error) {
if index.catalog == nil {
catalog := artifacts.NewArtifactCatalog()
if err := catalog.RegisterBuiltIns(); err != nil {
return "", err
}
rel, err := filepath.Rel(destinationRoot, local)
if err != nil {
if err := catalog.RegisterConfiguredArtifacts(artifacts.ConfiguredArtifactDefinitions(cfg.ConcreteArtifacts())); err != nil {
return "", err
}
rel = filepath.ToSlash(rel)
parts := strings.Split(rel, "/")
if len(parts) != 2 || (parts[0] != config.PathArtifactsDirSegment && parts[0] != config.PathTranscriptsSegment) || parts[1] == "" || parts[1] == "." || parts[1] == ".." {
return "", fmt.Errorf("product path %q is not a flat canonical product", rel)
if err := catalog.RegisterExtractionArtifacts(artifacts.ExtractionDefinitionsFromConfig(cfg.Pipeline.Notarius)); err != nil {
return "", err
}
if result != "" && result != rel {
return "", fmt.Errorf("conflicting product paths for %q", source)
}
result = rel
index.catalog = catalog
}
if result == "" {
if index.fallback == nil {
catalog := artifacts.NewArtifactCatalog()
if err := catalog.RegisterBuiltIns(); err != nil {
return "", err
}
if err := catalog.RegisterConfiguredArtifacts(artifacts.ConfiguredArtifactDefinitions(cfg.ConcreteArtifacts())); err != nil {
return "", err
}
if err := catalog.RegisterExtractionArtifacts(artifacts.ExtractionDefinitionsFromConfig(cfg.Pipeline.Notarius)); err != nil {
return "", err
}
index.fallback = catalog
}
if entry, ok := index.fallback.Lookup(source); ok {
relative, err := artifacts.ProductRelativePath(destinationRoot, entry.CanonicalRelPath)
if err != nil {
return "", err
}
result = relative
parts := strings.Split(result, "/")
if len(parts) != 2 || (parts[0] != config.PathArtifactsDirSegment && parts[0] != config.PathTranscriptsSegment) || parts[1] == "" || parts[1] == "." || parts[1] == ".." {
return "", fmt.Errorf("configured product path %q is not flat", result)
}
} else {
return "", fmt.Errorf("%w: %q", errRestoreProductNotFound, source)
}
entry, ok := index.catalog.Lookup(source)
if !ok {
return "", fmt.Errorf("%w: %q", errRestoreProductNotFound, source)
}
return result, nil
rel, err := artifacts.ProductRelativePath(destinationRoot, entry.CanonicalRelPath)
if err != nil {
return "", err
}
parts := strings.Split(rel, "/")
if len(parts) != 2 || (parts[0] != config.PathArtifactsDirSegment && parts[0] != config.PathTranscriptsSegment) || parts[1] == "" || parts[1] == "." || parts[1] == ".." {
return "", fmt.Errorf("configured product path %q is not flat", rel)
}
return rel, nil
}
func restoreLocalRelativePathForCommittedArtifact(sessionPrefix string, artifact artifacts.RemoteArtifact, includeAudio bool) (string, bool, error) {
if artifact.Type == artifacts.RemoteArtifactTypeSessionManifest {
return config.PathManifestFile, true, nil
}
if artifact.Type == artifacts.RemoteArtifactTypeRunFile {
prepared := map[string]bool{
"run:prepare/inputs/session.yml": true, "run:prepare/inputs/campaign.yml": true,