Skip to content

Latest commit

 

History

History
308 lines (246 loc) · 18.9 KB

env-minted-root.md

File metadata and controls

308 lines (246 loc) · 18.9 KB
title Environment-Minted Root
issue #393
status complete
created 2026-08-13
updated 2026-08-13

Plan: Environment-Minted Root

Superseded in part, 2026-08-25. The three-variant design below — the Mode type over ModeSandboxed / ModeUnsandboxed / ModeWritableUnsandboxed, and the dispatching Open(dir string, mode Mode) — was replaced by 4.5-fsroot-variants.md on 2026-08-19, whose status records why: "tracing their consumers found the middle one unimplemented and the outer one justified by bootstrapping rather than access, so the design collapses to a single sandbox behavior and two types." Measured 2026-08-25: none of those three Mode values, nor OpenUnsandboxed / OpenWritableUnsandboxed, appears in any Go file. The surviving constructors are OpenExisting and OpenScratch, both sandboxed. The rest of this plan stands as the record of what was done under #393.

Implements the amended #393 ruling (option 4, banked at #393 issuecomment-5283660132): RuntimeEnvironmentSpec carries no live fsroot.Dir — only the anchor path and access mode — and every RuntimeEnvironment mints its own Root and closes it. Branch: env-minted-root. Tracking issue: #393 (pre-existing; no new issue). Campaign: #373 / platform-test-matrix.md.

Summary

The sandboxed Root's directory handle (os.OpenRoot) leaks on every path that mints a Root into a spec without a Run to close it, and Windows turns each leak into a RemoveAll test failure — 18 of the standing 48. The verified fix: no handle ever lives in a spec. The spec carries two serializable values (anchor path + mode), NewRuntimeEnvironment mints from them, and RuntimeEnvironment.Close — already the single closer — releases what it minted. Nothing mints before environment build, so pre-Run error paths cannot leak, structurally. The deciding fact was verified exhaustively on 2026-08-13: nothing between spec construction and Run dereferences spec.Root (sole production readers runtime_environment.go:200,206; all nine host mint→Run gaps clean; no .star script or doc touches spec.root).

Goals

  1. No live Root in any spec — RuntimeEnvironmentSpec holds anchor path + access mode only.
  2. The environment mints and closes its own Root — executor lifecycle ownership unchanged.
  3. plan.spec keeps its fail-fast contract — an open-and-release probe at spec time; the authoritative gate stays the mint at Run's preflight (PhasePreparing → ReasonPreflightFailed).
  4. Clear the 18 Windows handle-leak failures and structurally heal the lore closed-Root loop defect (cmd/lore/lore/commands.go:259).

Current State

Component Status Notes
Happy-path close ✅ Working GraphExecutor.Run defer → RuntimeEnvironment.Close → iox.Close(re.Root)
Pre-Run error paths ❌ Leak plan.Provider.Spec (provider.go:475), devlore-test buildSpec (test_context.go:829) mint Roots no Run closes
lore command loop ❌ Defect one spec's Root reused by N executors (commands.go:259); iteration 2+ runs against a closed Root
devlore-test root aliasing ⚠️ Latent runner.go:281 aliases the spec's root into TestContext for post-close reads; benign only because unsandboxed Close is a no-op
cmd/lore/lore/integration_test.go 💀 Dead //go:build ignore, references removed APIs (op.contextBase) — rider: delete

Requirements

1. fsroot.Mode and mode-dispatched opening

pkg/fsroot gains a Mode type naming its three implementations, and one constructor that dispatches on it:

  • ModeSandboxed (zero value — the production-correct default), ModeUnsandboxed (read-only), ModeWritableUnsandboxed.
  • Open(dir string, mode Mode) (Root, error) — dispatches to OpenExisting / OpenUnsandboxed / OpenWritableUnsandboxed. Only the sandboxed branch can fail; the unsandboxed constructors stay error-free and public (tests and TestContext use them directly).

2. Spec carries anchor + mode

In pkg/op/runtime_environment.go:

  • RuntimeEnvironmentSpec.Root fsroot.Dir → RootPath string + RootMode fsroot.Mode.
  • WithRoot(root fsroot.Dir) → WithRoot(path string, mode fsroot.Mode) — anchor and mode travel together; the name stays because the method still specifies the root.
  • Empty RootPath = no root: env.Root stays nil and no RecoverySite is built — the existing nil-Root semantics, with the guard at runtime_environment.go:206 re-keyed to the mint result.
  • Starlark surface: the spec's goReceiver now projects root_path / root_mode instead of root. Verified breaking nothing — no script or doc dereferences spec.root.

