Report workspace lock acquisition before waiting

This commit is contained in:
2026-12-02 00:38:15 +00:00
parent 4d7fc57a5e
commit 89c8e5de3c
8 changed files with 108 additions and 11 deletions

View File

@@ -742,6 +742,8 @@ Use `narratio session clean SESSION` to remove an entire local session, or
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 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. restore. Waiting can be cancelled; dry-run inspection does not take the lock.
Mutating commands report the lock path through progress reporting before
acquisition; normal visibility controls apply.
The lock file remains at `<workspace.root>/.lock` after cleanup. 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

View File

@@ -7,13 +7,23 @@ Comparison baseline: `a92a117`.
### R1 — P3: Identify workspace-lock contention while the command waits ### R1 — P3: Identify workspace-lock contention while the command waits
Status: Open Status: Complete
**Resolution.** All four application acquisition paths use a shared helper that
reports the workspace lock path at progress visibility before waiting. Existing
locking, cancellation, and quiet-mode behavior remain unchanged.
`TestCleanReportsWorkspaceLockBeforeWaiting` captures native CLI diagnostics
while a real lock is held, observes contention, then verifies cancellation and
absence of managed-state mutation. The test enables native `--progress` visibility.
Remediation verification passed: `go test ./...`, uncached race-enabled lock and
command regression tests, `go vet ./internal/app`, and documentation/diff checks
with Go 1.27.4.
Plan: [Stage 2](implementation.md#stage-2-introduce-one-stable-workspace-lock), Plan: [Stage 2](implementation.md#stage-2-introduce-one-stable-workspace-lock),
item 3, and the command wiring in Stage 3. The approved behavior includes item 3, and the command wiring in Stage 3. The approved behavior includes
identifying the waited-on lock through existing diagnostics. identifying the waited-on lock through existing diagnostics.
**Evidence.** `AcquireWorkspaceLockContext` in **Original review evidence.** `AcquireWorkspaceLockContext` in
[local.go](../../internal/artifacts/local.go), lines 202–224, retries contention [local.go](../../internal/artifacts/local.go), lines 202–224, retries contention
silently. The workspace path is included only when cancellation returns an error. silently. The workspace path is included only when cancellation returns an error.
The callers in [runner.go](../../internal/app/runner.go), lines 67–69, The callers in [runner.go](../../internal/app/runner.go), lines 67–69,
@@ -46,8 +56,8 @@ signal rather than asserting exact message wording or elapsed time.
| Stage | Review result | | Stage | Review result |
| --- | --- | | --- | --- |
| 1 | SDK upload tests consume and compare payload bytes; recovery instructions bound regeneration before publication. | | 1 | SDK upload tests consume and compare payload bytes; recovery instructions bound regeneration before publication. |
| 2 | Stable workspace lock, cancellation, independent roots, and persistent coordination identity implemented; R1 remains. | | 2 | Stable workspace lock, cancellation, independent roots, and persistent coordination identity implemented; R1 now supplies acquisition diagnostics. |
| 3 | Runner layout, preflight, mutating restore, manual cleanup, and managed initialization use the shared gate; R1 affects their operator diagnostics. | | 3 | Runner layout, preflight, mutating restore, manual cleanup, and managed initialization use the shared gate and report lock acquisition. |
| 4 | Exclusive local creation and provider-conditioned remote creation enforce non-forced conflicts at the write boundary. | | 4 | Exclusive local creation and provider-conditioned remote creation enforce non-forced conflicts at the write boundary. |
| 5 | Subprocess shutdown joins waiter/output completion before returning ownership, with delayed-completion regressions. | | 5 | Subprocess shutdown joins waiter/output completion before returning ownership, with delayed-completion regressions. |
| 6 | Shared response-bound streaming enforces known sizes, preserves unknown-size operation, closes responses, and retains failure causes. | | 6 | Shared response-bound streaming enforces known sizes, preserves unknown-size operation, closes responses, and retains failure causes. |
@@ -56,7 +66,7 @@ signal rather than asserting exact message wording or elapsed time.
| 9 | Changed local copies use existing atomic streaming and installed-byte checksums. | | 9 | Changed local copies use existing atomic streaming and installed-byte checksums. |
| 10 | Publication mapping uses confined source descriptors rather than retaining all open handles. | | 10 | Publication mapping uses confined source descriptors rather than retaining all open handles. |
| 11 | Sources are transferred and closed sequentially; same-handle use, late failure, and pointer-last selection remain protected. | | 11 | Sources are transferred and closed sequentially; same-handle use, late failure, and pointer-last selection remain protected. |
| 12 | Original audit reports remain unchanged and only the nine scoped catalog entries are closed; the stage-completion claim needs R1 follow-through. | | 12 | Original audit reports remain unchanged and only the nine scoped catalog entries are closed; R1 follow-through is complete. |
No additional correctness defect or inadvertently strengthened requirement was No additional correctness defect or inadvertently strengthened requirement was
identified in this sprint's scope. Workspace serialization, delayed shutdown identified in this sprint's scope. Workspace serialization, delayed shutdown
@@ -76,5 +86,6 @@ Passed with Go 1.27.4:
documentation; and documentation; and
- `git diff --check`. - `git diff --check`.
The finding concerns missing operator feedback, which the passing lock tests do Those checks describe the original review. The remediation adds the shared
not assert. No production code was changed or live external services invoked. acquisition diagnostic and command-level regression above; focused verification
is recorded with the fixing commit. No live external services were invoked.

View File

@@ -87,7 +87,7 @@ func cleanSelectedSession(ctx context.Context, input *cleanCommandInput, deps co
} }
if !input.DryRun { if !input.DryRun {
store := deps.newWorkspaceStore(pipeline.Workspace.Root) store := deps.newWorkspaceStore(pipeline.Workspace.Root)
lock, lockErr := store.AcquireWorkspaceLockContext(ctx) lock, lockErr := acquireWorkspaceLock(ctx, store, pipeline.Workspace.Root, deps.reporter)
if lockErr != nil { if lockErr != nil {
return report, fmt.Errorf("clean: acquire workspace lock: %w", lockErr) return report, fmt.Errorf("clean: acquire workspace lock: %w", lockErr)
} }

View File

@@ -6,6 +6,8 @@ import (
"errors" "errors"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"sync"
"testing" "testing"
"time" "time"
@@ -16,6 +18,71 @@ import (
"go.maximumdirect.net/commandkit" "go.maximumdirect.net/commandkit"
) )
type lockDiagnosticWriter struct {
mu sync.Mutex
data bytes.Buffer
path string
seen chan struct{}
once sync.Once
}
func (w *lockDiagnosticWriter) Write(p []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
n, err := w.data.Write(p)
if strings.Contains(w.data.String(), w.path) {
w.once.Do(func() { close(w.seen) })
}
return n, err
}
func TestCleanReportsWorkspaceLockBeforeWaiting(t *testing.T) {
root := t.TempDir()
pipeline, _, _ := 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{})
app, err := newApplication(commandDependencies{newWorkspaceStore: func(root string) artifacts.Store {
return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attempted}
}}, executePlan)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
diagnostic := &lockDiagnosticWriter{path: artifacts.WorkspaceLockPath(root), seen: make(chan struct{})}
done := make(chan commandkit.Outcome, 1)
go func() {
done <- app.Execute(ctx, []string{"session", "clean", "--all", "--config", pipeline, "--progress"}, commandkit.Streams{Out: &bytes.Buffer{}, Err: diagnostic})
}()
select {
case <-diagnostic.seen:
case <-time.After(5 * time.Second):
t.Fatal("workspace lock path was not reported before acquisition completed")
}
select {
case <-attempted:
case <-time.After(5 * time.Second):
t.Fatal("command did not contend for the held lock")
}
cancel()
select {
case outcome := <-done:
if outcome.Status == 0 {
t.Fatal("cancelled cleanup succeeded")
}
case <-time.After(5 * time.Second):
t.Fatal("waiting command did not cancel")
}
if _, err := os.Stat(filepath.Join(root, "work")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("waiting command mutated managed work: %v", err)
}
}
type observedWorkspaceStore struct { type observedWorkspaceStore struct {
artifacts.Store artifacts.Store
entering chan struct{} entering chan struct{}

View File

@@ -96,7 +96,7 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl
} }
artifactStore := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root) artifactStore := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root)
lock, err := artifactStore.AcquireWorkspaceLockContext(ctx) lock, err := acquireWorkspaceLock(ctx, artifactStore, cfg.Pipeline.Workspace.Root, deps.reporter)
if err != nil { if err != nil {
return diagnostic, fmt.Errorf("restore: acquire workspace lock: %w", err) return diagnostic, fmt.Errorf("restore: acquire workspace lock: %w", err)
} }

