Skip to content

feat(cloud-native): cross-process single-writer session leasing (Phase 4) (#60) - #119

Merged
JAORMX merged 5 commits into
mainfrom
feat/60-session-leasing
Jun 19, 2026
Merged

JAORMX merged 5 commits into
mainfrom
feat/60-session-leasing

Conversation

@JAORMX

@JAORMX JAORMX commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

Closes #60. Phase 4 (final piece) of the cloud-native arc (ADR 0027).

What & why

Makes cross-process single-writer enforcement a code-enforced backstop, not just a session-affinity deployment assumption. Today two replicas over one store can each loadAndReopen → run → Save over each other — the cross-process twin of the Phase 2 concurrent-/approve double-execution bug. A lease prevents it.

Design (maintainer pre-decided)

  • port.SessionLease — a new OPTIONAL capability (Acquire/Renew/Release returning an immutable {SessionID, Owner, Token, Expiry} Lease), discovered by type assertion exactly like port.PrunableStore. Sentinels ErrLeaseHeld / ErrLeaseUnsupported (the latter sticky-disables to a byte-identical no-lease path). The engine loop never imports it — the renewer + heldLeases registry live on server.Service (same storage-agnostic discipline as port.EventLog).
  • Enforcement at the run-entry funnel (StartRunContent / resumeFromAwaiting, after runEntryMu): a session held by another live owner is refused with ErrSessionLeasedElsewhere → gRPC FailedPrecondition / HTTP 409.
  • Session-scoped lifecycle: acquire on first run-entry, hold + renew in a Service-owned background renewer across turns, release on CloseSession/shutdown; TTL expiry is the crash-failover path. On lease loss the renewer cancels the in-flight run (a transient renew blip within headroom is tolerated; ErrLeaseHeld is definitive and cancels immediately). The fencing Token is plumbed through every adapter; CAS-Save enforcement is deferred (documented).

Adapters

  • engine/adapter/memlease — reference, clock-injected.
  • internal/adapter/flocklease — single-host (gofrs/flock; auto-release on process death = crash recovery).
  • gRPC SessionLeaseService driver — proto + client + server wrapper, conformance over bufconn.
  • internal/adapter/k8slease — in-process over coordination.k8s.io/v1 Lease objects (resourceVersion CAS, leaseTransitions as the fencing epoch, least-privilege RBAC).
  • Composition wires an independent --session-lease-{url,dir,k8s-namespace} override or type-asserts the store; default = no lease wired (byte-identical to pre-Phase-4).

Tests

  • Conformance-as-contract suite run against memlease, flocklease, the gRPC driver over bufconn, and k8slease (fake clientset + a reactor-injected conflict path; envtest gap documented).
  • Gates: cross-process exclusion + TTL-expiry takeover; the cross-process double-execution scenario prevented by the lease; byte-identical default; renewer success + race-with-Close under -race.
  • Live two-process e2e (e2e/lease_exclusion_test.go): HTTP 409 while held, takeover after release/SIGKILL.

Review

Ran the full dev-pipeline (architect → implement → spec/standards/architecture/security/k8s-operator/concurrency panel + QA test-adequacy → iterate). The panel caught one Critical (-race data race on the held-lease registry) plus RBAC over-grant, missing hot-path timeouts, a CancelFunc leak, first-blip cancel, and two missing renewer tests — all fixed and independently re-verified.

Verification

task lint → 0 issues · task test (-race) → clean · go run ./cmd/mecademo → full offline session · matlatl check --strict → 0 broken links.

Docs

ADR 0027 Phase 4 deferred → SHIPPED with the List 1 inventory row + List 2 / List 3(c) re-audit; docs/usage.md flags + k8s RBAC + flock single-host note + multi-replica posture; docs/architecture/observability.md behaviour; AGENTS.md gotcha. GC-liveness consulting the lease is a documented follow-on.

🤖 Generated with Claude Code

…e 4) (#60)

Phase 4 of the cloud-native arc (ADR 0027): make cross-process single-writer
enforcement a code-enforced backstop, not just a session-affinity deployment
assumption. Two replicas over one store could each loadAndReopen -> run -> Save
over each other (the cross-process twin of the Phase 2 concurrent-/approve
double-execution bug); a lease prevents it.

New optional capability `port.SessionLease` (Acquire/Renew/Release returning an
immutable {SessionID, Owner, Token, Expiry} Lease), discovered by type assertion
exactly like port.PrunableStore, with ErrLeaseHeld / ErrLeaseUnsupported
sentinels (the latter sticky-disables to a byte-identical no-lease path). The
engine loop never imports it — the renewer + heldLeases registry live on
server.Service, the same storage-agnostic discipline as port.EventLog.

Enforcement at the run-entry funnel (StartRunContent / resumeFromAwaiting, after
runEntryMu): a session held by another live owner is refused with
ErrSessionLeasedElsewhere -> gRPC FailedPrecondition / HTTP 409. Session-scoped
lifecycle: acquire on first run-entry, hold + renew in a Service-owned background
renewer across turns, release on CloseSession / shutdown; TTL expiry is the
crash-failover path. On lease loss the renewer cancels the in-flight run (a
transient renew blip within headroom is tolerated; an ErrLeaseHeld is definitive
and cancels immediately). The fencing Token is plumbed through every adapter but
CAS-Save enforcement is deferred (documented).

Adapters: engine/adapter/memlease (reference, clock-injected); a single-host
internal/adapter/flocklease (gofrs/flock; auto-release on process death =
crash recovery); a gRPC SessionLeaseService driver (proto + client + server
wrapper, conformance over bufconn); and an in-process internal/adapter/k8slease
over coordination.k8s.io/v1 Lease objects (resourceVersion CAS, leaseTransitions
as the fencing epoch, least-privilege RBAC). Composition wires an independent
--session-lease-{url,dir,k8s-namespace} override OR type-asserts the store;
default = no lease wired (byte-identical to pre-Phase-4).

Conformance-as-contract suite (engine/adapter/leaseconformance) run against
memlease, flocklease, the gRPC driver over bufconn, and k8slease (fake clientset
+ a reactor-injected conflict path; envtest gap documented). Gate tests: cross-
process exclusion + TTL-expiry takeover, the cross-process double-execution
scenario prevented by the lease, byte-identical default, and a live two-process
e2e (HTTP 409 while held, takeover after release/SIGKILL). Renewer success +
race-with-Close guards run under -race.

Docs: ADR 0027 Phase 4 deferred -> SHIPPED with the List 1 inventory row + the
List 2 / List 3(c) re-audit; docs/usage.md flags + k8s RBAC + flock single-host
note + multi-replica posture; docs/architecture/observability.md behaviour; the
AGENTS.md gotcha. GC-liveness consulting the lease is a documented follow-on.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
JAORMX and others added 3 commits June 19, 2026 05:37
The deployment & hardening guide (the operator-facing production doc) had no
mention of the multi-replica posture or session leasing. Add a "Multi-replica
deployment & single-writer enforcement" subsection pointing to the usage-guide
flags + RBAC manifest, the observability seam doc, and ADR 0027. Regenerate
llms.txt (matlatl check --strict: 0 broken links).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…collision (#60)

The live e2e harness allocated the gRPC/HTTP/metrics ports with three separate
freePort() calls, each closing its listener before the next. The OS could then
re-assign the same just-freed ephemeral port to two of them — observed in CI as
httpPort == metricsPort, so the admin/metrics server bound the port first and
the HTTP/SSE listener crashed the daemon at startup ("bind: address already in
use"). This is a pre-existing latent race; the new lease spec exposed it because
it spawns THREE daemons per run (bootstrap + replica A + replica B), widening
the window.

Replace the three calls with freePorts(3), which holds all listeners open
simultaneously before reading their ports, so a single daemon's three ports are
guaranteed distinct. The irreducible cross-process bind→hand-off window remains
(loopback-private; FlakeAttempts covers it) but a daemon can no longer collide
its own ports.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@JAORMX
JAORMX marked this pull request as ready for review June 19, 2026 06:29
The lease-exclusion spec spawns three daemons (bootstrap → replica A → replica
B), the first chained NewLocalSharingStore usage. The helper bound the new
spawn's stateRoot to prior.Root rather than prior.stateRoot, so replica B
pointed --store-dir at replica A's OWN (empty) scratch root instead of the
shared store tree A actually uses. B therefore couldn't see the session A
created and its run-start returned 404 (session not found) instead of the
409 the lease should produce — the lease enforcement was never reached.

Bind stateRoot to prior.stateRoot so chaining keeps every spawn on the SAME
store. For an ordinary first spawn prior.stateRoot == prior.Root, so the
existing 2-process restart callers (approve-after-kill, verdict-replay) are
unaffected. Also document that a live prior is safe specifically when a session
lease guards the store (the lease-exclusion scenario).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@JAORMX
JAORMX merged commit c8472be into main Jun 19, 2026
9 checks passed
@JAORMX
JAORMX deleted the feat/60-session-leasing branch June 19, 2026 06:52
JAORMX added a commit that referenced this pull request Jun 19, 2026
… clock-injectability, supply-chain, event-sourced rehydration (#120)

Make engine/ a clean, dependable, embeddable library (the Atrium convergence): import-and-inject the core instead of vendoring. On top of #119 (session leasing); kept a monorepo via a committed go.work.

- #116 clock-injectability: all engine-core wall-clock reads route through the injected port.Clock (nil-safe Engine.now()); ephemeral child ids use an atomic counter (fake-clock-safe); AST arch guard forbids time.Now/Since/Until in core.
- #113 engine as its own Go module (github.com/stacklok/mecatl/engine) via go.work; external consumers get a tiny dep graph (x/sync + doublestar + goleak), not the toolhive/k8s/otel/grpc/SDK cone; dedicated GOWORK=off CI hygiene proof. ADR 0036.
- #114 stability contract: engine/COMPATIBILITY.md + a text API-snapshot freshness gate (captures const values/exported surface; tied to arch.CorePackages); gorelease advisory. ADR 0037.
- #118 supply-chain: per-module govulncheck (engine strict-clean; root fail-closed gate + dated allowlist for two unfixable docker CVEs) + dependabot for both modules and SHA-pinned actions.
- #115 event-sourced rehydration: engine/adapter/eventsource.Fold (EventLog + SessionMeta -> *session.Session) + reconstruction contract; new log-only EvUserPrompt so the durable log records and the fold reconstructs user-role turns (closes a latent ADR-0027 gap). ADR 0038.
- follow-up: go 1.26.3 -> 1.26.4 to clear three newly-disclosed stdlib CVEs the new vuln gate caught.

No hard API breaks; import paths unchanged. Validated by full CI + the live OpenRouter e2e suite.

Closes #113
Closes #114
Closes #115
Closes #116
Closes #118

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

e2e-live Run the live e2e suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cloud-native Phase 4: cross-process single-writer enforcement (session leasing)

1 participant