3. NewRuntimeEnvironment mints; the signature gains an error

  • NewRuntimeEnvironment(ctx, spec) *RuntimeEnvironment → (ctx, spec) (*RuntimeEnvironment, error). When RootPath is non-empty, mint via fsroot.Open(spec.RootPath, spec.RootMode); a mint failure is the error. Close is unchanged — it already owns the Root's release.
  • Callers updated: op.Plan (planner.go:49 — propagates), GraphExecutor.Run (graph_executor.go:477), GraphExecutor.ResumeUnwind (graph_executor.go:296), and the direct-environment hosts (cmd/star/star/application.go:82, cmd/writ/writ/verify/verify.go:260, cmd/writ/writ/readback/readback.go:520, cmd/lore/lore/builder.go:107).
  • In Run / ResumeUnwind, a mint failure lands the preflight-failed terminal before any dispatch: RunStatus{Phase: PhaseStopped, Condition: ConditionExecutionFailed, Reason: ReasonPreflightFailed} — and the teardown defer is registered only after a successful build.

4. plan.Provider.Spec keeps fail-fast via open-and-release

provider.go:475's retained mint becomes a probe: fsroot.OpenExisting(rootPath) + immediate Close in the same statement group. The error contract and message shape ("plan.Provider.Spec: open root %s: %w") survive verbatim; the mint itself is the check, so no second definition of "valid" exists. The returned spec is built with WithRoot(rootPath, fsroot.ModeSandboxed).

5. Host mint sites dissolve

Every host OpenExisting + error handling collapses to a WithRoot(path, mode) argument. Spec factories whose only error source was the mint become infallible (error return dropped — greenfield, no compatibility shims), and their callers simplify:

Site Change
cmd/writ/writ/deploy/plan.go:387,412 deploySpec / runSpec infallible; sandboxed
cmd/writ/writ/adopt/batch.go:274 buildSpec infallible; sandboxed
cmd/writ/writ/migrate/execute.go:74, helpers.go:90 inline mint removed; migrateSpec infallible; sandboxed
cmd/writ/writ/upgrade/upgrade.go:566 upgradeSpec infallible; sandboxed
cmd/writ/writ/decommission/decommission.go:295 removalSpec infallible; sandboxed
cmd/writ/writ/secret/encrypt.go:253 encryptSpec infallible; sandboxed
cmd/writ/writ/verify/verify.go:255 mint removed; spec WithRoot(separator, sandboxed); handles the env-build error
cmd/writ/writ/readback/readback.go:515 same as verify
cmd/lore/lore/commands.go:245 mint removed; the N-executor loop at :259 heals — each Run mints fresh
cmd/star/star/application.go:81 WithRoot(wd, ModeWritableUnsandboxed); handles the env-build error
cmd/devlore-test/devloretest/test_context.go:829 buildSpec mint removed; sandboxed at tc.tmpDir
cmd/devlore-test/devloretest/runner.go:241 spec gets WithRoot(tmpDir, ModeWritableUnsandboxed); TestContext keeps constructing its own unsandboxed root — separate object, separate lifecycle; the aliasing and double-close dissolve