View File

@@ -64,7 +64,7 @@ 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
} }
lock, err := runtime.artifactStore.AcquireWorkspaceLockContext(ctx) lock, err := acquireWorkspaceLock(ctx, runtime.artifactStore, cfg.Pipeline.Workspace.Root, runtime.env.Reporter)
if err != nil { if err != nil {
return nil, fmt.Errorf("acquire workspace lock: %w", err) return nil, fmt.Errorf("acquire workspace lock: %w", err)
} }

View File

@@ -179,7 +179,7 @@ func initializeSession(ctx context.Context, request *sessionInitializationInput,
} }
if managed { if managed {
store := deps.newWorkspaceStore(base.Pipeline.Workspace.Root) store := deps.newWorkspaceStore(base.Pipeline.Workspace.Root)
lock, lockErr := store.AcquireWorkspaceLockContext(ctx) lock, lockErr := acquireWorkspaceLock(ctx, store, base.Pipeline.Workspace.Root, deps.reporter)
if lockErr != nil { if lockErr != nil {
return report, fmt.Errorf("session init: acquire workspace lock: %w", lockErr) return report, fmt.Errorf("session init: acquire workspace lock: %w", lockErr)
} }

View File

@@ -0,0 +1,17 @@
package app
import (
"context"
"fmt"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/logging"
)
// acquireWorkspaceLock identifies acquisition before a potentially blocking wait.
func acquireWorkspaceLock(ctx context.Context, store artifacts.Store, root string, reporter logging.Reporter) (*artifacts.LockHandle, error) {
if reporter != nil {
reporter.Progress(fmt.Sprintf("acquiring workspace lock %q", artifacts.WorkspaceLockPath(root)))
}
return store.AcquireWorkspaceLockContext(ctx)
}