← Back to Pull requests

Release or report compute left running after a failed resume or exec #245

Merged
aramase merged 23 files (2824 lines) on Nov 09, 2026 23:06 UTC
View on GitHub
aramase aramase commented on Nov 05, 2026 03:46 UTC
Author

Refs #242

A Resume or Exec that fails after the runtime returns compute (lazy dial, confirm, recheck, fence) left that compute running with nothing journaled to own it, and the caller got no signal.

  • One deferred check, armed once Create or Restore succeeds, verifies the journal's hash chain and leaves compute the journal owns (LIVE from this harness, not a replacement instance) alone.

  • Unowned compute is released through CleanupRuntime.ReleaseSession (30s, ignores caller cancellation). Otherwise, or when another owner may hold it (checkpoint, fence, deletion, moved head) or the journal cannot say who owns it, the error becomes ErrComputeLeftRunning. gRPC codes are unchanged.

  • Exec refuses a stale expected_last_seq before creating a runtime.

  • The compute-state projection moves to internal/computestate (no behavior change).
  • Detection only; re-suspend or a release SPI stays open on #242. It errs toward reporting: a turn a fork superseded is reported even when the fork then succeeds.

    Diff: 2824 lines (+2748 / -76) across 23 files Reviewer: gambtho Review duration: 6919m
    All Vouch review confidence checks passed
    Residual risk 0.10 = Change Risk (0.72) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 2824 lines diff across 23 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.87 · 5 substantive comment(s)
    0.87
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    85%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    31 items
    Copilot Copilot commented on code on Nov 05, 2026 04:31 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,241 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show a turn on the operation's harness owning it. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read, or another owner (a writer that committed during
    +// the operation, a checkpoint, a newer fence, a deletion) may hold it, so a release could pull it
    +// from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute, disarms
    +// it when another step takes the compute over (handoffPark), and settles it in a defer registered
    +// before the allocation, so every early return after the effect passes through settle.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads the journal: compute the journal owns (LIVE on a turn this Placer
    +// ran, liveHere) is left to it, compute another owner may hold is reported without a release, and
    +// unowned compute is released through api.CleanupRuntime or, failing that, reported as a
    +// *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	// A checkpoint ended this turn's connection after minting its own fence: the checkpoint owns
    +	// the compute (Suspend snapshots it, a stateful Fork clones it), exactly as it does when it
    +	// supersedes a running turn.
    +	if errors.Is(err, errSuperseded) {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}

    Read does not verify the journal's hash chain (sqlitelog/sqlitelog.go:638–648). If a stored SUSPEND is corrupted into RESUME, this guard can accept the unverified LIVE projection and omit the compute-left-running report even after the controller rejects the journal. Verify these records before using them as ownership evidence; verification failure should report unknown ownership and skip release.

    Copilot Copilot commented on code on Nov 05, 2026 04:31 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,241 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show a turn on the operation's harness owning it. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read, or another owner (a writer that committed during
    +// the operation, a checkpoint, a newer fence, a deletion) may hold it, so a release could pull it
    +// from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute, disarms
    +// it when another step takes the compute over (handoffPark), and settles it in a defer registered
    +// before the allocation, so every early return after the effect passes through settle.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads the journal: compute the journal owns (LIVE on a turn this Placer
    +// ran, liveHere) is left to it, compute another owner may hold is reported without a release, and
    +// unowned compute is released through api.CleanupRuntime or, failing that, reported as a
    +// *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	// A checkpoint ended this turn's connection after minting its own fence: the checkpoint owns
    +	// the compute (Suspend snapshots it, a stateful Fork clones it), exactly as it does when it
    +	// supersedes a running turn.
    +	if errors.Is(err, errSuperseded) {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	before := recs
    +	for i, r := range recs {
    +		if r.Seq > g.headBefore {
    +			before = recs[:i]
    +			break
    +		}
    +	}
    +	// LIVE before the call on a turn this Placer ran: the runtime attached the compute that turn
    +	// ran on, which the journal already owns. LIVE now on such a turn: the controller journaled
    +	// this turn on it. LIVE on another Placer's turn says nothing about this backend's compute.
    +	if g.liveHere(before) || g.liveHere(recs) {
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session holds it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// liveHere reports whether recs leave the session's compute LIVE (SES-8) with the latest turn they
    +// record run on this Placer (turnRanHere). Only then does the journal own compute this Placer's
    +// backend returned: after another Placer's turn (an ExecRequest.harness override onto either
    +// one), LIVE is that Placer's compute.
    +func (g *computeGuard) liveHere(recs []eventlog.Record) bool {
    +	return computestate.Of(recs) == api.ComputeLive && g.turnRanHere(latestTurnHarness(recs))

    A LIVE turn on the same harness can belong to an older compute instance: if Create returns a replacement, the controller refuses it with ErrMemoryStateLost before appending, but this predicate still suppresses release and reporting. Compare nonempty g.inc.ComputeInstance and the journal's recorded instance using controller.LatestComputeInstance(recs, g.turnRanHere) before accepting LIVE as ownership. Keep mismatched instances on the release/report path and add a replacement-instance regression test.

    Copilot Copilot commented on code on Nov 05, 2026 04:31 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,241 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show a turn on the operation's harness owning it. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read, or another owner (a writer that committed during
    +// the operation, a checkpoint, a newer fence, a deletion) may hold it, so a release could pull it
    +// from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute, disarms
    +// it when another step takes the compute over (handoffPark), and settles it in a defer registered
    +// before the allocation, so every early return after the effect passes through settle.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads the journal: compute the journal owns (LIVE on a turn this Placer
    +// ran, liveHere) is left to it, compute another owner may hold is reported without a release, and
    +// unowned compute is released through api.CleanupRuntime or, failing that, reported as a
    +// *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	// A checkpoint ended this turn's connection after minting its own fence: the checkpoint owns
    +	// the compute (Suspend snapshots it, a stateful Fork clones it), exactly as it does when it
    +	// supersedes a running turn.
    +	if errors.Is(err, errSuperseded) {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	before := recs
    +	for i, r := range recs {
    +		if r.Seq > g.headBefore {
    +			before = recs[:i]
    +			break
    +		}
    +	}
    +	// LIVE before the call on a turn this Placer ran: the runtime attached the compute that turn
    +	// ran on, which the journal already owns. LIVE now on such a turn: the controller journaled
    +	// this turn on it. LIVE on another Placer's turn says nothing about this backend's compute.
    +	if g.liveHere(before) || g.liveHere(recs) {
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session holds it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// liveHere reports whether recs leave the session's compute LIVE (SES-8) with the latest turn they
    +// record run on this Placer (turnRanHere). Only then does the journal own compute this Placer's
    +// backend returned: after another Placer's turn (an ExecRequest.harness override onto either
    +// one), LIVE is that Placer's compute.
    +func (g *computeGuard) liveHere(recs []eventlog.Record) bool {
    +	return computestate.Of(recs) == api.ComputeLive && g.turnRanHere(latestTurnHarness(recs))
    +}
    +
    +// turnRanHere reports whether a turn recorded under the harness name recorded ran on this Placer.
    +// Unlike ranHere, which counts every turn it cannot attribute because its callers can only refuse
    +// on an overcount, it counts only turns it can: a wrong yes here leaves compute neither released
    +// nor reported. A standalone Placer has one backend, so every turn ran on it. In a Registry, an
    +// empty name is a turn on the session's own harness (api.ExecutionStart.Harness), which is this
    +// Placer unless the operation is an override; any other name counts when it resolves to this
    +// Placer, so an alias does and a name this host does not serve does not.
    +func (g *computeGuard) turnRanHere(recorded string) bool {
    +	if g.p.registry == nil {
    +		return true
    +	}
    +	if recorded == "" {
    +		return !g.override
    +	}
    +	q, ok := g.p.registry.lookup(recorded)
    +	return ok && q == g.p
    +}
    +
    +// latestTurnHarness returns the harness name the latest turn in recs recorded on its
    +// EXECUTION_START, or "" for a legacy turn with no EXECUTION_START or when recs record no turn,
    +// both of which ran on the session's own harness (Registry.Resume runs a session with no pending
    +// turn there too).
    +func latestTurnHarness(recs []eventlog.Record) string {
    +	for i := len(recs) - 1; i >= 0; i-- {
    +		ev := recs[i].Event
    +		switch {
    +		case ev.Kind == api.EventExecutionStart:
    +			if ev.ExecutionStart == nil {
    +				return ""
    +			}
    +			return ev.ExecutionStart.Harness

    This scan can attribute a fork child's compute to a turn in the parent's copied prefix. If the parent's completed turn used override B, a child on A can Resume with no pending turn and append only RESUME. A subsequent failed override onto B then sees LIVE plus the inherited B name and skips both release and reporting, although B has never run that child. Stop at the latest FORK marker and treat a child with no subsequent turn as running on its own harness.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 05, 2026 04:31 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    The guard relies on unverified or misattributed ownership evidence, allowing replacement instances, inherited fork turns, or corrupted journal records to incorrectly suppress compute release and reporting.

    <details open>
    <summary><strong>3 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Verify the journal hash chain before trusting LIVE ownership · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Verify LIVE ownership matches the current compute instance · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Do not attribute inherited parent compute to a fork child · New

  • </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    This PR addresses #242 by adding cleanup or explicit reporting when Exec or Resume fails after allocating compute, using journal state to determine ownership.

    Changes:

  • Adds a deferred compute guard that releases unowned compute or reports ErrComputeLeftRunning, preserving the original error classification.

  • Rejects stale execution cursors before runtime creation.

  • Shares the compute-state projection and adds tests, specification updates, and compatibility notes.
  • | File | Description |
    | ---- | ----------- |
    | sqlitelog/​sqlitelog.go | Uses the shared compute-state projection. |
    | sqlitelog/​sessions.go | Removes the relocated projection helper. |
    | spec.md | Defines cleanup, reporting, and early cursor-check behavior. |
    | session/​compute_left_running_test.go | Tests public reporting and stale-cursor refusal. |
    | session/​compute_left_running_error_test.go | Tests preservation of gRPC error codes. |
    | placement/​registry.go | Extracts a reusable cursor check. |
    | placement/​placement.go | Integrates compute guards into Exec and Resume. |
    | placement/​ownership_test.go | Extends runtime fixtures for cleanup tests. |
    | placement/​compute_guard.go | Implements ownership checks, cleanup, and reporting. |
    | placement/​compute_guard_test.go | Tests failure paths and cross-harness ownership. |
    | internal/​computestate/​computestate.go | Centralizes event-to-compute-state projection. |
    | internal/​computestate/​computestate_test.go | Tests individual events and journal folding. |
    | docs/​allocation-ownership.md | Documents cleanup outside the allocation ledger. |
    | changelog/​unreleased/​compute-left-running.md | Records the cleanup and reporting change. |
    | changelog/​unreleased/​compute-left-running-compat.md | Explains error, timing, and cursor compatibility. |
    </details>

    <sub>Review effort: Balanced</sub>

    aramase aramase commented on code on Nov 05, 2026 07:27 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,241 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show a turn on the operation's harness owning it. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read, or another owner (a writer that committed during
    +// the operation, a checkpoint, a newer fence, a deletion) may hold it, so a release could pull it
    +// from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute, disarms
    +// it when another step takes the compute over (handoffPark), and settles it in a defer registered
    +// before the allocation, so every early return after the effect passes through settle.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads the journal: compute the journal owns (LIVE on a turn this Placer
    +// ran, liveHere) is left to it, compute another owner may hold is reported without a release, and
    +// unowned compute is released through api.CleanupRuntime or, failing that, reported as a
    +// *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	// A checkpoint ended this turn's connection after minting its own fence: the checkpoint owns
    +	// the compute (Suspend snapshots it, a stateful Fork clones it), exactly as it does when it
    +	// supersedes a running turn.
    +	if errors.Is(err, errSuperseded) {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	before := recs
    +	for i, r := range recs {
    +		if r.Seq > g.headBefore {
    +			before = recs[:i]
    +			break
    +		}
    +	}
    +	// LIVE before the call on a turn this Placer ran: the runtime attached the compute that turn
    +	// ran on, which the journal already owns. LIVE now on such a turn: the controller journaled
    +	// this turn on it. LIVE on another Placer's turn says nothing about this backend's compute.
    +	if g.liveHere(before) || g.liveHere(recs) {
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session holds it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// liveHere reports whether recs leave the session's compute LIVE (SES-8) with the latest turn they
    +// record run on this Placer (turnRanHere). Only then does the journal own compute this Placer's
    +// backend returned: after another Placer's turn (an ExecRequest.harness override onto either
    +// one), LIVE is that Placer's compute.
    +func (g *computeGuard) liveHere(recs []eventlog.Record) bool {
    +	return computestate.Of(recs) == api.ComputeLive && g.turnRanHere(latestTurnHarness(recs))

    Fixed, but compared with p.ranHere instead of turnRanHere. That is the attribution the controller's own ErrMemoryStateLost check uses, so the guard calls an instance a replacement exactly when the controller refuses it.

    aramase aramase commented on code on Nov 05, 2026 07:27 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,241 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show a turn on the operation's harness owning it. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read, or another owner (a writer that committed during
    +// the operation, a checkpoint, a newer fence, a deletion) may hold it, so a release could pull it
    +// from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute, disarms
    +// it when another step takes the compute over (handoffPark), and settles it in a defer registered
    +// before the allocation, so every early return after the effect passes through settle.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads the journal: compute the journal owns (LIVE on a turn this Placer
    +// ran, liveHere) is left to it, compute another owner may hold is reported without a release, and
    +// unowned compute is released through api.CleanupRuntime or, failing that, reported as a
    +// *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	// A checkpoint ended this turn's connection after minting its own fence: the checkpoint owns
    +	// the compute (Suspend snapshots it, a stateful Fork clones it), exactly as it does when it
    +	// supersedes a running turn.
    +	if errors.Is(err, errSuperseded) {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	before := recs
    +	for i, r := range recs {
    +		if r.Seq > g.headBefore {
    +			before = recs[:i]
    +			break
    +		}
    +	}
    +	// LIVE before the call on a turn this Placer ran: the runtime attached the compute that turn
    +	// ran on, which the journal already owns. LIVE now on such a turn: the controller journaled
    +	// this turn on it. LIVE on another Placer's turn says nothing about this backend's compute.
    +	if g.liveHere(before) || g.liveHere(recs) {
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session holds it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// liveHere reports whether recs leave the session's compute LIVE (SES-8) with the latest turn they
    +// record run on this Placer (turnRanHere). Only then does the journal own compute this Placer's
    +// backend returned: after another Placer's turn (an ExecRequest.harness override onto either
    +// one), LIVE is that Placer's compute.
    +func (g *computeGuard) liveHere(recs []eventlog.Record) bool {
    +	return computestate.Of(recs) == api.ComputeLive && g.turnRanHere(latestTurnHarness(recs))
    +}
    +
    +// turnRanHere reports whether a turn recorded under the harness name recorded ran on this Placer.
    +// Unlike ranHere, which counts every turn it cannot attribute because its callers can only refuse
    +// on an overcount, it counts only turns it can: a wrong yes here leaves compute neither released
    +// nor reported. A standalone Placer has one backend, so every turn ran on it. In a Registry, an
    +// empty name is a turn on the session's own harness (api.ExecutionStart.Harness), which is this
    +// Placer unless the operation is an override; any other name counts when it resolves to this
    +// Placer, so an alias does and a name this host does not serve does not.
    +func (g *computeGuard) turnRanHere(recorded string) bool {
    +	if g.p.registry == nil {
    +		return true
    +	}
    +	if recorded == "" {
    +		return !g.override
    +	}
    +	q, ok := g.p.registry.lookup(recorded)
    +	return ok && q == g.p
    +}
    +
    +// latestTurnHarness returns the harness name the latest turn in recs recorded on its
    +// EXECUTION_START, or "" for a legacy turn with no EXECUTION_START or when recs record no turn,
    +// both of which ran on the session's own harness (Registry.Resume runs a session with no pending
    +// turn there too).
    +func latestTurnHarness(recs []eventlog.Record) string {
    +	for i := len(recs) - 1; i >= 0; i-- {
    +		ev := recs[i].Event
    +		switch {
    +		case ev.Kind == api.EventExecutionStart:
    +			if ev.ExecutionStart == nil {
    +				return ""
    +			}
    +			return ev.ExecutionStart.Harness

    Fixed at the RESUME marker rather than at FORK. A filesystem-tier child can fork inside a turn and re-drive it on B across the marker, and the same misattribution happens without a fork (B turn, Suspend, Resume on A). When the journal can't tell which harness a Resume ran on, the guard now reports and releases nothing if the call runs on either candidate harness and the runtime returned no replacement instance; a replacement, or a call on a third harness, is treated as unowned.

    Copilot Copilot commented on code on Nov 05, 2026 07:41 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,325 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show the operation's harness owning that compute. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read or verified (hash chain), the journal does not
    +// record whether the latest resume ran on this harness, or another owner (a writer that
    +// committed during the operation, a checkpoint, a newer fence, a deletion) may hold it, so a
    +// release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute, disarms
    +// it when another step takes the compute over (handoffPark), and settles it in a defer registered
    +// before the allocation, so every early return after the effect passes through settle.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, or does not record which harness the latest resume ran on), is reported
    +// without a release; and unowned compute is released through api.CleanupRuntime or, failing
    +// that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore

    If the final SUSPEND is lost during allocation, the remaining completed-turn prefix still passes chain verification, so both ownership checks see LIVE and suppress cleanup and reporting for compute restored from a COLD journal. Reject a returned head below headBefore as unknown ownership before evaluating either prefix. The captured head makes this truncation detectable.

    Copilot Copilot commented on code on Nov 05, 2026 07:41 UTC
    Code Review
    placement/placement.go:1
    @@ -497,6 +512,8 @@ func (p *Placer) Exec(ctx context.Context, log eventlog.Store, sessionUID string
     	if err := c.Exec(ctx, har, inputs, expectedLastSeq); err != nil {
     		var park *api.ApprovalParkedError
     		if errors.As(err, &park) && api.IsParkUnwind(err, park.Ref) {
    +			// The park suspends or keeps the compute under the journal's approval gate.
    +			guard.disarm()
     			return inc, p.handoffPark(operationCtx, log, sessionUID, fence, park, closeInvocation, cfg.observer)

    If the journal becomes unreadable after an approval request is appended, handoffPark fails before suspension, but the already-disarmed guard skips unknown-ownership reporting for compute still running. Disarm only after handoffPark successfully commits the park; keep the guard armed on failure. Same issue in the Resume path at placement/placement.go:1332–1333.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 05, 2026 07:41 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    Critical ownership-handling flaws allow journal truncation and premature guard disarming to suppress cleanup or unknown-ownership reporting for restored or still-running compute.

    <details open>
    <summary><strong>2 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Detect a truncated journal before suppressing cleanup · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Disarm the guard only after handoffPark succeeds · New

  • </details>

    <details>
    <summary><strong>3 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Do not attribute inherited parent compute to a fork child

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Verify LIVE ownership matches the current compute instance

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Verify the journal hash chain before trusting LIVE ownership

  • </details>

    <sub>Review effort: Balanced</sub>

    gambtho gambtho commented on Nov 05, 2026 13:27 UTC
    Reviewer

    Two cases where the new guard doesn't report compute it can't account for. Both match the latest Copilot threads and reproduce locally.

    1. If reading the journal fails inside handoffPark, after the approval request is written, the actor is still running but Exec returns only the read error, not ComputeLeftRunningError. Could the guard stay armed until the park succeeds?

    2. If the journal comes back shorter than headBefore (say the SUSPEND record is missing), the remaining records look LIVE, so the guard treats the compute as owned. Could a head below headBefore count as unknown?

    aramase aramase commented on Nov 05, 2026 19:55 UTC
    Author

    @gambtho Yes to both, folded into "fix(placement): release or report compute left running after a failed resume or exec". The guard now stays armed through handoffPark and is disarmed only once its SUSPEND commits, so an unreadable journal there comes back as ComputeLeftRunningError. A journal that ends before headBefore (or is empty) is reported as unknown ownership and nothing is released. Each has a test row in compute_guard_test.go for both Exec and Resume.

    Copilot Copilot commented on code on Nov 05, 2026 21:54 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,335 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show the operation's harness owning that compute. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read or verified (hash chain) or is shorter than it
    +// was before the operation, the journal does not record whether the latest resume ran on this
    +// harness, or another owner (a writer that committed during the operation, a checkpoint, a newer
    +// fence, a deletion) may hold it, so a release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute and
    +// settles it in a defer registered before the allocation, so every early return after the effect
    +// passes through settle. handoffPark disarms it once its SUSPEND commits the compute to the
    +// approval gate; a handoff that fails before then leaves it armed.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner; a journal that ends before it
    +	// lost records.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, is shorter than before the operation, or does not record which harness the
    +// latest resume ran on), is reported without a release; and unowned compute is released through
    +// api.CleanupRuntime or, failing that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// The chain verifies from genesis only, so a journal that lost its tail still verifies, and its
    +	// prefix can read LIVE on this harness (a COLD session's final SUSPEND lost). headBefore shows
    +	// the loss.
    +	if n := len(recs); g.headBefore > 0 && (n == 0 || recs[n-1].Seq < g.headBefore) {
    +		left.Cleanup = errors.New("ownership unknown: the journal is shorter than it was before the operation")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	before := recs
    +	for i, r := range recs {
    +		if r.Seq > g.headBefore {
    +			before = recs[:i]
    +			break
    +		}
    +	}
    +	// Owned before the call: the runtime attached the compute the journal already owns. Owned
    +	// now: the controller journaled this turn on it.
    +	ownedBefore, ownedNow := g.ownership(before), g.ownership(recs)
    +	if ownedBefore == owned || ownedNow == owned {
    +		return
    +	}
    +	if ownedBefore == ownerUnknown || ownedNow == ownerUnknown {
    +		left.Cleanup = errors.New("ownership unknown: the journal does not record which harness the latest resume ran on")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		// Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may
    +		// still be snapshotting the compute, or may fail before it suspends it, and only the
    +		// Fork's SUSPEND record would show which.
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// ownership is what a journal says about compute this Placer's backend returned.
    +type ownership int
    +
    +const (
    +	// unowned: the journal's compute state is not LIVE, or LIVE is other compute.
    +	unowned ownership = iota
    +	// owned: LIVE is this compute.
    +	owned
    +	// ownerUnknown: LIVE after a resume that ran on this Placer or on another one, and the journal
    +	// does not say which.
    +	ownerUnknown
    +)
    +
    +// ownership reports whether recs leave the session's compute LIVE (SES-8) on compute this Placer's
    +// backend returned:
    +//
    +//   - LIVE must come from this Placer (liveOwner, turnRanHere). After another Placer's turn or
    +//     resume (an ExecRequest.harness override, either way), LIVE is that Placer's compute.
    +//   - The returned instance must not have replaced the one this harness's latest turn, or a fork
    +//     child's FORK marker, recorded (controller.LatestComputeInstance, attributed by ranHere as the
    +//     controller's own check is). The controller refuses such a replacement with
    +//     api.ErrMemoryStateLost before it appends anything, and LIVE is the replaced instance.
    +//
    +// When LIVE comes from a resume that ran either on this Placer or on another one, it is
    +// ownerUnknown: releasing could take compute the journal owns, and keeping it could leak it.
    +func (g *computeGuard) ownership(recs []eventlog.Record) ownership {
    +	if computestate.Of(recs) != api.ComputeLive {
    +		return unowned
    +	}
    +	if g.inc.ComputeInstance != "" {
    +		if last, _ := controller.LatestComputeInstance(recs, g.p.ranHere); last != "" && last != g.inc.ComputeInstance {
    +			return unowned
    +		}
    +	}
    +	recorded, orOwn := liveOwner(recs)
    +	here := g.turnRanHere(recorded)
    +	if orOwn && here != g.turnRanHere("") {
    +		return ownerUnknown
    +	}
    +	if here {
    +		return owned
    +	}
    +	return unowned
    +}
    +
    +// turnRanHere reports whether a turn recorded under the harness name recorded ran on this Placer.
    +// Unlike ranHere, which counts every turn it cannot attribute because its callers can only refuse
    +// on an overcount, it counts only turns it can: a wrong yes here leaves compute neither released
    +// nor reported. A standalone Placer has one backend, so every turn ran on it. In a Registry, an
    +// empty name is a turn on the session's own harness (api.ExecutionStart.Harness), which is this
    +// Placer unless the operation is an override; any other name counts when it resolves to this
    +// Placer, so an alias does and a name this host does not serve does not.
    +func (g *computeGuard) turnRanHere(recorded string) bool {
    +	if g.p.registry == nil {
    +		return true
    +	}
    +	if recorded == "" {
    +		return !g.override
    +	}
    +	q, ok := g.p.registry.lookup(recorded)
    +	return ok && q == g.p
    +}
    +
    +// liveOwner returns the harness name recorded for whatever left recs LIVE, read through
    +// latestTurnHarness: "" is the session's own harness. orOwn reports that the session's own harness
    +// is just as likely.
    +//
    +// A turn record is attributed to its turn, across a FORK marker when a fork child re-drove an
    +// inherited turn. A LIFECYCLE_RESUME is placement's, appended after controller.Resume: a Resume
    +// with a pending turn re-drives it on its recorded harness (Registry.Resume) and appends at least
    +// its END first, while one with nothing pending runs on the session's own harness. So a RESUME
    +// after anything but a turn record (SUSPEND, FORK, another RESUME, an approval decision, nothing)
    +// ran on the own harness, and one directly after a turn record ran either on that turn's harness
    +// or on the own harness: the journal does not record which.
    +func liveOwner(recs []eventlog.Record) (recorded string, orOwn bool) {
    +	for i := len(recs) - 1; i >= 0; i-- {
    +		ev := recs[i].Event
    +		if _, moves := computestate.Event(ev); !moves {
    +			continue
    +		}
    +		if ev.Kind != api.EventLifecycle {
    +			return latestTurnHarness(recs[:i+1]), false
    +		}
    +		if i == 0 || !isTurnRecord(recs[i-1].Event) {
    +			return "", false

    Two unchecked Registry.Resume calls on separate hosts can both select override harness B before either finishes; after the first writes END/RESUME, the second can find no pending turn and append another RESUME while still using B. This branch attributes that second RESUME to the session's own harness A, so a later failed allocation on A is incorrectly treated as owned and neither released nor reported. Preserve uncertain ownership across consecutive RESUME markers, or record the resolved harness explicitly, and cover this interleaving with a two-registry regression test.

    Copilot Copilot commented on code on Nov 05, 2026 21:54 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,335 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show the operation's harness owning that compute. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read or verified (hash chain) or is shorter than it
    +// was before the operation, the journal does not record whether the latest resume ran on this
    +// harness, or another owner (a writer that committed during the operation, a checkpoint, a newer
    +// fence, a deletion) may hold it, so a release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute and
    +// settles it in a defer registered before the allocation, so every early return after the effect
    +// passes through settle. handoffPark disarms it once its SUSPEND commits the compute to the
    +// approval gate; a handoff that fails before then leaves it armed.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner; a journal that ends before it
    +	// lost records.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, is shorter than before the operation, or does not record which harness the
    +// latest resume ran on), is reported without a release; and unowned compute is released through
    +// api.CleanupRuntime or, failing that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// The chain verifies from genesis only, so a journal that lost its tail still verifies, and its
    +	// prefix can read LIVE on this harness (a COLD session's final SUSPEND lost). headBefore shows
    +	// the loss.
    +	if n := len(recs); g.headBefore > 0 && (n == 0 || recs[n-1].Seq < g.headBefore) {
    +		left.Cleanup = errors.New("ownership unknown: the journal is shorter than it was before the operation")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	before := recs
    +	for i, r := range recs {
    +		if r.Seq > g.headBefore {
    +			before = recs[:i]
    +			break
    +		}
    +	}
    +	// Owned before the call: the runtime attached the compute the journal already owns. Owned
    +	// now: the controller journaled this turn on it.
    +	ownedBefore, ownedNow := g.ownership(before), g.ownership(recs)
    +	if ownedBefore == owned || ownedNow == owned {
    +		return
    +	}
    +	if ownedBefore == ownerUnknown || ownedNow == ownerUnknown {
    +		left.Cleanup = errors.New("ownership unknown: the journal does not record which harness the latest resume ran on")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		// Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may
    +		// still be snapshotting the compute, or may fail before it suspends it, and only the
    +		// Fork's SUSPEND record would show which.
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left

    With session.WithAuthorization enabled, a failed allocation confirmation or RESUME append maps to INTERNAL, and the deferred authorization.internalError replaces the entire response with "internal error". This discards the new compute-left-running warning, so those callers still receive no indication that compute remains. Preserve a safe warning or structured status detail through the service mapping and sanitization path, without exposing the original cause, and add an authorization-enabled regression test.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 05, 2026 21:54 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    Concurrent RESUME handling can misattribute compute ownership and leave failed allocations unreleased, while authorization-enabled error sanitization hides warnings that compute remains running.

    <details open>
    <summary><strong>2 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Consecutive RESUMEs can misattribute harness ownership · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Authorization sanitization drops the compute-still-running warning · New

  • </details>

    <details>
    <summary><strong>2 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Disarm the guard only after handoffPark succeeds

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Detect a truncated journal before suppressing cleanup

  • </details>

    <sub>Review effort: Balanced</sub>

    aramase aramase commented on code on Nov 05, 2026 23:16 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,335 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show the operation's harness owning that compute. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read or verified (hash chain) or is shorter than it
    +// was before the operation, the journal does not record whether the latest resume ran on this
    +// harness, or another owner (a writer that committed during the operation, a checkpoint, a newer
    +// fence, a deletion) may hold it, so a release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute and
    +// settles it in a defer registered before the allocation, so every early return after the effect
    +// passes through settle. handoffPark disarms it once its SUSPEND commits the compute to the
    +// approval gate; a handoff that fails before then leaves it armed.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner; a journal that ends before it
    +	// lost records.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, is shorter than before the operation, or does not record which harness the
    +// latest resume ran on), is reported without a release; and unowned compute is released through
    +// api.CleanupRuntime or, failing that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// The chain verifies from genesis only, so a journal that lost its tail still verifies, and its
    +	// prefix can read LIVE on this harness (a COLD session's final SUSPEND lost). headBefore shows
    +	// the loss.
    +	if n := len(recs); g.headBefore > 0 && (n == 0 || recs[n-1].Seq < g.headBefore) {
    +		left.Cleanup = errors.New("ownership unknown: the journal is shorter than it was before the operation")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	before := recs
    +	for i, r := range recs {
    +		if r.Seq > g.headBefore {
    +			before = recs[:i]
    +			break
    +		}
    +	}
    +	// Owned before the call: the runtime attached the compute the journal already owns. Owned
    +	// now: the controller journaled this turn on it.
    +	ownedBefore, ownedNow := g.ownership(before), g.ownership(recs)
    +	if ownedBefore == owned || ownedNow == owned {
    +		return
    +	}
    +	if ownedBefore == ownerUnknown || ownedNow == ownerUnknown {
    +		left.Cleanup = errors.New("ownership unknown: the journal does not record which harness the latest resume ran on")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		// Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may
    +		// still be snapshotting the compute, or may fail before it suspends it, and only the
    +		// Fork's SUSPEND record would show which.
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left

    With authorization on, an Exec or Resume INTERNAL failure that left compute running now returns internal error; compute instance "<id>" may still be running, with no cause or request text. Every other INTERNAL error is still sanitized. Fixed in 3a637e9.

    aramase aramase commented on code on Nov 05, 2026 23:16 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,335 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show the operation's harness owning that compute. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read or verified (hash chain) or is shorter than it
    +// was before the operation, the journal does not record whether the latest resume ran on this
    +// harness, or another owner (a writer that committed during the operation, a checkpoint, a newer
    +// fence, a deletion) may hold it, so a release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute and
    +// settles it in a defer registered before the allocation, so every early return after the effect
    +// passes through settle. handoffPark disarms it once its SUSPEND commits the compute to the
    +// approval gate; a handoff that fails before then leaves it armed.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner; a journal that ends before it
    +	// lost records.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, is shorter than before the operation, or does not record which harness the
    +// latest resume ran on), is reported without a release; and unowned compute is released through
    +// api.CleanupRuntime or, failing that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// The chain verifies from genesis only, so a journal that lost its tail still verifies, and its
    +	// prefix can read LIVE on this harness (a COLD session's final SUSPEND lost). headBefore shows
    +	// the loss.
    +	if n := len(recs); g.headBefore > 0 && (n == 0 || recs[n-1].Seq < g.headBefore) {
    +		left.Cleanup = errors.New("ownership unknown: the journal is shorter than it was before the operation")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	before := recs
    +	for i, r := range recs {
    +		if r.Seq > g.headBefore {
    +			before = recs[:i]
    +			break
    +		}
    +	}
    +	// Owned before the call: the runtime attached the compute the journal already owns. Owned
    +	// now: the controller journaled this turn on it.
    +	ownedBefore, ownedNow := g.ownership(before), g.ownership(recs)
    +	if ownedBefore == owned || ownedNow == owned {
    +		return
    +	}
    +	if ownedBefore == ownerUnknown || ownedNow == ownerUnknown {
    +		left.Cleanup = errors.New("ownership unknown: the journal does not record which harness the latest resume ran on")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		// Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may
    +		// still be snapshotting the compute, or may fail before it suspends it, and only the
    +		// Fork's SUSPEND record would show which.
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// ownership is what a journal says about compute this Placer's backend returned.
    +type ownership int
    +
    +const (
    +	// unowned: the journal's compute state is not LIVE, or LIVE is other compute.
    +	unowned ownership = iota
    +	// owned: LIVE is this compute.
    +	owned
    +	// ownerUnknown: LIVE after a resume that ran on this Placer or on another one, and the journal
    +	// does not say which.
    +	ownerUnknown
    +)
    +
    +// ownership reports whether recs leave the session's compute LIVE (SES-8) on compute this Placer's
    +// backend returned:
    +//
    +//   - LIVE must come from this Placer (liveOwner, turnRanHere). After another Placer's turn or
    +//     resume (an ExecRequest.harness override, either way), LIVE is that Placer's compute.
    +//   - The returned instance must not have replaced the one this harness's latest turn, or a fork
    +//     child's FORK marker, recorded (controller.LatestComputeInstance, attributed by ranHere as the
    +//     controller's own check is). The controller refuses such a replacement with
    +//     api.ErrMemoryStateLost before it appends anything, and LIVE is the replaced instance.
    +//
    +// When LIVE comes from a resume that ran either on this Placer or on another one, it is
    +// ownerUnknown: releasing could take compute the journal owns, and keeping it could leak it.
    +func (g *computeGuard) ownership(recs []eventlog.Record) ownership {
    +	if computestate.Of(recs) != api.ComputeLive {
    +		return unowned
    +	}
    +	if g.inc.ComputeInstance != "" {
    +		if last, _ := controller.LatestComputeInstance(recs, g.p.ranHere); last != "" && last != g.inc.ComputeInstance {
    +			return unowned
    +		}
    +	}
    +	recorded, orOwn := liveOwner(recs)
    +	here := g.turnRanHere(recorded)
    +	if orOwn && here != g.turnRanHere("") {
    +		return ownerUnknown
    +	}
    +	if here {
    +		return owned
    +	}
    +	return unowned
    +}
    +
    +// turnRanHere reports whether a turn recorded under the harness name recorded ran on this Placer.
    +// Unlike ranHere, which counts every turn it cannot attribute because its callers can only refuse
    +// on an overcount, it counts only turns it can: a wrong yes here leaves compute neither released
    +// nor reported. A standalone Placer has one backend, so every turn ran on it. In a Registry, an
    +// empty name is a turn on the session's own harness (api.ExecutionStart.Harness), which is this
    +// Placer unless the operation is an override; any other name counts when it resolves to this
    +// Placer, so an alias does and a name this host does not serve does not.
    +func (g *computeGuard) turnRanHere(recorded string) bool {
    +	if g.p.registry == nil {
    +		return true
    +	}
    +	if recorded == "" {
    +		return !g.override
    +	}
    +	q, ok := g.p.registry.lookup(recorded)
    +	return ok && q == g.p
    +}
    +
    +// liveOwner returns the harness name recorded for whatever left recs LIVE, read through
    +// latestTurnHarness: "" is the session's own harness. orOwn reports that the session's own harness
    +// is just as likely.
    +//
    +// A turn record is attributed to its turn, across a FORK marker when a fork child re-drove an
    +// inherited turn. A LIFECYCLE_RESUME is placement's, appended after controller.Resume: a Resume
    +// with a pending turn re-drives it on its recorded harness (Registry.Resume) and appends at least
    +// its END first, while one with nothing pending runs on the session's own harness. So a RESUME
    +// after anything but a turn record (SUSPEND, FORK, another RESUME, an approval decision, nothing)
    +// ran on the own harness, and one directly after a turn record ran either on that turn's harness
    +// or on the own harness: the journal does not record which.
    +func liveOwner(recs []eventlog.Record) (recorded string, orOwn bool) {
    +	for i := len(recs) - 1; i >= 0; i-- {
    +		ev := recs[i].Event
    +		if _, moves := computestate.Event(ev); !moves {
    +			continue
    +		}
    +		if ev.Kind != api.EventLifecycle {
    +			return latestTurnHarness(recs[:i+1]), false
    +		}
    +		if i == 0 || !isTurnRecord(recs[i-1].Event) {
    +			return "", false

    Agreed. A RESUME is now treated as possibly run on the session's own harness or on any turn's harness since the latest fork marker. When those span this host and another, the guard reports instead of claiming the compute. Added a two-host test. Fixed in 3a637e9.

    Copilot Copilot commented on code on Nov 06, 2026 00:55 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,382 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"iter"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show the operation's harness owning that compute. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read or verified (hash chain) or is shorter than it
    +// was before the operation, the journal does not record whether the latest resume ran on this
    +// harness, or another owner (a writer that committed during the operation, a checkpoint, a newer
    +// fence, a deletion) may hold it, so a release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute and
    +// settles it in a defer registered before the allocation, so every early return after the effect
    +// passes through settle. handoffPark disarms it once its SUSPEND commits the compute to the
    +// approval gate; a handoff that fails before then leaves it armed.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner; a journal that ends before it
    +	// lost records.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, is shorter than before the operation, or does not record which harness the
    +// latest resume ran on), is reported without a release; and unowned compute is released through
    +// api.CleanupRuntime or, failing that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// The chain verifies from genesis only, so a journal that lost its tail still verifies, and its
    +	// prefix can read LIVE on this harness (a COLD session's final SUSPEND lost). headBefore shows
    +	// the loss.
    +	if n := len(recs); g.headBefore > 0 && (n == 0 || recs[n-1].Seq < g.headBefore) {
    +		left.Cleanup = errors.New("ownership unknown: the journal is shorter than it was before the operation")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	before := recs
    +	for i, r := range recs {
    +		if r.Seq > g.headBefore {
    +			before = recs[:i]
    +			break
    +		}
    +	}
    +	// Owned before the call: the runtime attached the compute the journal already owns. Owned
    +	// now: the controller journaled this turn on it.
    +	ownedBefore, ownedNow := g.ownership(before), g.ownership(recs)
    +	if ownedBefore == owned || ownedNow == owned {
    +		return
    +	}
    +	if ownedBefore == ownerUnknown || ownedNow == ownerUnknown {
    +		left.Cleanup = errors.New("ownership unknown: the journal does not record which harness the latest resume ran on")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		// Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may
    +		// still be snapshotting the compute, or may fail before it suspends it, and only the
    +		// Fork's SUSPEND record would show which.
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// ownership is what a journal says about compute this Placer's backend returned.
    +type ownership int
    +
    +const (
    +	// unowned: the journal's compute state is not LIVE, or LIVE is other compute.
    +	unowned ownership = iota
    +	// owned: LIVE is this compute.
    +	owned
    +	// ownerUnknown: LIVE after a resume that may have run on this Placer or on another one, and the
    +	// journal does not say which.
    +	ownerUnknown
    +)
    +
    +// ownership reports whether recs leave the session's compute LIVE (SES-8) on compute this Placer's
    +// backend returned:
    +//
    +//   - LIVE must come from this Placer (liveOwner, turnRanHere). After another Placer's turn or
    +//     resume (an ExecRequest.harness override, either way), LIVE is that Placer's compute.
    +//   - The returned instance must not have replaced the one this harness's latest turn, or a fork
    +//     child's FORK marker, recorded (controller.LatestComputeInstance, attributed by ranHere as the
    +//     controller's own check is). The controller refuses such a replacement with
    +//     api.ErrMemoryStateLost before it appends anything, and LIVE is the replaced instance.
    +//
    +// When LIVE comes from a resume that may have run on this Placer or on another one (liveOwner names
    +// harnesses on both sides), it is ownerUnknown: releasing could take compute the journal owns, and
    +// keeping it could leak it.
    +func (g *computeGuard) ownership(recs []eventlog.Record) ownership {
    +	if computestate.Of(recs) != api.ComputeLive {
    +		return unowned
    +	}

    After an approval park commits SUSPEND, controller.CloseApproval can append a host-only NOT_EXECUTED or OUTCOME_UNKNOWN TOOL_RESULT without waking compute. A subsequent Exec/Resume that allocates compute but fails during confirmation or dialing treats that receipt as LIVE ownership, skipping both release and ErrComputeLeftRunning. Ignore these receipts when deriving ownership, without changing the shared SES-8 projection, and add a park → CloseApproval → failed-dial regression test.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 06, 2026 00:55 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    Host-only CloseApproval receipts can be mistaken for live ownership after suspension, causing failed Exec/Resume attempts to leave allocated compute running without releasing it or reporting ErrComputeLeftRunning.

    <details open>
    <summary><strong>2 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Ignore host-only receipts when deriving compute ownership · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Authorization sanitization drops the compute-still-running warning

  • </details>

    <details>
    <summary><strong>1 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Consecutive RESUMEs can misattribute harness ownership

  • </details>

    <sub>Review effort: Balanced</sub>

    gambtho gambtho commented on code on Nov 08, 2026 18:37 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,382 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"iter"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show the operation's harness owning that compute. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read or verified (hash chain) or is shorter than it
    +// was before the operation, the journal does not record whether the latest resume ran on this
    +// harness, or another owner (a writer that committed during the operation, a checkpoint, a newer
    +// fence, a deletion) may hold it, so a release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute and
    +// settles it in a defer registered before the allocation, so every early return after the effect
    +// passes through settle. handoffPark disarms it once its SUSPEND commits the compute to the
    +// approval gate; a handoff that fails before then leaves it armed.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner; a journal that ends before it
    +	// lost records.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, is shorter than before the operation, or does not record which harness the
    +// latest resume ran on), is reported without a release; and unowned compute is released through
    +// api.CleanupRuntime or, failing that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// The chain verifies from genesis only, so a journal that lost its tail still verifies, and its
    +	// prefix can read LIVE on this harness (a COLD session's final SUSPEND lost). headBefore shows
    +	// the loss.
    +	if n := len(recs); g.headBefore > 0 && (n == 0 || recs[n-1].Seq < g.headBefore) {
    +		left.Cleanup = errors.New("ownership unknown: the journal is shorter than it was before the operation")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	before := recs
    +	for i, r := range recs {
    +		if r.Seq > g.headBefore {
    +			before = recs[:i]
    +			break
    +		}
    +	}
    +	// Owned before the call: the runtime attached the compute the journal already owns. Owned
    +	// now: the controller journaled this turn on it.
    +	ownedBefore, ownedNow := g.ownership(before), g.ownership(recs)
    +	if ownedBefore == owned || ownedNow == owned {
    +		return
    +	}
    +	if ownedBefore == ownerUnknown || ownedNow == ownerUnknown {
    +		left.Cleanup = errors.New("ownership unknown: the journal does not record which harness the latest resume ran on")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		// Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may
    +		// still be snapshotting the compute, or may fail before it suspends it, and only the
    +		// Fork's SUSPEND record would show which.
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// ownership is what a journal says about compute this Placer's backend returned.
    +type ownership int
    +
    +const (
    +	// unowned: the journal's compute state is not LIVE, or LIVE is other compute.
    +	unowned ownership = iota
    +	// owned: LIVE is this compute.
    +	owned
    +	// ownerUnknown: LIVE after a resume that may have run on this Placer or on another one, and the
    +	// journal does not say which.
    +	ownerUnknown
    +)
    +
    +// ownership reports whether recs leave the session's compute LIVE (SES-8) on compute this Placer's
    +// backend returned:
    +//
    +//   - LIVE must come from this Placer (liveOwner, turnRanHere). After another Placer's turn or
    +//     resume (an ExecRequest.harness override, either way), LIVE is that Placer's compute.
    +//   - The returned instance must not have replaced the one this harness's latest turn, or a fork
    +//     child's FORK marker, recorded (controller.LatestComputeInstance, attributed by ranHere as the
    +//     controller's own check is). The controller refuses such a replacement with
    +//     api.ErrMemoryStateLost before it appends anything, and LIVE is the replaced instance.
    +//
    +// When LIVE comes from a resume that may have run on this Placer or on another one (liveOwner names
    +// harnesses on both sides), it is ownerUnknown: releasing could take compute the journal owns, and
    +// keeping it could leak it.
    +func (g *computeGuard) ownership(recs []eventlog.Record) ownership {
    +	if computestate.Of(recs) != api.ComputeLive {
    +		return unowned
    +	}

    Confirmed this one locally: close an approval with NOT_EXECUTED after the park, then fail the next Exec's dial, and the actor stays running with no release or report. Probably just needs the guard to skip host-only receipts, plus a test for that path.

    Copilot Copilot commented on code on Nov 08, 2026 21:41 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,408 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"iter"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal, read after the failure, does
    +// not show the operation's harness owning that compute (the guard's own fold of the records, which
    +// unlike the stored SES-8 compute_state skips a CloseApproval receipt). The host never calls Stop
    +// on this path (RT-7) and did not release the compute either: the backend has no
    +// api.CleanupRuntime, the release failed, the journal could not be read or verified (hash chain) or
    +// is shorter than it was before the operation, the journal does not record whether the latest
    +// resume ran on this harness, or another owner (a writer that committed during the operation, a
    +// checkpoint, a newer fence, a deletion) may hold it, so a release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute and
    +// settles it in a defer registered before the allocation, so every early return after the effect
    +// passes through settle. handoffPark disarms it once its SUSPEND commits the compute to the
    +// approval gate; a handoff that fails before then leaves it armed.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner; a journal that ends before it
    +	// lost records.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, is shorter than before the operation, or does not record which harness the
    +// latest resume ran on), is reported without a release; and unowned compute is released through
    +// api.CleanupRuntime or, failing that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// The chain verifies from genesis only, so a journal that lost its tail still verifies, and its
    +	// prefix can read LIVE on this harness (a COLD session's final SUSPEND lost). headBefore shows
    +	// the loss.
    +	if n := len(recs); g.headBefore > 0 && (n == 0 || recs[n-1].Seq < g.headBefore) {
    +		left.Cleanup = errors.New("ownership unknown: the journal is shorter than it was before the operation")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	// The journal as read now decides: the runtime attached compute the journal owned and nothing
    +	// committed since changed that, or the controller journaled this turn on it. Ownership before
    +	// the operation does not count once a record committed during it says otherwise: after another
    +	// host's SUSPEND the runtime may have woken compute the journal no longer owns, which the moved
    +	// case below reports.
    +	switch g.ownership(recs) {
    +	case owned:
    +		return
    +	case ownerUnknown:
    +		left.Cleanup = errors.New("ownership unknown: the journal does not record which harness the latest resume ran on")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		// Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may
    +		// still be snapshotting the compute, or may fail before it suspends it, and only the
    +		// Fork's SUSPEND record would show which.
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// ownership is what a journal says about compute this Placer's backend returned.
    +type ownership int
    +
    +const (
    +	// unowned: the journal's compute state (ownershipEvent) is not LIVE, or LIVE is other compute.
    +	unowned ownership = iota
    +	// owned: LIVE is this compute.
    +	owned
    +	// ownerUnknown: LIVE after a resume that may have run on this Placer or on another one, and the
    +	// journal does not say which.
    +	ownerUnknown
    +)
    +
    +// ownership reports whether recs leave the session's compute LIVE, by the guard's own fold
    +// (ownershipState, which unlike the stored SES-8 compute_state skips a CloseApproval receipt), on
    +// compute this Placer's backend returned:
    +//
    +//   - LIVE must come from this Placer (liveOwner, turnRanHere). After another Placer's turn or
    +//     resume (an ExecRequest.harness override, either way), LIVE is that Placer's compute.
    +//   - The returned instance must not have replaced the one this harness's latest turn, or a fork
    +//     child's FORK marker, recorded (controller.LatestComputeInstance, attributed by ranHere as the
    +//     controller's own check is). The controller refuses such a replacement with
    +//     api.ErrMemoryStateLost before it appends anything, and LIVE is the replaced instance.
    +//
    +// When LIVE comes from a resume that may have run on this Placer or on another one (liveOwner names
    +// harnesses on both sides), it is ownerUnknown: releasing could take compute the journal owns, and
    +// keeping it could leak it.
    +func (g *computeGuard) ownership(recs []eventlog.Record) ownership {
    +	if ownershipState(recs) != api.ComputeLive {
    +		return unowned
    +	}
    +	if g.inc.ComputeInstance != "" {
    +		if last, _ := controller.LatestComputeInstance(recs, g.p.ranHere); last != "" && last != g.inc.ComputeInstance {
    +			return unowned
    +		}
    +	}
    +	recorded, others := liveOwner(recs)
    +	here := g.turnRanHere(recorded)
    +	for name := range others {
    +		if g.turnRanHere(name) != here {
    +			return ownerUnknown
    +		}
    +	}
    +	if here {
    +		return owned
    +	}
    +	return unowned
    +}
    +
    +// ownershipEvent is computestate.Event for deciding who owns compute, except that a CloseApproval
    +// receipt (a TOOL_RESULT closing an approval gate with NOT_EXECUTED or OUTCOME_UNKNOWN) moves
    +// nothing. The host writes that receipt without a harness, an executor or compute (APR-18): the
    +// controller rewrites either code from an executor to EXECUTOR_ERROR and harnesswire refuses it
    +// from a harness, so in a verified journal it proves no compute ran. SES-8 still counts it as
    +// LIVE, but after a park's SUSPEND it would make compute a later Resume or Exec allocated look
    +// owned by the closed turn, and a failed operation would neither release nor report it.
    +func ownershipEvent(ev api.Event) (api.ComputeState, bool) {
    +	r := ev.Result
    +	if ev.Kind == api.EventToolResult && r != nil && r.IsError && r.ApprovalDecisionSeq > 0 &&
    +		(r.Code == api.ToolResultCodeNotExecuted || r.Code == api.ToolResultCodeOutcomeUnknown) {
    +		return api.ComputeNone, false
    +	}
    +	return computestate.Event(ev)
    +}
    +
    +// ownershipState folds recs from NONE as computestate.Of does, through ownershipEvent.
    +func ownershipState(recs []eventlog.Record) api.ComputeState {
    +	state := api.ComputeNone
    +	for _, r := range recs {
    +		if s, moves := ownershipEvent(r.Event); moves {
    +			state = s
    +		}
    +	}
    +	return state
    +}
    +
    +// turnRanHere reports whether a turn recorded under the harness name recorded ran on this Placer.
    +// Unlike ranHere, which counts every turn it cannot attribute because its callers can only refuse
    +// on an overcount, it counts only turns it can: a wrong yes here leaves compute neither released
    +// nor reported. A standalone Placer has one backend, so every turn ran on it. In a Registry, an
    +// empty name is a turn on the session's own harness (api.ExecutionStart.Harness), which is this
    +// Placer unless the operation is an override; any other name counts when it resolves to this
    +// Placer, so an alias does and a name this host does not serve does not.
    +func (g *computeGuard) turnRanHere(recorded string) bool {
    +	if g.p.registry == nil {
    +		return true
    +	}
    +	if recorded == "" {
    +		return !g.override
    +	}
    +	q, ok := g.p.registry.lookup(recorded)
    +	return ok && q == g.p
    +}
    +
    +// liveOwner returns the harness name recorded for whatever left recs LIVE (ownershipEvent), read
    +// through latestTurnHarness ("" is the session's own harness), and the names of the other harnesses
    +// that may have run it instead, which the journal cannot rule out (none for a turn record).
    +//
    +// A turn record is attributed to its turn, across a FORK marker when a fork child re-drove an
    +// inherited turn. A LIFECYCLE_RESUME is placement's, appended after controller.Resume, and the
    +// journal does not record the harness it ran on. Registry.Resume picks it before any fence: the
    +// recorded harness of the pending turn, or the session's own harness with nothing pending. A
    +// Resume that finds a pending turn re-drives it and appends at least its END first, but a Resume
    +// whose pick went stale runs anyway: two Resume calls without expected_last_seq on hosts sharing
    +// the journal can both pick harness B for a turn pending on B; the first appends END and RESUME,
    +// and the second finds nothing pending (controller.Resume does not check the harness then),
    +// restores on B and appends a second RESUME, after which any record (a SUSPEND, an approval
    +// decision, a later turn on another harness) may come before it. So a RESUME ran on the session's
    +// own harness or on the harness of any turn that was ever pending in this journal: every turn with
    +// a record after the latest FORK marker before the RESUME, or every turn when there is none. A
    +// fork child's journal starts at its FORK marker; the turns before it completed in the parent,
    +// except an inherited one that the child re-drove, which then has a record after the marker.
    +func liveOwner(recs []eventlog.Record) (recorded string, others iter.Seq[string]) {
    +	for i := len(recs) - 1; i >= 0; i-- {
    +		ev := recs[i].Event
    +		if _, moves := ownershipEvent(ev); !moves {
    +			continue
    +		}
    +		if ev.Kind != api.EventLifecycle {
    +			return latestTurnHarness(recs[:i+1]), noHarnesses
    +		}
    +		return "", resumeCandidates(recs[:i])
    +	}
    +	return "", noHarnesses
    +}
    +
    +func noHarnesses(func(string) bool) {}
    +
    +// resumeCandidates yields the recorded harness name (latestTurnHarness's form) of every turn with a
    +// record in recs after the latest FORK marker, or anywhere in recs when there is none: the turns a
    +// RESUME that follows recs may have re-driven or picked. It skips a name the turn before already
    +// yielded.
    +func resumeCandidates(recs []eventlog.Record) iter.Seq[string] {
    +	return func(yield func(string) bool) {
    +		start := 0
    +		for i := len(recs) - 1; i >= 0; i-- {
    +			if ev := recs[i].Event; ev.Kind == api.EventLifecycle && ev.Lifecycle != nil && ev.Lifecycle.Kind == api.LifecycleFork {
    +				start = i + 1
    +				break
    +			}
    +		}
    +		// A turn record after the marker that no EXECUTION_START precedes is the inherited turn's.
    +		current := latestTurnHarness(recs[:start])
    +		last, yielded := "", false
    +		for _, r := range recs[start:] {
    +			ev := r.Event
    +			switch {
    +			case ev.Kind == api.EventExecutionStart:
    +				current = ""
    +				if ev.ExecutionStart != nil {
    +					current = ev.ExecutionStart.Harness
    +				}
    +			case ev.ExecutionID == "" && isLegacyTurnEvent(ev.Kind):
    +				current = ""
    +			}
    +			if isTurnRecord(ev) && (!yielded || current != last) {

    For interleaved executions such as START(x1, A), START(x2, B), FORK, END(x1), RESUME, this scan attributes x1's post-FORK record to B and omits A from the possible owners, allowing release instead of reporting uncertain ownership. The same attribution error in liveOwner at line 335 can treat B's compute as owned after END(x1), suppressing both release and reporting; controller/harness_identity_test.go:56–63 already covers interleaved execution records. Resolve each record through its matching EXECUTION_START by ExecutionID, preserving that mapping across FORK and the fallback for legacy records, and add regression coverage for both lookups.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 08, 2026 21:41 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    Interleaved execution records can be attributed to the wrong owner across FORK, allowing unsafe release or suppressing release and uncertainty reporting, so both ownership lookups need ExecutionID-based matching and regression coverage.

    <details open>
    <summary><strong>2 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Resolve interleaved execution records by ExecutionID · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Authorization sanitization drops the compute-still-running warning

  • </details>

    <details>
    <summary><strong>1 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Ignore host-only receipts when deriving compute ownership

  • </details>

    <sub>Review effort: Balanced</sub>

    aramase aramase commented on code on Nov 08, 2026 22:12 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,408 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"iter"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal, read after the failure, does
    +// not show the operation's harness owning that compute (the guard's own fold of the records, which
    +// unlike the stored SES-8 compute_state skips a CloseApproval receipt). The host never calls Stop
    +// on this path (RT-7) and did not release the compute either: the backend has no
    +// api.CleanupRuntime, the release failed, the journal could not be read or verified (hash chain) or
    +// is shorter than it was before the operation, the journal does not record whether the latest
    +// resume ran on this harness, or another owner (a writer that committed during the operation, a
    +// checkpoint, a newer fence, a deletion) may hold it, so a release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute and
    +// settles it in a defer registered before the allocation, so every early return after the effect
    +// passes through settle. handoffPark disarms it once its SUSPEND commits the compute to the
    +// approval gate; a handoff that fails before then leaves it armed.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner; a journal that ends before it
    +	// lost records.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, is shorter than before the operation, or does not record which harness the
    +// latest resume ran on), is reported without a release; and unowned compute is released through
    +// api.CleanupRuntime or, failing that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// The chain verifies from genesis only, so a journal that lost its tail still verifies, and its
    +	// prefix can read LIVE on this harness (a COLD session's final SUSPEND lost). headBefore shows
    +	// the loss.
    +	if n := len(recs); g.headBefore > 0 && (n == 0 || recs[n-1].Seq < g.headBefore) {
    +		left.Cleanup = errors.New("ownership unknown: the journal is shorter than it was before the operation")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	// The journal as read now decides: the runtime attached compute the journal owned and nothing
    +	// committed since changed that, or the controller journaled this turn on it. Ownership before
    +	// the operation does not count once a record committed during it says otherwise: after another
    +	// host's SUSPEND the runtime may have woken compute the journal no longer owns, which the moved
    +	// case below reports.
    +	switch g.ownership(recs) {
    +	case owned:
    +		return
    +	case ownerUnknown:
    +		left.Cleanup = errors.New("ownership unknown: the journal does not record which harness the latest resume ran on")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		// Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may
    +		// still be snapshotting the compute, or may fail before it suspends it, and only the
    +		// Fork's SUSPEND record would show which.
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// ownership is what a journal says about compute this Placer's backend returned.
    +type ownership int
    +
    +const (
    +	// unowned: the journal's compute state (ownershipEvent) is not LIVE, or LIVE is other compute.
    +	unowned ownership = iota
    +	// owned: LIVE is this compute.
    +	owned
    +	// ownerUnknown: LIVE after a resume that may have run on this Placer or on another one, and the
    +	// journal does not say which.
    +	ownerUnknown
    +)
    +
    +// ownership reports whether recs leave the session's compute LIVE, by the guard's own fold
    +// (ownershipState, which unlike the stored SES-8 compute_state skips a CloseApproval receipt), on
    +// compute this Placer's backend returned:
    +//
    +//   - LIVE must come from this Placer (liveOwner, turnRanHere). After another Placer's turn or
    +//     resume (an ExecRequest.harness override, either way), LIVE is that Placer's compute.
    +//   - The returned instance must not have replaced the one this harness's latest turn, or a fork
    +//     child's FORK marker, recorded (controller.LatestComputeInstance, attributed by ranHere as the
    +//     controller's own check is). The controller refuses such a replacement with
    +//     api.ErrMemoryStateLost before it appends anything, and LIVE is the replaced instance.
    +//
    +// When LIVE comes from a resume that may have run on this Placer or on another one (liveOwner names
    +// harnesses on both sides), it is ownerUnknown: releasing could take compute the journal owns, and
    +// keeping it could leak it.
    +func (g *computeGuard) ownership(recs []eventlog.Record) ownership {
    +	if ownershipState(recs) != api.ComputeLive {
    +		return unowned
    +	}
    +	if g.inc.ComputeInstance != "" {
    +		if last, _ := controller.LatestComputeInstance(recs, g.p.ranHere); last != "" && last != g.inc.ComputeInstance {
    +			return unowned
    +		}
    +	}
    +	recorded, others := liveOwner(recs)
    +	here := g.turnRanHere(recorded)
    +	for name := range others {
    +		if g.turnRanHere(name) != here {
    +			return ownerUnknown
    +		}
    +	}
    +	if here {
    +		return owned
    +	}
    +	return unowned
    +}
    +
    +// ownershipEvent is computestate.Event for deciding who owns compute, except that a CloseApproval
    +// receipt (a TOOL_RESULT closing an approval gate with NOT_EXECUTED or OUTCOME_UNKNOWN) moves
    +// nothing. The host writes that receipt without a harness, an executor or compute (APR-18): the
    +// controller rewrites either code from an executor to EXECUTOR_ERROR and harnesswire refuses it
    +// from a harness, so in a verified journal it proves no compute ran. SES-8 still counts it as
    +// LIVE, but after a park's SUSPEND it would make compute a later Resume or Exec allocated look
    +// owned by the closed turn, and a failed operation would neither release nor report it.
    +func ownershipEvent(ev api.Event) (api.ComputeState, bool) {
    +	r := ev.Result
    +	if ev.Kind == api.EventToolResult && r != nil && r.IsError && r.ApprovalDecisionSeq > 0 &&
    +		(r.Code == api.ToolResultCodeNotExecuted || r.Code == api.ToolResultCodeOutcomeUnknown) {
    +		return api.ComputeNone, false
    +	}
    +	return computestate.Event(ev)
    +}
    +
    +// ownershipState folds recs from NONE as computestate.Of does, through ownershipEvent.
    +func ownershipState(recs []eventlog.Record) api.ComputeState {
    +	state := api.ComputeNone
    +	for _, r := range recs {
    +		if s, moves := ownershipEvent(r.Event); moves {
    +			state = s
    +		}
    +	}
    +	return state
    +}
    +
    +// turnRanHere reports whether a turn recorded under the harness name recorded ran on this Placer.
    +// Unlike ranHere, which counts every turn it cannot attribute because its callers can only refuse
    +// on an overcount, it counts only turns it can: a wrong yes here leaves compute neither released
    +// nor reported. A standalone Placer has one backend, so every turn ran on it. In a Registry, an
    +// empty name is a turn on the session's own harness (api.ExecutionStart.Harness), which is this
    +// Placer unless the operation is an override; any other name counts when it resolves to this
    +// Placer, so an alias does and a name this host does not serve does not.
    +func (g *computeGuard) turnRanHere(recorded string) bool {
    +	if g.p.registry == nil {
    +		return true
    +	}
    +	if recorded == "" {
    +		return !g.override
    +	}
    +	q, ok := g.p.registry.lookup(recorded)
    +	return ok && q == g.p
    +}
    +
    +// liveOwner returns the harness name recorded for whatever left recs LIVE (ownershipEvent), read
    +// through latestTurnHarness ("" is the session's own harness), and the names of the other harnesses
    +// that may have run it instead, which the journal cannot rule out (none for a turn record).
    +//
    +// A turn record is attributed to its turn, across a FORK marker when a fork child re-drove an
    +// inherited turn. A LIFECYCLE_RESUME is placement's, appended after controller.Resume, and the
    +// journal does not record the harness it ran on. Registry.Resume picks it before any fence: the
    +// recorded harness of the pending turn, or the session's own harness with nothing pending. A
    +// Resume that finds a pending turn re-drives it and appends at least its END first, but a Resume
    +// whose pick went stale runs anyway: two Resume calls without expected_last_seq on hosts sharing
    +// the journal can both pick harness B for a turn pending on B; the first appends END and RESUME,
    +// and the second finds nothing pending (controller.Resume does not check the harness then),
    +// restores on B and appends a second RESUME, after which any record (a SUSPEND, an approval
    +// decision, a later turn on another harness) may come before it. So a RESUME ran on the session's
    +// own harness or on the harness of any turn that was ever pending in this journal: every turn with
    +// a record after the latest FORK marker before the RESUME, or every turn when there is none. A
    +// fork child's journal starts at its FORK marker; the turns before it completed in the parent,
    +// except an inherited one that the child re-drove, which then has a record after the marker.
    +func liveOwner(recs []eventlog.Record) (recorded string, others iter.Seq[string]) {
    +	for i := len(recs) - 1; i >= 0; i-- {
    +		ev := recs[i].Event
    +		if _, moves := ownershipEvent(ev); !moves {
    +			continue
    +		}
    +		if ev.Kind != api.EventLifecycle {
    +			return latestTurnHarness(recs[:i+1]), noHarnesses
    +		}
    +		return "", resumeCandidates(recs[:i])
    +	}
    +	return "", noHarnesses
    +}
    +
    +func noHarnesses(func(string) bool) {}
    +
    +// resumeCandidates yields the recorded harness name (latestTurnHarness's form) of every turn with a
    +// record in recs after the latest FORK marker, or anywhere in recs when there is none: the turns a
    +// RESUME that follows recs may have re-driven or picked. It skips a name the turn before already
    +// yielded.
    +func resumeCandidates(recs []eventlog.Record) iter.Seq[string] {
    +	return func(yield func(string) bool) {
    +		start := 0
    +		for i := len(recs) - 1; i >= 0; i-- {
    +			if ev := recs[i].Event; ev.Kind == api.EventLifecycle && ev.Lifecycle != nil && ev.Lifecycle.Kind == api.LifecycleFork {
    +				start = i + 1
    +				break
    +			}
    +		}
    +		// A turn record after the marker that no EXECUTION_START precedes is the inherited turn's.
    +		current := latestTurnHarness(recs[:start])
    +		last, yielded := "", false
    +		for _, r := range recs[start:] {
    +			ev := r.Event
    +			switch {
    +			case ev.Kind == api.EventExecutionStart:
    +				current = ""
    +				if ev.ExecutionStart != nil {
    +					current = ev.ExecutionStart.Harness
    +				}
    +			case ev.ExecutionID == "" && isLegacyTurnEvent(ev.Kind):
    +				current = ""
    +			}
    +			if isTurnRecord(ev) && (!yielded || current != last) {

    Good catch, fixed. liveOwner and resumeCandidates now resolve each turn record to the EXECUTION_START with its ExecutionID, including an inherited turn's START before a FORK marker, and a record with no ExecutionID (or none with a START) still counts as the session's own harness. With A as the session's own harness your exact sequence over-reported rather than released, but with a third harness it released compute the journal owned, and the new TestLiveOwnerByExecutionID and interleaved TestComputeGuardAcrossPlacers rows cover both.

    Copilot Copilot commented on code on Nov 08, 2026 22:18 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,427 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"iter"
    +	"slices"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal, read after the failure, does
    +// not show the operation's harness owning that compute (the guard's own fold of the records, which
    +// unlike the stored SES-8 compute_state skips a CloseApproval receipt). The host never calls Stop
    +// on this path (RT-7) and did not release the compute either: the backend has no
    +// api.CleanupRuntime, the release failed, the journal could not be read or verified (hash chain) or
    +// is shorter than it was before the operation, the journal does not record whether the latest
    +// resume ran on this harness, or another owner (a writer that committed during the operation, a
    +// checkpoint, a newer fence, a deletion) may hold it, so a release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute and
    +// settles it in a defer registered before the allocation, so every early return after the effect
    +// passes through settle. handoffPark disarms it once its SUSPEND commits the compute to the
    +// approval gate; a handoff that fails before then leaves it armed.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner; a journal that ends before it
    +	// lost records.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, is shorter than before the operation, or does not record which harness the
    +// latest resume ran on), is reported without a release; and unowned compute is released through
    +// api.CleanupRuntime or, failing that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// The chain verifies from genesis only, so a journal that lost its tail still verifies, and its
    +	// prefix can read LIVE on this harness (a COLD session's final SUSPEND lost). headBefore shows
    +	// the loss.
    +	if n := len(recs); g.headBefore > 0 && (n == 0 || recs[n-1].Seq < g.headBefore) {
    +		left.Cleanup = errors.New("ownership unknown: the journal is shorter than it was before the operation")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	// The journal as read now decides: the runtime attached compute the journal owned and nothing
    +	// committed since changed that, or the controller journaled this turn on it. Ownership before
    +	// the operation does not count once a record committed during it says otherwise: after another
    +	// host's SUSPEND the runtime may have woken compute the journal no longer owns, which the moved
    +	// case below reports.
    +	switch g.ownership(recs) {
    +	case owned:
    +		return
    +	case ownerUnknown:
    +		left.Cleanup = errors.New("ownership unknown: the journal does not record which harness the latest resume ran on")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		// Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may
    +		// still be snapshotting the compute, or may fail before it suspends it, and only the
    +		// Fork's SUSPEND record would show which.
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// ownership is what a journal says about compute this Placer's backend returned.
    +type ownership int
    +
    +const (
    +	// unowned: the journal's compute state (ownershipEvent) is not LIVE, or LIVE is other compute.
    +	unowned ownership = iota
    +	// owned: LIVE is this compute.
    +	owned
    +	// ownerUnknown: LIVE after a resume that may have run on this Placer or on another one, and the
    +	// journal does not say which.
    +	ownerUnknown
    +)
    +
    +// ownership reports whether recs leave the session's compute LIVE, by the guard's own fold
    +// (ownershipState, which unlike the stored SES-8 compute_state skips a CloseApproval receipt), on
    +// compute this Placer's backend returned:
    +//
    +//   - LIVE must come from this Placer (liveOwner, turnRanHere). After another Placer's turn or
    +//     resume (an ExecRequest.harness override, either way), LIVE is that Placer's compute.
    +//   - The returned instance must not have replaced the one this harness's latest turn, or a fork
    +//     child's FORK marker, recorded (controller.LatestComputeInstance, attributed by ranHere as the
    +//     controller's own check is). The controller refuses such a replacement with
    +//     api.ErrMemoryStateLost before it appends anything, and LIVE is the replaced instance.
    +//
    +// When LIVE comes from a resume that may have run on this Placer or on another one (liveOwner names
    +// harnesses on both sides), it is ownerUnknown: releasing could take compute the journal owns, and
    +// keeping it could leak it.
    +func (g *computeGuard) ownership(recs []eventlog.Record) ownership {
    +	if ownershipState(recs) != api.ComputeLive {
    +		return unowned
    +	}
    +	if g.inc.ComputeInstance != "" {
    +		if last, _ := controller.LatestComputeInstance(recs, g.p.ranHere); last != "" && last != g.inc.ComputeInstance {
    +			return unowned
    +		}
    +	}
    +	recorded, others := liveOwner(recs)
    +	here := g.turnRanHere(recorded)
    +	for name := range others {
    +		if g.turnRanHere(name) != here {
    +			return ownerUnknown
    +		}
    +	}
    +	if here {
    +		return owned
    +	}
    +	return unowned
    +}
    +
    +// ownershipEvent is computestate.Event for deciding who owns compute, except that a CloseApproval
    +// receipt (a TOOL_RESULT closing an approval gate with NOT_EXECUTED or OUTCOME_UNKNOWN) moves
    +// nothing. The host writes that receipt without a harness, an executor or compute (APR-18): the
    +// controller rewrites either code from an executor to EXECUTOR_ERROR and harnesswire refuses it
    +// from a harness, so in a verified journal it proves no compute ran. SES-8 still counts it as
    +// LIVE, but after a park's SUSPEND it would make compute a later Resume or Exec allocated look
    +// owned by the closed turn, and a failed operation would neither release nor report it.
    +func ownershipEvent(ev api.Event) (api.ComputeState, bool) {
    +	r := ev.Result
    +	if ev.Kind == api.EventToolResult && r != nil && r.IsError && r.ApprovalDecisionSeq > 0 &&
    +		(r.Code == api.ToolResultCodeNotExecuted || r.Code == api.ToolResultCodeOutcomeUnknown) {
    +		return api.ComputeNone, false
    +	}
    +	return computestate.Event(ev)
    +}
    +
    +// ownershipState folds recs from NONE as computestate.Of does, through ownershipEvent.
    +func ownershipState(recs []eventlog.Record) api.ComputeState {
    +	state := api.ComputeNone
    +	for _, r := range recs {
    +		if s, moves := ownershipEvent(r.Event); moves {
    +			state = s
    +		}
    +	}
    +	return state
    +}
    +
    +// turnRanHere reports whether a turn recorded under the harness name recorded ran on this Placer.
    +// Unlike ranHere, which counts every turn it cannot attribute because its callers can only refuse
    +// on an overcount, it counts only turns it can: a wrong yes here leaves compute neither released
    +// nor reported. A standalone Placer has one backend, so every turn ran on it. In a Registry, an
    +// empty name is a turn on the session's own harness (api.ExecutionStart.Harness), which is this
    +// Placer unless the operation is an override; any other name counts when it resolves to this
    +// Placer, so an alias does and a name this host does not serve does not.
    +func (g *computeGuard) turnRanHere(recorded string) bool {
    +	if g.p.registry == nil {
    +		return true
    +	}
    +	if recorded == "" {
    +		return !g.override
    +	}
    +	q, ok := g.p.registry.lookup(recorded)
    +	return ok && q == g.p
    +}
    +
    +// liveOwner returns the harness name recorded for whatever left recs LIVE (ownershipEvent), read
    +// through turnHarness ("" is the session's own harness), and the names of the other harnesses that
    +// may have run it instead, which the journal cannot rule out (none for a turn record).
    +//
    +// A turn record is attributed to the turn its ExecutionID names (turnHarness), not to the latest
    +// EXECUTION_START before it: executions can interleave (controller.ResumeInvocation selects the
    +// last one first seen, with an earlier one's records after it), and a fork child that re-drove an
    +// inherited turn writes that turn's records after its FORK marker, under the START its parent
    +// wrote. A LIFECYCLE_RESUME is placement's, appended after controller.Resume, and the journal does
    +// not record the harness it ran on. Registry.Resume picks it before any fence: the recorded harness
    +// of the pending turn, or the session's own harness with nothing pending. A Resume that finds a
    +// pending turn re-drives it and appends at least its END first, but a Resume whose pick went stale
    +// runs anyway: two Resume calls without expected_last_seq on hosts sharing the journal can both
    +// pick harness B for a turn pending on B; the first appends END and RESUME, and the second finds
    +// nothing pending (controller.Resume does not check the harness then), restores on B and appends a
    +// second RESUME, after which any record (a SUSPEND, an approval decision, a later turn on another
    +// harness) may come before it. So a RESUME ran on the session's own harness or on the harness of
    +// any turn that was ever pending in this journal: every turn with a record after the latest FORK
    +// marker before the RESUME, or every turn when there is none. A fork child's journal starts at its
    +// FORK marker; the turns before it completed in the parent, except an inherited one that the child
    +// re-drove, which then has a record after the marker.
    +func liveOwner(recs []eventlog.Record) (recorded string, others iter.Seq[string]) {
    +	for i := len(recs) - 1; i >= 0; i-- {
    +		ev := recs[i].Event
    +		if _, moves := ownershipEvent(ev); !moves {
    +			continue
    +		}
    +		if ev.Kind != api.EventLifecycle {
    +			return turnHarness(executionHarnesses(recs[:i+1]), ev), noHarnesses
    +		}
    +		return "", resumeCandidates(recs[:i])
    +	}
    +	return "", noHarnesses
    +}
    +
    +func noHarnesses(func(string) bool) {}
    +
    +// resumeCandidates yields the recorded harness name (turnHarness) of every turn with a record in
    +// recs after the latest FORK marker, or anywhere in recs when there is none: the turns a RESUME
    +// that follows recs may have re-driven or picked. It yields each name once.
    +func resumeCandidates(recs []eventlog.Record) iter.Seq[string] {
    +	return func(yield func(string) bool) {
    +		start := 0
    +		for i := len(recs) - 1; i >= 0; i-- {
    +			if ev := recs[i].Event; ev.Kind == api.EventLifecycle && ev.Lifecycle != nil && ev.Lifecycle.Kind == api.LifecycleFork {
    +				start = i + 1
    +				break
    +			}
    +		}
    +		// The whole of recs, so an inherited turn re-driven after the marker resolves to the START
    +		// its parent wrote before it.
    +		harnesses := executionHarnesses(recs)
    +		var yielded []string
    +		for _, r := range recs[start:] {
    +			if !isTurnRecord(r.Event) {
    +				continue
    +			}
    +			name := turnHarness(harnesses, r.Event)
    +			if slices.Contains(yielded, name) {
    +				continue
    +			}
    +			if !yield(name) {
    +				return
    +			}
    +			yielded = append(yielded, name)
    +		}
    +	}
    +}
    +
    +// isTurnRecord reports whether ev is a record a turn wrote: one that implies LIVE compute
    +// (computestate.Event) other than a lifecycle marker. It counts a CloseApproval receipt, which
    +// ownershipEvent does not: here a record can only add a candidate harness, which moves the guard
    +// toward reporting, never toward keeping compute as the journal's.
    +func isTurnRecord(ev api.Event) bool {
    +	_, moves := computestate.Event(ev)
    +	return moves && ev.Kind != api.EventLifecycle
    +}
    +
    +// executionHarnesses maps each ExecutionID in recs to the harness name its EXECUTION_START
    +// recorded ("" for one with no payload). The first START of an ID counts, as it is the only one
    +// controller replay accepts.
    +func executionHarnesses(recs []eventlog.Record) map[string]string {
    +	harnesses := make(map[string]string)
    +	for _, r := range recs {
    +		ev := r.Event
    +		if ev.Kind != api.EventExecutionStart || ev.ExecutionID == "" {
    +			continue
    +		}
    +		if _, seen := harnesses[ev.ExecutionID]; seen {
    +			continue
    +		}
    +		name := ""
    +		if ev.ExecutionStart != nil {
    +			name = ev.ExecutionStart.Harness
    +		}
    +		harnesses[ev.ExecutionID] = name
    +	}
    +	return harnesses
    +}
    +
    +// turnHarness returns the harness name recorded on the EXECUTION_START of the turn that wrote ev,
    +// found by ev's ExecutionID in harnesses (executionHarnesses). A legacy record (no ExecutionID) and
    +// one whose ExecutionID has no EXECUTION_START (an older writer's turn) return "": both ran on the
    +// session's own harness, as a session with no recorded turn does (Registry.Resume runs one with no
    +// pending turn there too). An EXECUTION_START names its own harness.
    +func turnHarness(harnesses map[string]string, ev api.Event) string {
    +	switch {
    +	case ev.Kind == api.EventExecutionStart:
    +		if ev.ExecutionStart == nil {
    +			return ""
    +		}
    +		return ev.ExecutionStart.Harness

    For a journal ending in START(x1, A), START(x1, B), this branch attributes LIVE compute to B even though executionHarnesses retains A and the controller rejects the duplicate start. If an override Exec on B allocates compute and then fails confirmation or dialing, the guard skips both release and reporting because hash-chain verification does not validate invocation structure. Treat conflicting starts as unknown ownership and add a regression test with the duplicate START at the journal tail.

    Copilot Copilot commented on code on Nov 08, 2026 22:18 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,427 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"iter"
    +	"slices"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal, read after the failure, does
    +// not show the operation's harness owning that compute (the guard's own fold of the records, which
    +// unlike the stored SES-8 compute_state skips a CloseApproval receipt). The host never calls Stop
    +// on this path (RT-7) and did not release the compute either: the backend has no
    +// api.CleanupRuntime, the release failed, the journal could not be read or verified (hash chain) or
    +// is shorter than it was before the operation, the journal does not record whether the latest
    +// resume ran on this harness, or another owner (a writer that committed during the operation, a
    +// checkpoint, a newer fence, a deletion) may hold it, so a release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute and
    +// settles it in a defer registered before the allocation, so every early return after the effect
    +// passes through settle. handoffPark disarms it once its SUSPEND commits the compute to the
    +// approval gate; a handoff that fails before then leaves it armed.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner; a journal that ends before it
    +	// lost records.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, is shorter than before the operation, or does not record which harness the
    +// latest resume ran on), is reported without a release; and unowned compute is released through
    +// api.CleanupRuntime or, failing that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// The chain verifies from genesis only, so a journal that lost its tail still verifies, and its
    +	// prefix can read LIVE on this harness (a COLD session's final SUSPEND lost). headBefore shows
    +	// the loss.
    +	if n := len(recs); g.headBefore > 0 && (n == 0 || recs[n-1].Seq < g.headBefore) {
    +		left.Cleanup = errors.New("ownership unknown: the journal is shorter than it was before the operation")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	// The journal as read now decides: the runtime attached compute the journal owned and nothing
    +	// committed since changed that, or the controller journaled this turn on it. Ownership before
    +	// the operation does not count once a record committed during it says otherwise: after another
    +	// host's SUSPEND the runtime may have woken compute the journal no longer owns, which the moved
    +	// case below reports.
    +	switch g.ownership(recs) {
    +	case owned:
    +		return
    +	case ownerUnknown:
    +		left.Cleanup = errors.New("ownership unknown: the journal does not record which harness the latest resume ran on")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		// Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may
    +		// still be snapshotting the compute, or may fail before it suspends it, and only the
    +		// Fork's SUSPEND record would show which.
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,

    This warning drops left.ComputeInstance, logging only the reusable incarnation ID. For a runtime that replaces compute under the same ID, operators cannot distinguish which instance the failed call left running—especially when cancellation prevents the client from receiving the error containing its UID. Include the returned compute-instance identity alongside incarnation_id so the host's report identifies the same compute as the error.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 08, 2026 22:18 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    A critical ownership error on duplicate START entries can skip compute release and reporting, and the warning omits the compute-instance identity needed to identify the runtime left running.

    <details open>
    <summary><strong>3 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Treat duplicate journal starts as unknown compute ownership · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Log the compute-instance identity in the failure warning · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Authorization sanitization drops the compute-still-running warning

  • </details>

    <details>
    <summary><strong>1 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Resolve interleaved execution records by ExecutionID

  • </details>

    <sub>Review effort: Balanced</sub>

    aramase aramase commented on code on Nov 09, 2026 00:50 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,427 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"iter"
    +	"slices"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal, read after the failure, does
    +// not show the operation's harness owning that compute (the guard's own fold of the records, which
    +// unlike the stored SES-8 compute_state skips a CloseApproval receipt). The host never calls Stop
    +// on this path (RT-7) and did not release the compute either: the backend has no
    +// api.CleanupRuntime, the release failed, the journal could not be read or verified (hash chain) or
    +// is shorter than it was before the operation, the journal does not record whether the latest
    +// resume ran on this harness, or another owner (a writer that committed during the operation, a
    +// checkpoint, a newer fence, a deletion) may hold it, so a release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute and
    +// settles it in a defer registered before the allocation, so every early return after the effect
    +// passes through settle. handoffPark disarms it once its SUSPEND commits the compute to the
    +// approval gate; a handoff that fails before then leaves it armed.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner; a journal that ends before it
    +	// lost records.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, is shorter than before the operation, or does not record which harness the
    +// latest resume ran on), is reported without a release; and unowned compute is released through
    +// api.CleanupRuntime or, failing that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// The chain verifies from genesis only, so a journal that lost its tail still verifies, and its
    +	// prefix can read LIVE on this harness (a COLD session's final SUSPEND lost). headBefore shows
    +	// the loss.
    +	if n := len(recs); g.headBefore > 0 && (n == 0 || recs[n-1].Seq < g.headBefore) {
    +		left.Cleanup = errors.New("ownership unknown: the journal is shorter than it was before the operation")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	// The journal as read now decides: the runtime attached compute the journal owned and nothing
    +	// committed since changed that, or the controller journaled this turn on it. Ownership before
    +	// the operation does not count once a record committed during it says otherwise: after another
    +	// host's SUSPEND the runtime may have woken compute the journal no longer owns, which the moved
    +	// case below reports.
    +	switch g.ownership(recs) {
    +	case owned:
    +		return
    +	case ownerUnknown:
    +		left.Cleanup = errors.New("ownership unknown: the journal does not record which harness the latest resume ran on")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		// Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may
    +		// still be snapshotting the compute, or may fail before it suspends it, and only the
    +		// Fork's SUSPEND record would show which.
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// ownership is what a journal says about compute this Placer's backend returned.
    +type ownership int
    +
    +const (
    +	// unowned: the journal's compute state (ownershipEvent) is not LIVE, or LIVE is other compute.
    +	unowned ownership = iota
    +	// owned: LIVE is this compute.
    +	owned
    +	// ownerUnknown: LIVE after a resume that may have run on this Placer or on another one, and the
    +	// journal does not say which.
    +	ownerUnknown
    +)
    +
    +// ownership reports whether recs leave the session's compute LIVE, by the guard's own fold
    +// (ownershipState, which unlike the stored SES-8 compute_state skips a CloseApproval receipt), on
    +// compute this Placer's backend returned:
    +//
    +//   - LIVE must come from this Placer (liveOwner, turnRanHere). After another Placer's turn or
    +//     resume (an ExecRequest.harness override, either way), LIVE is that Placer's compute.
    +//   - The returned instance must not have replaced the one this harness's latest turn, or a fork
    +//     child's FORK marker, recorded (controller.LatestComputeInstance, attributed by ranHere as the
    +//     controller's own check is). The controller refuses such a replacement with
    +//     api.ErrMemoryStateLost before it appends anything, and LIVE is the replaced instance.
    +//
    +// When LIVE comes from a resume that may have run on this Placer or on another one (liveOwner names
    +// harnesses on both sides), it is ownerUnknown: releasing could take compute the journal owns, and
    +// keeping it could leak it.
    +func (g *computeGuard) ownership(recs []eventlog.Record) ownership {
    +	if ownershipState(recs) != api.ComputeLive {
    +		return unowned
    +	}
    +	if g.inc.ComputeInstance != "" {
    +		if last, _ := controller.LatestComputeInstance(recs, g.p.ranHere); last != "" && last != g.inc.ComputeInstance {
    +			return unowned
    +		}
    +	}
    +	recorded, others := liveOwner(recs)
    +	here := g.turnRanHere(recorded)
    +	for name := range others {
    +		if g.turnRanHere(name) != here {
    +			return ownerUnknown
    +		}
    +	}
    +	if here {
    +		return owned
    +	}
    +	return unowned
    +}
    +
    +// ownershipEvent is computestate.Event for deciding who owns compute, except that a CloseApproval
    +// receipt (a TOOL_RESULT closing an approval gate with NOT_EXECUTED or OUTCOME_UNKNOWN) moves
    +// nothing. The host writes that receipt without a harness, an executor or compute (APR-18): the
    +// controller rewrites either code from an executor to EXECUTOR_ERROR and harnesswire refuses it
    +// from a harness, so in a verified journal it proves no compute ran. SES-8 still counts it as
    +// LIVE, but after a park's SUSPEND it would make compute a later Resume or Exec allocated look
    +// owned by the closed turn, and a failed operation would neither release nor report it.
    +func ownershipEvent(ev api.Event) (api.ComputeState, bool) {
    +	r := ev.Result
    +	if ev.Kind == api.EventToolResult && r != nil && r.IsError && r.ApprovalDecisionSeq > 0 &&
    +		(r.Code == api.ToolResultCodeNotExecuted || r.Code == api.ToolResultCodeOutcomeUnknown) {
    +		return api.ComputeNone, false
    +	}
    +	return computestate.Event(ev)
    +}
    +
    +// ownershipState folds recs from NONE as computestate.Of does, through ownershipEvent.
    +func ownershipState(recs []eventlog.Record) api.ComputeState {
    +	state := api.ComputeNone
    +	for _, r := range recs {
    +		if s, moves := ownershipEvent(r.Event); moves {
    +			state = s
    +		}
    +	}
    +	return state
    +}
    +
    +// turnRanHere reports whether a turn recorded under the harness name recorded ran on this Placer.
    +// Unlike ranHere, which counts every turn it cannot attribute because its callers can only refuse
    +// on an overcount, it counts only turns it can: a wrong yes here leaves compute neither released
    +// nor reported. A standalone Placer has one backend, so every turn ran on it. In a Registry, an
    +// empty name is a turn on the session's own harness (api.ExecutionStart.Harness), which is this
    +// Placer unless the operation is an override; any other name counts when it resolves to this
    +// Placer, so an alias does and a name this host does not serve does not.
    +func (g *computeGuard) turnRanHere(recorded string) bool {
    +	if g.p.registry == nil {
    +		return true
    +	}
    +	if recorded == "" {
    +		return !g.override
    +	}
    +	q, ok := g.p.registry.lookup(recorded)
    +	return ok && q == g.p
    +}
    +
    +// liveOwner returns the harness name recorded for whatever left recs LIVE (ownershipEvent), read
    +// through turnHarness ("" is the session's own harness), and the names of the other harnesses that
    +// may have run it instead, which the journal cannot rule out (none for a turn record).
    +//
    +// A turn record is attributed to the turn its ExecutionID names (turnHarness), not to the latest
    +// EXECUTION_START before it: executions can interleave (controller.ResumeInvocation selects the
    +// last one first seen, with an earlier one's records after it), and a fork child that re-drove an
    +// inherited turn writes that turn's records after its FORK marker, under the START its parent
    +// wrote. A LIFECYCLE_RESUME is placement's, appended after controller.Resume, and the journal does
    +// not record the harness it ran on. Registry.Resume picks it before any fence: the recorded harness
    +// of the pending turn, or the session's own harness with nothing pending. A Resume that finds a
    +// pending turn re-drives it and appends at least its END first, but a Resume whose pick went stale
    +// runs anyway: two Resume calls without expected_last_seq on hosts sharing the journal can both
    +// pick harness B for a turn pending on B; the first appends END and RESUME, and the second finds
    +// nothing pending (controller.Resume does not check the harness then), restores on B and appends a
    +// second RESUME, after which any record (a SUSPEND, an approval decision, a later turn on another
    +// harness) may come before it. So a RESUME ran on the session's own harness or on the harness of
    +// any turn that was ever pending in this journal: every turn with a record after the latest FORK
    +// marker before the RESUME, or every turn when there is none. A fork child's journal starts at its
    +// FORK marker; the turns before it completed in the parent, except an inherited one that the child
    +// re-drove, which then has a record after the marker.
    +func liveOwner(recs []eventlog.Record) (recorded string, others iter.Seq[string]) {
    +	for i := len(recs) - 1; i >= 0; i-- {
    +		ev := recs[i].Event
    +		if _, moves := ownershipEvent(ev); !moves {
    +			continue
    +		}
    +		if ev.Kind != api.EventLifecycle {
    +			return turnHarness(executionHarnesses(recs[:i+1]), ev), noHarnesses
    +		}
    +		return "", resumeCandidates(recs[:i])
    +	}
    +	return "", noHarnesses
    +}
    +
    +func noHarnesses(func(string) bool) {}
    +
    +// resumeCandidates yields the recorded harness name (turnHarness) of every turn with a record in
    +// recs after the latest FORK marker, or anywhere in recs when there is none: the turns a RESUME
    +// that follows recs may have re-driven or picked. It yields each name once.
    +func resumeCandidates(recs []eventlog.Record) iter.Seq[string] {
    +	return func(yield func(string) bool) {
    +		start := 0
    +		for i := len(recs) - 1; i >= 0; i-- {
    +			if ev := recs[i].Event; ev.Kind == api.EventLifecycle && ev.Lifecycle != nil && ev.Lifecycle.Kind == api.LifecycleFork {
    +				start = i + 1
    +				break
    +			}
    +		}
    +		// The whole of recs, so an inherited turn re-driven after the marker resolves to the START
    +		// its parent wrote before it.
    +		harnesses := executionHarnesses(recs)
    +		var yielded []string
    +		for _, r := range recs[start:] {
    +			if !isTurnRecord(r.Event) {
    +				continue
    +			}
    +			name := turnHarness(harnesses, r.Event)
    +			if slices.Contains(yielded, name) {
    +				continue
    +			}
    +			if !yield(name) {
    +				return
    +			}
    +			yielded = append(yielded, name)
    +		}
    +	}
    +}
    +
    +// isTurnRecord reports whether ev is a record a turn wrote: one that implies LIVE compute
    +// (computestate.Event) other than a lifecycle marker. It counts a CloseApproval receipt, which
    +// ownershipEvent does not: here a record can only add a candidate harness, which moves the guard
    +// toward reporting, never toward keeping compute as the journal's.
    +func isTurnRecord(ev api.Event) bool {
    +	_, moves := computestate.Event(ev)
    +	return moves && ev.Kind != api.EventLifecycle
    +}
    +
    +// executionHarnesses maps each ExecutionID in recs to the harness name its EXECUTION_START
    +// recorded ("" for one with no payload). The first START of an ID counts, as it is the only one
    +// controller replay accepts.
    +func executionHarnesses(recs []eventlog.Record) map[string]string {
    +	harnesses := make(map[string]string)
    +	for _, r := range recs {
    +		ev := r.Event
    +		if ev.Kind != api.EventExecutionStart || ev.ExecutionID == "" {
    +			continue
    +		}
    +		if _, seen := harnesses[ev.ExecutionID]; seen {
    +			continue
    +		}
    +		name := ""
    +		if ev.ExecutionStart != nil {
    +			name = ev.ExecutionStart.Harness
    +		}
    +		harnesses[ev.ExecutionID] = name
    +	}
    +	return harnesses
    +}
    +
    +// turnHarness returns the harness name recorded on the EXECUTION_START of the turn that wrote ev,
    +// found by ev's ExecutionID in harnesses (executionHarnesses). A legacy record (no ExecutionID) and
    +// one whose ExecutionID has no EXECUTION_START (an older writer's turn) return "": both ran on the
    +// session's own harness, as a session with no recorded turn does (Registry.Resume runs one with no
    +// pending turn there too). An EXECUTION_START names its own harness.
    +func turnHarness(harnesses map[string]string, ev api.Event) string {
    +	switch {
    +	case ev.Kind == api.EventExecutionStart:
    +		if ev.ExecutionStart == nil {
    +			return ""
    +		}
    +		return ev.ExecutionStart.Harness

    Confirmed with a regression test: with a journal ending in two EXECUTION_START records for one execution, naming C and then B, an override Exec on B that failed its confirm or dial kept the compute without releasing or reporting it. Fixed in "fix(placement): release or report compute left running after a failed resume or exec". executionHarnesses now also reports whether the journal attributes every turn to one harness. Conflicting STARTs, a START with no ID or no payload, a START after its execution's other records, an ID-less record the controller would reject, or an ID'd record with no START right after an unfinished legacy turn make ownership unknown anywhere in the journal, so the guard reports the compute instead of keeping or releasing it. turnHarness now resolves a START through the same map as every other record. A repeated START naming the same harness still counts as that harness.

    aramase aramase commented on code on Nov 09, 2026 00:50 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,427 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"iter"
    +	"slices"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/controller"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal, read after the failure, does
    +// not show the operation's harness owning that compute (the guard's own fold of the records, which
    +// unlike the stored SES-8 compute_state skips a CloseApproval receipt). The host never calls Stop
    +// on this path (RT-7) and did not release the compute either: the backend has no
    +// api.CleanupRuntime, the release failed, the journal could not be read or verified (hash chain) or
    +// is shorter than it was before the operation, the journal does not record whether the latest
    +// resume ran on this harness, or another owner (a writer that committed during the operation, a
    +// checkpoint, a newer fence, a deletion) may hold it, so a release could pull it from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute and
    +// settles it in a defer registered before the allocation, so every early return after the effect
    +// passes through settle. handoffPark disarms it once its SUSPEND commits the compute to the
    +// approval gate; a handoff that fails before then leaves it armed.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner; a journal that ends before it
    +	// lost records.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads and verifies the journal: compute the journal owns (ownership) is
    +// left to it; compute another owner may hold, or whose owner the journal cannot establish (it
    +// fails verification, is shorter than before the operation, or does not record which harness the
    +// latest resume ran on), is reported without a release; and unowned compute is released through
    +// api.CleanupRuntime or, failing that, reported as a *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// Records that fail verification are no evidence either way: a tampered SUSPEND can read as a
    +	// RESUME that owns the compute, and a tampered turn as nothing that does.
    +	if verr := eventlog.VerifyChain("", recs); verr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be verified", err: verr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	// The chain verifies from genesis only, so a journal that lost its tail still verifies, and its
    +	// prefix can read LIVE on this harness (a COLD session's final SUSPEND lost). headBefore shows
    +	// the loss.
    +	if n := len(recs); g.headBefore > 0 && (n == 0 || recs[n-1].Seq < g.headBefore) {
    +		left.Cleanup = errors.New("ownership unknown: the journal is shorter than it was before the operation")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	// The journal as read now decides: the runtime attached compute the journal owned and nothing
    +	// committed since changed that, or the controller journaled this turn on it. Ownership before
    +	// the operation does not count once a record committed during it says otherwise: after another
    +	// host's SUSPEND the runtime may have woken compute the journal no longer owns, which the moved
    +	// case below reports.
    +	switch g.ownership(recs) {
    +	case owned:
    +		return
    +	case ownerUnknown:
    +		left.Cleanup = errors.New("ownership unknown: the journal does not record which harness the latest resume ran on")
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		// Including a checkpoint that superseded this turn (errSuperseded): a stateful Fork may
    +		// still be snapshotting the compute, or may fail before it suspends it, and only the
    +		// Fork's SUSPEND record would show which.
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session may hold it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,

    The warning now logs compute_instance (ComputeInstance, empty when the backend does not tell instances apart) next to incarnation_id, so it names the same compute as the error. I also added the field to docs/observability.md. The log still carries no error text.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 09, 2026 00:54 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🔵 Needs a closer look

    The ownership fold duplicates replay identity rules and controls cleanup across multi-host Resume/Fork interleavings, requiring maintainer validation of ownership and runtime-release invariants.

    <details open>
    <summary><strong>1 open issue</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Authorization sanitization drops the compute-still-running warning

  • </details>

    <details>
    <summary><strong>2 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Treat duplicate journal starts as unknown compute ownership

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Log the compute-instance identity in the failure warning

  • </details>

    <sub>Review effort: Balanced</sub>

    gambtho gambtho commented on code on Nov 09, 2026 14:35 UTC
    Code Review
    placement/compute_guard.go:1
    @@ -0,0 +1,241 @@
    +package placement
    +
    +import (
    +	"context"
    +	"errors"
    +	"fmt"
    +	"strconv"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/eventlog"
    +	"github.com/agent-primitives/sessions/internal/computestate"
    +	"github.com/agent-primitives/sessions/observability"
    +)
    +
    +// ErrComputeLeftRunning is matched (errors.Is) by the error of a Resume or Exec that failed after
    +// the runtime returned compute, when the journal records nothing that owns that compute and the
    +// host could not release it. The error is a *ComputeLeftRunningError.
    +var ErrComputeLeftRunning = errors.New("placement: compute instance may still be running")
    +
    +// ComputeLeftRunningError reports compute that a failed Resume or Exec may have left running. The
    +// runtime returned the compute, a later step failed, and the journal's compute state (SES-8) does
    +// not show a turn on the operation's harness owning it. The host never calls Stop on this path
    +// (RT-7) and did not release the compute either: the backend has no api.CleanupRuntime, the
    +// release failed, the journal could not be read, or another owner (a writer that committed during
    +// the operation, a checkpoint, a newer fence, a deletion) may hold it, so a release could pull it
    +// from under them.
    +//
    +// The error the operation failed with is Cause: errors.Is and errors.As reach it through Unwrap,
    +// so its classification (and the gRPC code session.Service maps it to) is unchanged. Cleanup says
    +// why nothing was released, and is reachable only through errors.As, never errors.Is: a cleanup
    +// failure such as a release deadline must not change how Cause is classified. The message carries
    +// Cleanup's fixed text only, never the text of a journal or release error it wraps.
    +type ComputeLeftRunningError struct {
    +	// Instance is the Incarnation.ID the runtime returned. A backend that reattaches a session
    +	// to the same compute on retry (substrate: the actor named by the session UID) returns the
    +	// same ID.
    +	Instance string
    +	// ComputeInstance is the Incarnation.ComputeInstance the runtime returned, empty for a backend
    +	// that does not tell instances apart behind one ID.
    +	ComputeInstance string
    +	// Cause is the error the operation failed with.
    +	Cause error
    +	// Cleanup is why the host did not release the compute.
    +	Cleanup error
    +}
    +
    +// Error reports Cause first, so a message read by prefix reads as it did without the report.
    +func (e *ComputeLeftRunningError) Error() string {
    +	instance := strconv.Quote(e.Instance)
    +	if e.ComputeInstance != "" {
    +		instance += " (uid " + strconv.Quote(e.ComputeInstance) + ")"
    +	}
    +	return fmt.Sprintf("%v; compute instance %s may still be running: %v", e.Cause, instance, e.Cleanup)
    +}
    +
    +// Unwrap returns Cause only; Cleanup stays out of the errors.Is chain.
    +func (e *ComputeLeftRunningError) Unwrap() error { return e.Cause }
    +
    +// Is reports whether target is ErrComputeLeftRunning.
    +func (e *ComputeLeftRunningError) Is(target error) bool { return target == ErrComputeLeftRunning }
    +
    +// releaseTimeout bounds the release of compute a failed Resume or Exec left unowned. The release
    +// ignores the caller's cancellation, so a turn the caller abandoned is still cleaned up, and runs
    +// under the session guard, which a wedged release therefore holds for at most this long.
    +const releaseTimeout = 30 * time.Second
    +
    +// computeGuard decides what happens to compute a Resume or Exec allocated when the operation then
    +// fails. The caller arms it inside the allocation effect once the runtime returns compute, disarms
    +// it when another step takes the compute over (handoffPark), and settles it in a defer registered
    +// before the allocation, so every early return after the effect passes through settle.
    +type computeGuard struct {
    +	p          *Placer
    +	log        eventlog.Store
    +	sessionUID string
    +	// headBefore is the journal head read before the allocation. A record after it was written
    +	// during the operation, by the controller or by another owner.
    +	headBefore int64
    +	// override is set when the operation runs on a Placer other than the session's own (an
    +	// ExecRequest.harness override, or the recovery of a turn recorded on one).
    +	override bool
    +	armed    bool
    +	inc      api.Incarnation
    +}
    +
    +func (g *computeGuard) arm(inc api.Incarnation) { g.armed, g.inc = true, inc }
    +
    +func (g *computeGuard) disarm() { g.armed = false }
    +
    +// settle runs when the operation returns. On success, or when no compute was returned, it does
    +// nothing. Otherwise it reads the journal: compute the journal owns (LIVE on a turn this Placer
    +// ran, liveHere) is left to it, compute another owner may hold is reported without a release, and
    +// unowned compute is released through api.CleanupRuntime or, failing that, reported as a
    +// *ComputeLeftRunningError wrapping *errp.
    +func (g *computeGuard) settle(ctx context.Context, errp *error) {
    +	err := *errp
    +	if err == nil || !g.armed {
    +		return
    +	}
    +	// A checkpoint ended this turn's connection after minting its own fence: the checkpoint owns
    +	// the compute (Suspend snapshots it, a stateful Fork clones it), exactly as it does when it
    +	// supersedes a running turn.
    +	if errors.Is(err, errSuperseded) {
    +		return
    +	}
    +	left := &ComputeLeftRunningError{Instance: g.inc.ID, ComputeInstance: g.inc.ComputeInstance, Cause: err}
    +	// Store.Read takes no context, so a cancelled caller still gets an answer.
    +	recs, rerr := g.log.Read(1)
    +	if rerr != nil {
    +		left.Cleanup = &fixedTextError{msg: "ownership unknown: the journal could not be read", err: rerr}
    +		g.report(ctx, errp, left)
    +		return
    +	}
    +	moved := len(recs) > 0 && recs[len(recs)-1].Seq > g.headBefore
    +	before := recs
    +	for i, r := range recs {
    +		if r.Seq > g.headBefore {
    +			before = recs[:i]
    +			break
    +		}
    +	}
    +	// LIVE before the call on a turn this Placer ran: the runtime attached the compute that turn
    +	// ran on, which the journal already owns. LIVE now on such a turn: the controller journaled
    +	// this turn on it. LIVE on another Placer's turn says nothing about this backend's compute.
    +	if g.liveHere(before) || g.liveHere(recs) {
    +		return
    +	}
    +	switch {
    +	case moved:
    +		// Another writer (Suspend, Delete, an approval decision, a peer's turn) committed during
    +		// the operation. A takeover by a caller's own stale cursor moves nothing and is not this.
    +		left.Cleanup = fmt.Errorf("release skipped: the journal moved past seq %d during the operation", g.headBefore)
    +	case errors.Is(err, ErrCheckpointing):
    +		left.Cleanup = errors.New("release skipped: a checkpoint of the session holds it")
    +	case errors.Is(err, eventlog.ErrFenced):
    +		left.Cleanup = errors.New("release skipped: a newer writer fenced this operation")
    +	case errors.Is(err, eventlog.ErrDeleted):
    +		left.Cleanup = errors.New("release skipped: the session is deleted")
    +	default:
    +		left.Cleanup = g.release(ctx)
    +		if left.Cleanup == nil {
    +			return
    +		}
    +	}
    +	g.report(ctx, errp, left)
    +}
    +
    +// report replaces *errp with left and logs it at Warn: the client sees only left's message, and an
    +// operator reading the log learns which instance may still be running. The log carries Cleanup's
    +// fixed text and the cause's error_kind, never an error's text (docs/observability.md).
    +func (g *computeGuard) report(ctx context.Context, errp *error, left *ComputeLeftRunningError) {
    +	*errp = left
    +	observability.Logger(ctx, g.p.logger).WarnContext(ctx, "compute may still be running",
    +		"component", "placement",
    +		"operation", "settle_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", left.Instance,
    +		"cleanup", left.Cleanup.Error(),
    +		"error_kind", placementErrorKind(left.Cause),
    +	)
    +}
    +
    +// release frees the session's compute through api.CleanupRuntime, whose contract makes it safe on
    +// any backend that implements it (no dedicated per-session resources), even if another host wrote
    +// to the journal after settle read it.
    +func (g *computeGuard) release(ctx context.Context) error {
    +	cleanup, ok := g.p.backend.(api.CleanupRuntime)
    +	if !ok {
    +		return errors.New("the backend does not implement CleanupRuntime")
    +	}
    +	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
    +	defer cancel()
    +	_, finish := observability.BeginDebug(ctx, g.p.logger, "placement", "release_compute",
    +		"session_uid", g.sessionUID,
    +		"incarnation_id", g.inc.ID,
    +	)
    +	err := cleanup.ReleaseSession(ctx, g.sessionUID)
    +	finish(err, "error_kind", placementErrorKind(err))
    +	if err != nil {
    +		return &fixedTextError{msg: "release failed", err: err}
    +	}
    +	return nil
    +}
    +
    +// fixedTextError is a Cleanup outcome whose message is the fixed text msg, since the client sees
    +// it, while err, a journal or backend error, stays reachable through errors.Is and errors.As. The
    +// release's own debug event records err's error_kind.
    +type fixedTextError struct {
    +	msg string
    +	err error
    +}
    +
    +func (e *fixedTextError) Error() string { return e.msg }
    +
    +func (e *fixedTextError) Unwrap() error { return e.err }
    +
    +// liveHere reports whether recs leave the session's compute LIVE (SES-8) with the latest turn they
    +// record run on this Placer (turnRanHere). Only then does the journal own compute this Placer's
    +// backend returned: after another Placer's turn (an ExecRequest.harness override onto either
    +// one), LIVE is that Placer's compute.
    +func (g *computeGuard) liveHere(recs []eventlog.Record) bool {
    +	return computestate.Of(recs) == api.ComputeLive && g.turnRanHere(latestTurnHarness(recs))
    +}
    +
    +// turnRanHere reports whether a turn recorded under the harness name recorded ran on this Placer.
    +// Unlike ranHere, which counts every turn it cannot attribute because its callers can only refuse
    +// on an overcount, it counts only turns it can: a wrong yes here leaves compute neither released
    +// nor reported. A standalone Placer has one backend, so every turn ran on it. In a Registry, an
    +// empty name is a turn on the session's own harness (api.ExecutionStart.Harness), which is this
    +// Placer unless the operation is an override; any other name counts when it resolves to this
    +// Placer, so an alias does and a name this host does not serve does not.
    +func (g *computeGuard) turnRanHere(recorded string) bool {
    +	if g.p.registry == nil {
    +		return true
    +	}
    +	if recorded == "" {
    +		return !g.override
    +	}
    +	q, ok := g.p.registry.lookup(recorded)
    +	return ok && q == g.p
    +}
    +
    +// latestTurnHarness returns the harness name the latest turn in recs recorded on its
    +// EXECUTION_START, or "" for a legacy turn with no EXECUTION_START or when recs record no turn,
    +// both of which ran on the session's own harness (Registry.Resume runs a session with no pending
    +// turn there too).
    +func latestTurnHarness(recs []eventlog.Record) string {
    +	for i := len(recs) - 1; i >= 0; i-- {
    +		ev := recs[i].Event
    +		switch {
    +		case ev.Kind == api.EventExecutionStart:
    +			if ev.ExecutionStart == nil {
    +				return ""
    +			}
    +			return ev.ExecutionStart.Harness

    One more fork race: the child is listed at its first fence, before the prefix finishes copying. A Resume in that window restores on B but writes only RESUME, which the guard reads as A's, so a failed Exec on A leaves compute running unreported. Reproduced at 3ef571a8. Counting B as a possible owner, or not listing the child until the copy finishes, would fix it. Possibly just a follow-up?

    gambtho gambtho approved these changes on Nov 09, 2026 14:38 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    aramase aramase
    Labels
    risk: low confidence: 86.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 86.0% · Lower = rushed or shallow review
    86.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 10% · Safe to merge
    10%