6. Tests

  • fsroot.Open dispatch: one test per mode, plus the sandboxed failure path.
  • NewRuntimeEnvironment with a bad anchor returns an error; with an empty RootPath yields a nil-Root environment with no RecoverySite.
  • GraphExecutor.Run with a bad anchor lands ReasonPreflightFailed and dispatches nothing.
  • Closed-Root-reuse regression (cross-platform, the lore bug's shape): two executors built sequentially from one spec; both Runs succeed because each mints its own Root. This asserts the heal on every OS — it does not need Windows to observe.
  • plan.Provider.Spec fail-fast: existing contract tests keep passing against the probe.
  • Migration of the ~19 WithRoot( occurrences across 10 test files to the new signature.
  • The Windows proof stays CI-side: the 18 leak failures (plan-package graph tests + resume family) are expected to clear on test (windows-latest) — Unix cannot observe the leak.

Implementation Phases

Phase 1: fsroot Mode — status: complete (2026-08-13)

  • Mode type, three values, Open(dir, mode) dispatch, doc comments per style guide.
  • Unit tests for the dispatch and the sandboxed failure path — behavioral discriminators (post-Close failure = sandboxed; errors.ErrUnsupported on write = read-only; post-Close success = writable unsandboxed), plus the missing-directory failure and the zero-value contract (Mode(0) == ModeSandboxed). make vet and full make test green.

Files: pkg/fsroot/root.go — Modify; pkg/fsroot/root_test.go — Modify.

Phase 2: spec + environment + executor — status: complete (2026-08-13)

  • Spec fields + WithRoot(path, mode); NewRuntimeEnvironment mints, returns error.
  • Run / ResumeUnwind preflight-failure terminals; defer registered only after a successful build.
  • op.Plan propagates the environment-build error.
  • pkg/op test migration + the new tests: mint-from-anchor, bad-anchor error, empty-anchor nil-Root semantics, Run bad-anchor → ReasonPreflightFailed, and the closed-Root-reuse regression (two executors, one spec, both green). Ride-along: env locals renamed environment in every touched test file (standing naming ban).

Discovered constraint (2026-08-13): phases 2–4 cannot be verified independently — make test depends on generate, which builds the in-tree star binary, which consumes the changed APIs through cmd/star/star and pkg/op/provider/plan. Phase 3 and the star slice of phase 4 were therefore pulled forward and verified jointly with phase 2.

Phase 3: plan provider probe — status: complete (2026-08-13)

  • plan.Provider.Spec open-and-release probe; spec built from anchor + sandboxed mode; error message shape preserved ("plan.Provider.Spec: open root %s").
  • Plan-provider test migration (all nine test files); the defaults-contract test now asserts RootPath/RootMode instead of handle identity. Full make test: every pkg/ package green; remaining reds are exactly the phase-4 host set below.

Phase 4: hosts — status: complete (2026-08-13; rider executes at commit)

  • cmd/star/star/application.go — pulled forward (codegen gate; see phase 2 note).
  • All remaining host sites migrated. The six writ spec factories (deploySpec, buildSpec, migrateSpec, upgradeSpec, removalSpec, encryptSpec) became infallible and their eleven caller hunks simplified; adopt and migrate-register collapsed their two-spec planning/execute pairs into one shared spec (safe under #393 — each phase mints its own Root). lore's commands.go mint removed — the N-executor loop now heals structurally. verify/readback anchor at the separator path via the spec; both loading environments now CLOSE (a pre-existing handle leak in both, fixed en passant). devlore-test's spec carries the anchor; TestContext keeps its own writable-unsandboxed root (aliasing dissolved).
  • Host-side test migration (migrate/receipt_integration_test.go, lore/builder_test.go). Ride-along: env/sharedEnv identifiers renamed in every touched file.
  • Rider: delete dead cmd/lore/lore/integration_test.go (//go:build ignore, removed APIs) — a git rm folded into the eventual commit script (git operations are script-side).

Verification: full make test — ZERO failures repository-wide; gofmt clean over the change set.

Flagged during phase 4 (user request, 2026-08-13): defer-lambda closes vs iox.Close in writ — findings reported; resolution pending a ruling: verify.go loadGraph and readback.go Fold (both introduced this change), identity.go:214 (pre-existing; identity.go:103 already uses the idiom), snapshot_test.go:152 (test-side, different fix shape — no error return to join).

Files: the cmd/ files in the Requirement 5 table — Modify; cmd/lore/lore/integration_test.go — Delete.

Phase 5: sweep and proof — status: complete except the PR (2026-08-13)

  • gofmt -l clean over the change set (40 files).
  • Go-style compliance sweep on every touched file: 77 multi-line doc summaries split, 37 over-120-column lines rewrapped (10 of them multi-line signature reflows), and one blank-line-after-signature inserted. Both mechanical detectors — first-doc-line-followed-by-text, and raw >120 columns — now report zero findings across the touched set.
  • make vet-all, make lint-all, make build-all: green on linux, darwin, AND windows (lint reports 0 issues per GOOS).
  • Full make test: zero failures repository-wide.
  • iox.Close conversions (user directive): verify.go loadGraph, readback.go Fold, and the pre-existing identity.go loadRecipientsFile converted from defer func(){ _ = x.Close() }() to named-return + defer iox.Close(&err, x), so close failures join the result instead of being discarded under a nolint. No production defer-lambda close remains in cmd/writ. (snapshot_test.go:152 is test-side with no error return — left as is.)
  • PR #402 opened; every leg green except test (windows-latest), as expected.

First windows measurement — 48 → 45, NOT the predicted ~30 (2026-08-13)

Measured against head dd72af41's check-runs, uncapped: 45 --- FAIL lines, zero [build failed]. The framework change delivered −3, not −18, and the estimate this plan carried was wrong.

Why. 15 of the 45 still carry the leak signature (TempDir RemoveAll cleanup: … being used by another process), and every one of them is a test-side runtime environment that is never closed — not a production path. The framework contract is that whoever constructs an environment closes it; these tests construct one and never do. That was true before this change (the environment held spec.Root, unclosed) and remained true after (the environment mints its own Root, unclosed). Relocating the mint could not fix it.

The proof is a natural experiment inside one package: lifecycle_e2e_test.go, lifecycle_starlark_test.go, and result_flow_starlark_test.go each close their environment and none of their tests appear in the failure list; provider_test.go (2 mints), lifecycle_api_test.go (10), gather_api_test.go (1), git_resume_test.go (1), and receipt_integration_test.go (1) close nothing and all of their tests do. 15 unclosed mint sites, 15 leak failures.

The estimate's error, named: the #393 diagnosis attributed these 18 failures to production pre-Run error paths and the resume family. Those production leaks were real and are fixed (lore's closed-Root loop, verify/readback never closing, devlore-test's aliasing) — but they were not what these tests were failing on. The verification that preceded the option-4 ruling asked whether anything dereferences spec.Root between spec construction and Run (it does not, and that holds); it never asked who closes the environment in the failing tests. Inherited estimates get their own enumeration — see [[verify-ledger-facts-by-enumeration]].

No regressions: the other 30 failures are the standing write/path/chown grind plus the known singles, unchanged, and no failure anywhere traces to the new mint or preflight code paths.

Phase 6: close the 15 unclosed test environments — status: complete (2026-08-13)

  • t.Cleanup(func() { _ = environment.Close() }) at all 15 mint sites across the five files above, matching the idiom the three already-passing helpers use.
  • Verified by enumeration rather than assumption: repo-wide, every test file that sets a root now closes it. The files that mint without a root (pkg/op internals, instance_test.go, builder_test.go) hold no handle; TestNewRuntimeEnvironment_BadAnchorFails mints nothing because the mint is what fails.
  • make test zero failures; make lint-all 0 issues per GOOS; gofmt clean.
  • Second windows measurement (head 27d23e8e, uncapped): 28 --- FAIL, 0 leak signature, 0 panics, 0 [build failed]. Seventeen --- FAIL lines cleared, none added — the 17-vs-15 gap is naming, not extra wins (two cleared tests are parent/subtest pairs whose /json child counts a second --- FAIL line against one cleanup).

Outcome

48 → 28 across the branch; the handle-leak cluster is closed (18 → 0). PR #402 merged to develop as 810745cf.

Measurement --- FAIL leak-signature
baseline (develop) 48 18
framework change only (dd72af4) 45 15
with test cleanups (27d23e8) 28 0

The −18 this plan opened with was close to the −20 delivered, but its reasoning was wrong: 3 came from the framework change and 17 from closing test environments. The production defects #393 named were real and are fixed; they simply were not what those tests were failing on. Recorded here rather than smoothed over, because the campaign's counts are only as trustworthy as their attributions.

Known non-blocker: make check fails its complexity step on two pre-existing functions this branch never touched — git guessDirName (27) and cli runSelfInstall (22). The gate is local-only (CI's quality-gate does not run it) and unrelated to this work; every other check step passes.

Migration Path

None — greenfield internal refactor. The Starlark-facing surface is unchanged where it is used (plan.spec(root_path=...) arguments are already strings; no script reads spec.root).

Files to Create/Modify

Consolidated in Requirements 1–5 and the phase lists above; no new files beyond tests.

Related Documents

  • Issue #393 — the ruling (amended 2026-08-13) and full diagnosis
  • platform-test-matrix.md — the #373 campaign this clears 18 failures for
  • Issue #373 — CI platform gap

Open Questions

None — the amended ruling closes the design; naming and placement decisions above follow it and the style guide.