A guard acquires
guard ACQUIRE BODY RELEASE owns acquisition and release as one dynamic
extent; the release observes the body’s ending but cannot consume it.
Agreed 2026-11-10 and 2026-11-11. This amends
a-failing-cleanup-pre-empts and
a-cleanup-is-shielded-within-its-grace.
Why
- The acquisition window must belong to the operator. In
let t = temp-dir; guard …, cancellation during creation or between the binding and frame installation can leak the directory. Step-boundary polling makes that window routine under exarch’s wall timeouts. The koalain-temp-dir, makeselfwith-srcand web-search helpers exhibited it. Haskell’sbracketmasks acquisition for the same reason. - Rollback needs the ending. Immutable bindings cannot remember whether
to remove a staging file on failure, exit or Ctrl-C. A release inspecting
the ending expresses that in one
case, likegeneralBracket. Unlike Python’s__exit__, returning a value cannot suppress the ending. - Creation must not precede a predictable removal refusal.
temp-*needs filesystem write authority, butrmalso needs exec admission. Bundledrmexists only withcoreutils; other builds needPATH. Without a precheck, a grant omitting or vetoingrmwould create a path, refuse its release and leak it, replacing even a successful body with an error about an unwritten command. - Typing does not decide what is syntax.
try,guardandgatherhave ordinary HM types. Their dynamic extent needs a machine frame or worker, which a function over thunks cannot supply in tail position: a native re-entersmachine::applyand meetsNESTED_MACHINE_LIMIT.
Decision
- D1–D2: execution order, one arity. The body takes the resource; the
release takes the resource and ending. A resource-less guard uses
guard { () } { |_| … } { |_ _| … }; no second release shape is added. - D3: observable endings.
ExitCaseis the closed variant`ok | `err ErrorRecord | `exited Int | `stopped CancelCause.okis nullary (its arm receives()); the body’s value is not passed.errcarries the witnessed recordtrysupplies, soraisepreserves its exact reason. A panic executes no release. - D5: bounded acquisition shielding. Acquisition and release both use
Shell::shield(cleanup_grace). A pending stop is polled before acquisition; a stop during it lets it finish within the grace. The guard frame is installed before the body’s first poll can observe that stop. - D6: removal remains
rm.with-temp-dirandwith-temp-fileare prelude functions overguard, releasing withrm -rfandrm -f. There is no native removal operation. Keep workers using the path inside agatherin the body: removal follows the body’s extent, not loose work. - D7:
temp-*requiresrmbefore creation.would_run("rm", …)usesCommand::from_name→lookup→admit, including the admitted command’s retained lookup error, without launching anything. Bundled orPATHlookup and grants are exactly the external command’s; a selected refusal is recorded through the same admission door. Preserve its error (including not-found status 127 or grant denial), adding one hint naming why the temporary-path builtin needsrm. Parent write authority already covers the invented leaf; no separate filesystem precheck is added. - D8: a frame’s observation is not an
Endingprojection.ExitCase<F>is its own type because no frame observes panic. It shares the tag table and four payload types. The type identity is pinned againstDone::ty()with onlypanicremoved.
The result is the body’s F^g α; acquisition and release grades do not
change it. In particular,
let x = guard { () } { |_| echo hi } { |_ _| () } captures hi.
Amended 2026-11-12. The acquisition is a binding, so it binds as
letdoes (grades and capture): a command acquisition is captured,guard { mktemp -d } { |d| … } …givingdthe path, and the checked rule’s acquire isU (F^p R), notU (F^ν R)with ν free. A free ν bound awproducer’s()whereletwould have captured its output. The checker sharesSolver::binding; readback wraps a captured acquire as{ capture (force A) }.dev/agda/Intrinsic/and the paper carryF p R.
D5: bounds and evidence
There is one budget from the strike, not one per phase.
Scope::shieldedandresolveuse the earliestcancelled_atabove the shield, capped by the nearest enclosing shield’s grace;Abortedis never masked. Acquisition and release therefore sharesince + grace.- An acquisition exceeding the grace is stopped and runs no release; anything it already held can leak. One finishing near the deadline leaves little release time: once the grace expires, the release’s first command polls and stops, possibly leaking the resource. Masking, not all host work, is bounded by the grace; polling is cooperative.
- Terminal SIGINT still reaches external children. A child dying under the
mask is a process failure (
`signaled 2), not a masked stop. If this halts acquisition, no release runs. - Owned, not inherited. The shield is in the extent’s ancestry: pipeline
stages, external children, nested machines and workers of a
gatheropened inside acquisition or release are masked with it. A worker born into an outside owner — an enclosinggather, a worker’s body or the session — hangs under that owner’s scope, not the shield. This rule is identical for acquisition and release; worker lifetime and cancellation machinery are unchanged. Delegate acquisition work through an inside owner:guard { gather { let h = spawn { … }; await $h } } { |r| … } { |r _| … }. Awaiting an outside owner’s worker can instead halt acquisition on that worker’s stop, despite the awaiter’s shield, and run no release. - The machine checks room for three computational frames before acquiring:
the deepest release stack is
Cleanupplus twoArgs. PoppingAcquireorGuardrestores entry depth; later guard reservations are assertions of that reserved room, never fallible exits while holding the resource. Acquirerestores the scope, installsGuard { release, resource }, then calls the body without a poll between.forceneither pushes nor polls; the β-step polls only after poppingArg.guard_releasesaves the untouched outcome inCleanupbefore calling release withexit_case. Return restores that outcome; a release halt replaces it.
Rejected: birth-place masking
A worker follows its owner, not the scope at its spawn site. Stages hang
under the current scope (launch_thread_stage); workers hang under
cradle.under (spawn_child). Opening gather captures the current scope
as its cradle. Trio likewise gives a task its nursery’s cancel scopes.
Shielding cradle.under alongside scope was rejected. A node’s ancestry is
fixed at birth: a worker outliving acquisition or release would keep that
mask for life. The time bound would survive — no shield masks past
since + grace, and a brood stops children on their own nodes — but:
- Ordinary work started in acquisition would ignore Ctrl-C for the grace.
spawnwould cease to be compositional: stop response would depend on birthplace, not only on the owner.- Haskell’s
forkIOinherits its mask and neededforkIOWithUnmaskto undo that inheritance; ral adds neither mechanism.
D7: extent and evidence
The precheck proves present lookup and admission, not future deletion.
Command::from_namechooses bundledrmwhen available, otherwise the effectivePATH;lookupjudges candidates andadmitreports the chosen denial.require_rmruns beforewritable_temp_diror exclusive creation in eitherbuiltin_temp_dirorbuiltin_temp_file.- In
with-temp-*, acquisition and release have the same dynamic grants andPATH: a context the body scopes ends before release. An enclosingwithinhandler forrmstill receives the release command; its meaning belongs to the handler. The precheck neither runs nor replaces it. - A bare
temp-*caller owns its lifetime; changing the context later is its responsibility. Filesystem races, removal failures and grace expiry remain possible; the rule prevents creation under an already known launch refusal.
Where
core/src/shell/evaluator/machine.rs:Frame::{Acquire, Guard, Cleanup},guard_release,exit_case, entry reservation and β polling.core/src/fact/ending.rs:ExitCase, sharedtagtable and type test.core/src/typecheck/generate/control.rs:Generator::guardandExitCase::<ErrorRecord>::ty().core/src/shell/exec/command.rs:would_run, lookup and admission.core/src/shell/builtins/fs.rs:require_rmbefore either creation path.core/src/process/cancel.rs:Scope::shielded,resolve,cancelled_at.core/src/shell/exec/pipeline/thread.rs:launch_thread_stageparents stages under the current scope.core/src/shell/builtins/concurrency/birth.rs:spawn_childparents workers underCradle::under;machine.rscaptures scope when openingGather.core/src/shell/prelude.ral:with-temp-dir,with-temp-file.
See control operators,
failure, endings,
the machine and
cancellation. User contract: docs/SPEC.md §8.7.