Coordinate workspace cleanup with active operations
This commit is contained in:
@@ -52,7 +52,7 @@ Planner behavior:
|
|||||||
directories, symlinks, and other non-regular targets remain conflicts.
|
directories, symlinks, and other non-regular targets remain conflicts.
|
||||||
|
|
||||||
For a non-dry-run restore, planning/classification happens only after acquiring
|
For a non-dry-run restore, planning/classification happens only after acquiring
|
||||||
the session lock. Runner manifest/reuse checks acquire that same lock first.
|
the workspace lock. Runner manifest/reuse checks acquire that same lock first.
|
||||||
|
|
||||||
Previous-cache readiness is resolved through `previouscache.Resolve` for restore,
|
Previous-cache readiness is resolved through `previouscache.Resolve` for restore,
|
||||||
prepare, status, and validation. Each requirement selects the unique
|
prepare, status, and validation. Each requirement selects the unique
|
||||||
|
|||||||
@@ -27,14 +27,14 @@ canonical stage sequence through adapter interfaces, while manifests record
|
|||||||
progress and artifact services resolve durable inputs and outputs.
|
progress and artifact services resolve durable inputs and outputs.
|
||||||
|
|
||||||
The pipeline runner follows one explicit invocation lifecycle: inspect bounded
|
The pipeline runner follows one explicit invocation lifecycle: inspect bounded
|
||||||
prerequisites without mutation, prepare the workspace layout, acquire one
|
prerequisites without mutation, acquire the workspace lock, prepare the workspace
|
||||||
session lock, load or create the authoritative session manifest, complete or
|
layout, load or create the authoritative session manifest, complete or
|
||||||
reuse selected preparation, check projected downstream work, compose only the
|
reuse selected preparation, check projected downstream work, compose only the
|
||||||
collaborators needed by selected work, execute each selected stage in order, finalize terminal state, release resources, and return a possibly partial
|
collaborators needed by selected work, execute each selected stage in order, finalize terminal state, release resources, and return a possibly partial
|
||||||
summary with preserved failure causes. Narrow terminal local persistence detaches
|
summary with preserved failure causes. Narrow terminal local persistence detaches
|
||||||
cancellation; active work retains the canceled operation context. Cleanup, when
|
cancellation; active work retains the canceled operation context. Cleanup, when
|
||||||
selected, is the ordinary final stage rather than runner finalization work.
|
selected, is the ordinary final stage rather than runner finalization work.
|
||||||
The lock remains held from manifest initialization through finalization, and a
|
The lock remains held from layout preparation through finalization, and a
|
||||||
failed stage or required manifest save prevents later stages from starting.
|
failed stage or required manifest save prevents later stages from starting.
|
||||||
Standalone preflight shares that lifecycle, runs only preparation, and checks
|
Standalone preflight shares that lifecycle, runs only preparation, and checks
|
||||||
enabled capabilities while holding the same lock.
|
enabled capabilities while holding the same lock.
|
||||||
@@ -44,7 +44,7 @@ enabled capabilities while holding the same lock.
|
|||||||
| Area | Implemented owners | Responsibility |
|
| Area | Implemented owners | Responsibility |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Executable | `cmd/narratio` | Process entry, standard stream wiring, argument handoff, and exit status. |
|
| Executable | `cmd/narratio` | Process entry, standard stream wiring, argument handoff, and exit status. |
|
||||||
| Application orchestration | `internal/app` | Native CommandKit declarations/reporting, lazy configuration selection, secret-file environment loading, production composition, session locking, planning, execution, restore, and user-facing reporting. |
|
| Application orchestration | `internal/app` | Native CommandKit declarations/reporting, lazy configuration selection, secret-file environment loading, production composition, workspace locking, planning, execution, restore, and user-facing reporting. |
|
||||||
| Configuration | [`internal/config`](configuration.md) | Typed ConfigKit results and lifecycle defaults, imports/overlays, canonical party loading, separate catalog/player/publication derivation, session templating, and validation. |
|
| Configuration | [`internal/config`](configuration.md) | Typed ConfigKit results and lifecycle defaults, imports/overlays, canonical party loading, separate catalog/player/publication derivation, session templating, and validation. |
|
||||||
| Pipeline stages | `internal/stage` | Canonical stage registry, shared stage contract, execution dependencies, and implemented stage behavior. |
|
| Pipeline stages | `internal/stage` | Canonical stage registry, shared stage contract, execution dependencies, and implemented stage behavior. |
|
||||||
| Glossaries | `internal/glossary` | Native vocabulary resolution, schema validation, party projection, and deterministic documents. |
|
| Glossaries | `internal/glossary` | Native vocabulary resolution, schema validation, party projection, and deterministic documents. |
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ discovery, and discovery issues produce warnings. Findings survive independent
|
|||||||
failures and cancellation stops new work.
|
failures and cancellation stops new work.
|
||||||
|
|
||||||
Probe files use invocation-scoped destinations under `runs/`, protected by the
|
Probe files use invocation-scoped destinations under `runs/`, protected by the
|
||||||
session lock through report consumption, reference verification, and terminal
|
workspace lock through report consumption, reference verification, and terminal
|
||||||
persistence. A later authorized cleanup can remove those files without removing
|
persistence. A later authorized cleanup can remove those files without removing
|
||||||
durable prepared inputs. See [workspace internals](workspace.md),
|
durable prepared inputs. See [workspace internals](workspace.md),
|
||||||
[CLI](../cli.md#preflight), and [operations](../operations.md#prompt-requirements-preflight).
|
[CLI](../cli.md#preflight), and [operations](../operations.md#prompt-requirements-preflight).
|
||||||
|
|||||||
@@ -46,11 +46,14 @@ session run-history cleanup, and are excluded from publish and restore enumerati
|
|||||||
|
|
||||||
## Locking
|
## Locking
|
||||||
|
|
||||||
`artifacts.LocalStore` enforces the single-writer session lock via an
|
`artifacts.LocalStore` enforces single-writer workspace access via an
|
||||||
operating-system lock held on `.lock` (`ErrLockConflict` on contention). The
|
operating-system lock held on `<workspace.root>/.lock` (`ErrLockConflict` on contention). The
|
||||||
file retains owner metadata after release or process death; its existence is
|
file retains owner metadata after release or process death; its existence is
|
||||||
not evidence that a lock is active. Command and restore flows wait for this
|
not evidence that a lock is active. Runs, preflight, mutating restore, and
|
||||||
lock only while their context remains active, and report a release failure.
|
manual cleanup acquire it before creating or changing managed session state.
|
||||||
|
Initialization targeting managed work also acquires it. They wait only while
|
||||||
|
their context remains active and report a release failure. Read-only inspection
|
||||||
|
and dry runs do not acquire it; separate workspaces remain independent.
|
||||||
Standalone preflight holds the same lock through preparation, readiness probes,
|
Standalone preflight holds the same lock through preparation, readiness probes,
|
||||||
and finalization, keeping active probe files outside concurrent cleanup.
|
and finalization, keeping active probe files outside concurrent cleanup.
|
||||||
Preparation uses ordinary manifest transitions and invalidation.
|
Preparation uses ordinary manifest transitions and invalidation.
|
||||||
|
|||||||
@@ -137,7 +137,7 @@ not rerun; otherwise it uses a synthetic input. These checks do not establish
|
|||||||
real-transcript feasibility, editorial quality, or future provider availability.
|
real-transcript feasibility, editorial quality, or future provider availability.
|
||||||
See [Audita](integrations/audita.md) and [Scriptorium](integrations/scriptorium.md).
|
See [Audita](integrations/audita.md) and [Scriptorium](integrations/scriptorium.md).
|
||||||
|
|
||||||
The session lock covers preparation, probes, and finalization. Probe diagnostics
|
The workspace lock covers preparation, probes, and finalization. Probe diagnostics
|
||||||
under `runs/` are disposable and can be removed by a later authorized cleanup;
|
under `runs/` are disposable and can be removed by a later authorized cleanup;
|
||||||
prepared inputs remain durable. Preflight itself does not run cleanup or rotate
|
prepared inputs remain durable. Preflight itself does not run cleanup or rotate
|
||||||
processing-stage diagnostic views. See [cleanup](#cleanup).
|
processing-stage diagnostic views. See [cleanup](#cleanup).
|
||||||
@@ -737,6 +737,9 @@ the session workload.
|
|||||||
Use `narratio session clean SESSION` to remove an entire local session, or
|
Use `narratio session clean SESSION` to remove an entire local session, or
|
||||||
`narratio session clean --all` for all local sessions. Add `--dry-run` to inspect
|
`narratio session clean --all` for all local sessions. Add `--dry-run` to inspect
|
||||||
planned targets. These commands do not delete subprocess caches or remote data.
|
planned targets. These commands do not delete subprocess caches or remote data.
|
||||||
|
Mutating cleanup waits for the same workspace lock used by runs, preflight, and
|
||||||
|
restore. Waiting can be cancelled; dry-run inspection does not take the lock.
|
||||||
|
The lock file remains at `<workspace.root>/.lock` after cleanup.
|
||||||
|
|
||||||
Automatic cleanup requires `workspace.cleanup_after_publish=true` and successful
|
Automatic cleanup requires `workspace.cleanup_after_publish=true` and successful
|
||||||
publication evidence. When selected, it removes the entire session `runs/` tree,
|
publication evidence. When selected, it removes the entire session `runs/` tree,
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ itself an architectural goal.
|
|||||||
## Ownership And Dependency Direction
|
## Ownership And Dependency Direction
|
||||||
|
|
||||||
The application boundary owns command composition, configuration selection,
|
The application boundary owns command composition, configuration selection,
|
||||||
production composition, session locking, and top-level lifecycle. It may depend
|
production composition, workspace locking, and top-level lifecycle. It may depend
|
||||||
on concrete implementations to assemble a run.
|
on concrete implementations to assemble a run.
|
||||||
|
|
||||||
Stage orchestration expresses intent in Narratio-level data and interfaces.
|
Stage orchestration expresses intent in Narratio-level data and interfaces.
|
||||||
@@ -131,7 +131,7 @@ not configurable.
|
|||||||
Downstream readiness is an invocation check after selected preparation and
|
Downstream readiness is an invocation check after selected preparation and
|
||||||
before the selected processing work. It does not create a stage success.
|
before the selected processing work. It does not create a stage success.
|
||||||
Standalone preflight prepares or reuses session inputs and checks enabled
|
Standalone preflight prepares or reuses session inputs and checks enabled
|
||||||
capabilities under the same session lock; its checks may probe destinations and
|
capabilities under the same workspace lock; its checks may probe destinations and
|
||||||
contact configured providers.
|
contact configured providers.
|
||||||
|
|
||||||
A stage may explicitly self-skip with a stable reason and no outputs. That
|
A stage may explicitly self-skip with a stable reason and no outputs. That
|
||||||
|
|||||||
@@ -131,6 +131,10 @@ Release/process exit permits later acquisition, and deleting a session or the
|
|||||||
|
|
||||||
## Stage 3: Coordinate runners, restore, preflight, and manual cleanup
|
## Stage 3: Coordinate runners, restore, preflight, and manual cleanup
|
||||||
|
|
||||||
|
**Complete:** Mutating commands acquire the workspace lock before managed work;
|
||||||
|
controlled command-level tests cover cleanup, cancellation, new admission, and
|
||||||
|
managed initialization. Application, artifact, and documentation checks pass.
|
||||||
|
|
||||||
Read:
|
Read:
|
||||||
|
|
||||||
- `audit/08-testing.md`, lines 170–201 (TE-04).
|
- `audit/08-testing.md`, lines 170–201 (TE-04).
|
||||||
|
|||||||
@@ -795,21 +795,21 @@ narratio run 2026-04-04 --stage prepare --force
|
|||||||
|
|
||||||
Relevant reference: [Operations: Restore Workflow](./operations.md#restore-workflow).
|
Relevant reference: [Operations: Restore Workflow](./operations.md#restore-workflow).
|
||||||
|
|
||||||
## Session lock conflict (`.lock`)
|
## Workspace lock wait (`.lock`)
|
||||||
|
|
||||||
Symptom:
|
Symptom:
|
||||||
|
|
||||||
- command fails acquiring session lock.
|
- a mutating command waits for the workspace lock or is cancelled while waiting.
|
||||||
|
|
||||||
Likely causes:
|
Likely causes:
|
||||||
|
|
||||||
- another process is running for the same session;
|
- another process is mutating the same workspace;
|
||||||
- a process still holds the operating-system lock while it is shutting down.
|
- a process still holds the operating-system lock while it is shutting down.
|
||||||
|
|
||||||
Diagnostics:
|
Diagnostics:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
ls -l {workspace.root}/work/{campaign}/{session_id}/.lock
|
ls -l {workspace.root}/.lock
|
||||||
ps aux | grep narratio
|
ps aux | grep narratio
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -85,6 +85,14 @@ func cleanSelectedSession(ctx context.Context, input *cleanCommandInput, deps co
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
|
if !input.DryRun {
|
||||||
|
store := deps.newWorkspaceStore(pipeline.Workspace.Root)
|
||||||
|
lock, lockErr := store.AcquireWorkspaceLockContext(ctx)
|
||||||
|
if lockErr != nil {
|
||||||
|
return report, fmt.Errorf("clean: acquire workspace lock: %w", lockErr)
|
||||||
|
}
|
||||||
|
defer func() { err = errors.Join(err, store.ReleaseWorkspaceLock(lock)) }()
|
||||||
|
}
|
||||||
appendTarget := func(root, target, policy string, directory bool) error {
|
appendTarget := func(root, target, policy string, directory bool) error {
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
235
internal/app/clean_lock_test.go
Normal file
235
internal/app/clean_lock_test.go
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||||
|
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||||
|
"gitea.maximumdirect.net/eric/narratio/internal/stage"
|
||||||
|
"go.maximumdirect.net/commandkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
type observedWorkspaceStore struct {
|
||||||
|
artifacts.Store
|
||||||
|
entering chan struct{}
|
||||||
|
acquired chan struct{}
|
||||||
|
proceed <-chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *observedWorkspaceStore) AcquireWorkspaceLockContext(ctx context.Context) (*artifacts.LockHandle, error) {
|
||||||
|
if s.entering != nil {
|
||||||
|
lock, err := s.Store.AcquireWorkspaceLock()
|
||||||
|
if !errors.Is(err, artifacts.ErrLockConflict) {
|
||||||
|
return lock, err
|
||||||
|
}
|
||||||
|
close(s.entering)
|
||||||
|
}
|
||||||
|
lock, err := s.Store.AcquireWorkspaceLockContext(ctx)
|
||||||
|
if err == nil && s.acquired != nil {
|
||||||
|
close(s.acquired)
|
||||||
|
<-s.proceed
|
||||||
|
}
|
||||||
|
return lock, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type waitingPrepare struct {
|
||||||
|
entered chan struct{}
|
||||||
|
release <-chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s waitingPrepare) Name() string { return "prepare" }
|
||||||
|
func (s waitingPrepare) Run(ctx context.Context, _ *stage.Env, _ *manifest.Manifest) (*stage.StageResult, error) {
|
||||||
|
close(s.entered)
|
||||||
|
select {
|
||||||
|
case <-s.release:
|
||||||
|
return &stage.StageResult{}, nil
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManualCleanWaitsForActiveInvocation(t *testing.T) {
|
||||||
|
for _, all := range []bool{false, true} {
|
||||||
|
t.Run(map[bool]string{false: "session", true: "all"}[all], func(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
pipeline, campaign, session := writeValidConfigFiles(t, root)
|
||||||
|
cfg, err := config.Load(pipeline, campaign, session)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
entered, release := make(chan struct{}), make(chan struct{})
|
||||||
|
running := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
_, err := executePlan(context.Background(), cfg, BoundedPlan{stages: []stage.Stage{waitingPrepare{entered, release}}}, RunOptions{})
|
||||||
|
running <- err
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-entered:
|
||||||
|
case err := <-running:
|
||||||
|
t.Fatalf("runner stopped: %v", err)
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("runner did not enter")
|
||||||
|
}
|
||||||
|
work := artifacts.SessionWorkDirForCampaign(root, cfg.Session.Campaign, cfg.Session.SessionID)
|
||||||
|
attempted := make(chan struct{})
|
||||||
|
deps := commandDependencies{newWorkspaceStore: func(root string) artifacts.Store {
|
||||||
|
return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attempted}
|
||||||
|
}}
|
||||||
|
app, err := newApplication(deps, executePlan)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
args := []string{"session", "clean", cfg.Session.SessionID, "--config", pipeline, "--campaign-file", campaign, "--session-file", session}
|
||||||
|
if all {
|
||||||
|
args = []string{"session", "clean", "--all", "--config", pipeline}
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
result := make(chan commandkit.Outcome, 1)
|
||||||
|
go func() {
|
||||||
|
result <- app.Execute(ctx, args, commandkit.Streams{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}})
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-attempted:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("cleanup did not attempt lock")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(work); err != nil {
|
||||||
|
t.Fatalf("active work removed: %v", err)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case out := <-result:
|
||||||
|
if out.Status == 0 {
|
||||||
|
t.Fatal("cancelled clean succeeded")
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("cleanup did not cancel")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(work); err != nil {
|
||||||
|
t.Fatalf("cancelled clean removed work: %v", err)
|
||||||
|
}
|
||||||
|
attemptedAgain := make(chan struct{})
|
||||||
|
retryApp, err := newApplication(commandDependencies{newWorkspaceStore: func(root string) artifacts.Store {
|
||||||
|
return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attemptedAgain}
|
||||||
|
}}, executePlan)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
retry := make(chan commandkit.Outcome, 1)
|
||||||
|
go func() {
|
||||||
|
retry <- retryApp.Execute(context.Background(), args, commandkit.Streams{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}})
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-attemptedAgain:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("cleanup retry did not wait for lock")
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
if err := <-running; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if outcome := <-retry; outcome.Status != 0 {
|
||||||
|
t.Fatalf("cleanup failed: status %d", outcome.Status)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(work); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("work remains: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCleanAllBlocksNewSessionAdmission(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
pipeline, campaign, session := writeValidConfigFiles(t, root)
|
||||||
|
cfg, err := config.Load(pipeline, campaign, session)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg.Session.SessionID = "new-session"
|
||||||
|
acquired, release := make(chan struct{}), make(chan struct{})
|
||||||
|
deps := commandDependencies{newWorkspaceStore: func(root string) artifacts.Store {
|
||||||
|
return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), acquired: acquired, proceed: release}
|
||||||
|
}}
|
||||||
|
app, err := newApplication(deps, executePlan)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
done := make(chan commandkit.Outcome, 1)
|
||||||
|
go func() {
|
||||||
|
done <- app.Execute(context.Background(), []string{"session", "clean", "--all", "--config", pipeline}, commandkit.Streams{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}})
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-acquired:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("cleanup did not acquire lock")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
attempted := make(chan struct{})
|
||||||
|
result := make(chan error, 1)
|
||||||
|
store := &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attempted}
|
||||||
|
go func() {
|
||||||
|
_, err := executeStages(ctx, cfg, nil, RunOptions{Env: &Env{ArtifactStore: store}})
|
||||||
|
result <- err
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-attempted:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("new invocation did not attempt lock")
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
err = <-result
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("new invocation: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(root, "work")); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("new session created work: %v", err)
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
if out := <-done; out.Status != 0 {
|
||||||
|
t.Fatalf("clean status = %d", out.Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionInitWaitsWhenOutputIsManaged(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
pipeline, campaign, _ := writeValidConfigFiles(t, root)
|
||||||
|
store := artifacts.NewLocalStore(root)
|
||||||
|
lock, err := store.AcquireWorkspaceLock()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer store.ReleaseWorkspaceLock(lock)
|
||||||
|
attempted := make(chan struct{})
|
||||||
|
deps := commandDependencies{newWorkspaceStore: func(root string) artifacts.Store {
|
||||||
|
return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attempted}
|
||||||
|
}}
|
||||||
|
app, err := newApplication(deps, executePlan)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
output := filepath.Join(root, "work", "sample-campaign", "new", "session.yml")
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan commandkit.Outcome, 1)
|
||||||
|
go func() {
|
||||||
|
done <- app.Execute(ctx, []string{"session", "init", "2026-06-07", "--config", pipeline, "--campaign-file", campaign, "--output", output}, commandkit.Streams{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}})
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-attempted:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("initialization did not attempt lock")
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
if out := <-done; out.Status == 0 {
|
||||||
|
t.Fatal("cancelled initialization succeeded")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(output); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("output created: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
|
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
|
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
||||||
|
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/logging"
|
"gitea.maximumdirect.net/eric/narratio/internal/logging"
|
||||||
configkit "go.maximumdirect.net/configkit"
|
configkit "go.maximumdirect.net/configkit"
|
||||||
@@ -18,6 +19,7 @@ type commandDependencies struct {
|
|||||||
preparePipelineSource func(configkit.Source) (*configkit.SecretsReport, configkit.Source, error)
|
preparePipelineSource func(configkit.Source) (*configkit.SecretsReport, configkit.Source, error)
|
||||||
loadPipelineSource func(configkit.Source, config.PipelineLoadOptions) (*config.PipelineConfig, error)
|
loadPipelineSource func(configkit.Source, config.PipelineLoadOptions) (*config.PipelineConfig, error)
|
||||||
newObjectStore func(context.Context, *config.Config) (storage.ObjectStore, error)
|
newObjectStore func(context.Context, *config.Config) (storage.ObjectStore, error)
|
||||||
|
newWorkspaceStore func(string) artifacts.Store
|
||||||
newScriptorium func() scriptorium.Runner
|
newScriptorium func() scriptorium.Runner
|
||||||
newAudita func(*config.Config) (audita.Runner, error)
|
newAudita func(*config.Config) (audita.Runner, error)
|
||||||
newNotarius func() notarius.Runner
|
newNotarius func() notarius.Runner
|
||||||
@@ -38,6 +40,9 @@ func normalizeCommandDependencies(deps commandDependencies) commandDependencies
|
|||||||
if deps.newObjectStore == nil {
|
if deps.newObjectStore == nil {
|
||||||
deps.newObjectStore = storage.NewObjectStoreFromConfig
|
deps.newObjectStore = storage.NewObjectStoreFromConfig
|
||||||
}
|
}
|
||||||
|
if deps.newWorkspaceStore == nil {
|
||||||
|
deps.newWorkspaceStore = func(root string) artifacts.Store { return artifacts.NewLocalStore(root) }
|
||||||
|
}
|
||||||
if deps.newAudita == nil {
|
if deps.newAudita == nil {
|
||||||
deps.newAudita = buildDefaultAuditaRunner
|
deps.newAudita = buildDefaultAuditaRunner
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -96,22 +96,22 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl
|
|||||||
}
|
}
|
||||||
|
|
||||||
artifactStore := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root)
|
artifactStore := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root)
|
||||||
if _, err := artifactStore.EnsureLayoutFor(cfg.Session.Campaign, cfg.Session.SessionID); err != nil {
|
|
||||||
return diagnostic, fmt.Errorf("restore: prepare workdir: %w", err)
|
|
||||||
}
|
|
||||||
lock, err := artifactStore.AcquireWorkspaceLockContext(ctx)
|
lock, err := artifactStore.AcquireWorkspaceLockContext(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return diagnostic, fmt.Errorf("restore: acquire session lock: %w", err)
|
return diagnostic, fmt.Errorf("restore: acquire workspace lock: %w", err)
|
||||||
}
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
if releaseErr := artifactStore.ReleaseWorkspaceLock(lock); releaseErr != nil {
|
if releaseErr := artifactStore.ReleaseWorkspaceLock(lock); releaseErr != nil {
|
||||||
if resultErr == nil {
|
if resultErr == nil {
|
||||||
resultErr = fmt.Errorf("restore: release session lock: %w", releaseErr)
|
resultErr = fmt.Errorf("restore: release workspace lock: %w", releaseErr)
|
||||||
} else {
|
} else {
|
||||||
resultErr = errors.Join(resultErr, fmt.Errorf("restore: release session lock: %w", releaseErr))
|
resultErr = errors.Join(resultErr, fmt.Errorf("restore: release workspace lock: %w", releaseErr))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
if _, err := artifactStore.EnsureLayoutFor(cfg.Session.Campaign, cfg.Session.SessionID); err != nil {
|
||||||
|
return diagnostic, fmt.Errorf("restore: prepare workdir: %w", err)
|
||||||
|
}
|
||||||
if _, _, err := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, manifestPath); err != nil {
|
if _, _, err := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, manifestPath); err != nil {
|
||||||
return diagnostic, fmt.Errorf("restore: %w", err)
|
return diagnostic, fmt.Errorf("restore: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,8 +48,8 @@ func TestRestoreHoldsTransitionLockBeforePlanning(t *testing.T) {
|
|||||||
|
|
||||||
runnerCtx, cancelRunner := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
runnerCtx, cancelRunner := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||||
defer cancelRunner()
|
defer cancelRunner()
|
||||||
if _, err := executeStages(runnerCtx, cfg, nil, RunOptions{}); err == nil || !strings.Contains(err.Error(), "acquire session lock") {
|
if _, err := executeStages(runnerCtx, cfg, nil, RunOptions{}); err == nil || !strings.Contains(err.Error(), "acquire workspace lock") {
|
||||||
t.Fatalf("runner while restore plans error = %v, want session-lock failure", err)
|
t.Fatalf("runner while restore plans error = %v, want workspace-lock failure", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
close(releasePlanning)
|
close(releasePlanning)
|
||||||
|
|||||||
@@ -64,23 +64,22 @@ func withLockedInvocation(ctx context.Context, cfg *config.Config, plan BoundedP
|
|||||||
if _, _, err := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, runtime.manifestPath); err != nil {
|
if _, _, err := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, runtime.manifestPath); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if err := prepareInvocationLayout(runtime); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
lock, err := runtime.artifactStore.AcquireWorkspaceLockContext(ctx)
|
lock, err := runtime.artifactStore.AcquireWorkspaceLockContext(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("acquire session lock: %w", err)
|
return nil, fmt.Errorf("acquire workspace lock: %w", err)
|
||||||
}
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
if releaseErr := runtime.artifactStore.ReleaseWorkspaceLock(lock); releaseErr != nil {
|
if releaseErr := runtime.artifactStore.ReleaseWorkspaceLock(lock); releaseErr != nil {
|
||||||
if resultErr == nil {
|
if resultErr == nil {
|
||||||
resultErr = fmt.Errorf("release session lock: %w", releaseErr)
|
resultErr = fmt.Errorf("release workspace lock: %w", releaseErr)
|
||||||
} else {
|
} else {
|
||||||
resultErr = errors.Join(resultErr, fmt.Errorf("release session lock: %w", releaseErr))
|
resultErr = errors.Join(resultErr, fmt.Errorf("release workspace lock: %w", releaseErr))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
if err := prepareInvocationLayout(runtime); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
if runtime.started {
|
if runtime.started {
|
||||||
result, resultErr = finalizeInvocation(runtime, resultErr)
|
result, resultErr = finalizeInvocation(runtime, resultErr)
|
||||||
|
|||||||
@@ -172,6 +172,18 @@ func initializeSession(ctx context.Context, request *sessionInitializationInput,
|
|||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
if !remote {
|
if !remote {
|
||||||
|
managed, err := pathInsideManagedWork(base.Pipeline.Workspace.Root, output)
|
||||||
|
if err != nil {
|
||||||
|
return report, fmt.Errorf("session init: resolve output: %w", err)
|
||||||
|
}
|
||||||
|
if managed {
|
||||||
|
store := deps.newWorkspaceStore(base.Pipeline.Workspace.Root)
|
||||||
|
lock, lockErr := store.AcquireWorkspaceLockContext(ctx)
|
||||||
|
if lockErr != nil {
|
||||||
|
return report, fmt.Errorf("session init: acquire workspace lock: %w", lockErr)
|
||||||
|
}
|
||||||
|
defer func() { err = errors.Join(err, store.ReleaseWorkspaceLock(lock)) }()
|
||||||
|
}
|
||||||
if err := writeLocalFile(output, data, force); err != nil {
|
if err := writeLocalFile(output, data, force); err != nil {
|
||||||
return report, fmt.Errorf("session init: %w", err)
|
return report, fmt.Errorf("session init: %w", err)
|
||||||
}
|
}
|
||||||
@@ -210,3 +222,60 @@ func initializeSession(ctx context.Context, request *sessionInitializationInput,
|
|||||||
report = &sessionInitializationReport{Campaign: config.CampaignID(base.Campaign), SessionID: sessionID, Destination: "s3://" + s3BucketName(base.Pipeline) + "/" + key, Remote: true, Written: true}
|
report = &sessionInitializationReport{Campaign: config.CampaignID(base.Campaign), SessionID: sessionID, Destination: "s3://" + s3BucketName(base.Pipeline) + "/" + key, Remote: true, Written: true}
|
||||||
return report, nil
|
return report, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// pathInsideManagedWork resolves existing ancestors so aliases to the work tree
|
||||||
|
// participate in the same coordination as paths written directly beneath it.
|
||||||
|
func pathInsideManagedWork(workspace, output string) (bool, error) {
|
||||||
|
within := func(work, target string) (bool, error) {
|
||||||
|
relative, err := filepath.Rel(work, target)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return relative == "." || (relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))), nil
|
||||||
|
}
|
||||||
|
workPath, err := filepath.Abs(filepath.Join(workspace, config.PathWorkDirSegment))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
outputPath, err := filepath.Abs(output)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if inside, err := within(workPath, outputPath); inside || err != nil {
|
||||||
|
return inside, err
|
||||||
|
}
|
||||||
|
resolve := func(path string) (string, error) {
|
||||||
|
absolute, err := filepath.Abs(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
candidate := absolute
|
||||||
|
for {
|
||||||
|
resolved, err := filepath.EvalSymlinks(candidate)
|
||||||
|
if err == nil {
|
||||||
|
rest, relErr := filepath.Rel(candidate, absolute)
|
||||||
|
if relErr != nil {
|
||||||
|
return "", relErr
|
||||||
|
}
|
||||||
|
return filepath.Join(resolved, rest), nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
parent := filepath.Dir(candidate)
|
||||||
|
if parent == candidate {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
candidate = parent
|
||||||
|
}
|
||||||
|
}
|
||||||
|
work, err := resolve(filepath.Join(workspace, config.PathWorkDirSegment))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
target, err := resolve(output)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return within(work, target)
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user