Skip to content

feat(runners): RunnerRuntime and the op path, session_id in the op envelope, the dev local adapter (task 8a) - #665

Merged
NOX73 merged 28 commits into
developfrom
feature/runners-8a-runner-runtime
Nov 8, 2026
Merged

NOX73 merged 28 commits into
developfrom
feature/runners-8a-runner-runtime

Conversation

@aixle-com

@aixle-com aixle-com Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Fix CR round 6 (Alex, 2026-11-08)

Commit: d54eb55f (runner, platform, tests and docs). No schema change.

  1. Bounded removal after a failed or cut-short container.start. Every ContainerRemove in container.start's failure paths runs under a fresh context with its own timeout (Environment.RemoveTimeout, 30 s by default), derived with context.WithoutCancel so it keeps the context's values only. A stalled daemon can no longer hold up the serial host loop. A removal that fails (not-found counts as removed) is logged through the environment's logger and named in the answer's message. The answer stays container_start_failed; the session still holds its machine, and the cleanup's env.reset removes what is left. Go tests: a remove that blocks returns within the timeout, and a remove that errors is logged; both answer container_start_failed.
  2. NoMachine is never dispatched. Runners::Machines::NoMachine is in AdmittedPhaseActivity::NEVER_DISPATCHED: acquire! raises it before any op exists, so the create operation is retryable, not uncertain. Test (RunnerSessionLaunchTest): the machine fails after the launch and before create_container; the create fails with the runner-named message and the cleanup releases the admission at once, with nothing sent to the runner.
  3. The transaction guard's limits. The guard checks calls on real runtime objects only, not on Mocha mocks or stubs: a mock("runtime") is not a BaseRuntime, and a stubs(...) on a runtime sits on the singleton class in front of the check. This is stated in the guard's header. Mocha is not hooked. New guarded tests: a whole SessionContextService assembly with a credential on FakeRuntime; Agents::CredentialDelivery to a runner holder (RunnerRuntime + FakeHostRunner) and a hosted holder (FakeRuntime); Sessions::AuthPause#heal! with a renewal on FakeRuntime.
  4. The guard's method list comes from the interface. CALLS is BaseRuntime.public_instance_methods(false) minus EXEMPT, which lists container_identifier and session_identity with their reasons (no I/O). image_digest and resolve_container are now checked. session_identity, cleanup_session and session_absent?, which every runtime already implemented and AdmittedPhaseActivity calls on every runtime, are declared on BaseRuntime, so they stay checked. RuntimeTransactionGuardTest compares the guard's list with the interface and checks image_digest and resolve_container inside a transaction.
  5. Case 14 in the docs. PROTOCOL.md §8 (next to 409 busy) and DESIGN.md §5.3: a machine unregistered during a session leaves that session's container running; the operator removes it by hand until scrub and return to service (tasks 11 and 13).

No change: SecretRegistry's blocking advisory lock (thread at secret_registry.rb:72), as Alex decided.

Tests (Coder workspace aixle-prod-2c822a0f, checkout d54eb55f, job 0f88dc20cdc2, logs in /var/lib/aixle-jobs/runner-8a-fixcr6-d54eb55/)

  • Go, golang:1.27.3: gofmt -l . (clean), go vet ./..., go test -race ./..., go mod tidy -diff: pass (01-go.log).
  • rubocop --force-exclusion on the 8 changed .rb files: no offenses (20-rubocop.log).
  • bin/vite build, then the whole Rails unit suite: 9897 runs, 0 failures, 0 errors with the guard active for every test (30-rails.log).

Fix CR round 5 (Alex, 2026-11-08)

Commits: 585780cd (runner) and 24df2bd3 (platform and docs).

  1. Docker Hub credentials. registryAuth maps docker.io and index.docker.io to https://index.docker.io/v1/ before the lookup, as the Docker CLI's getAuthConfigKey does. Go test: with {"auths": {"https://index.docker.io/v1/": …}}, a Hub reference (myorg/agent:1, docker.io/…, index.docker.io/…) sends those credentials to ImagePull.
  2. No panic on a runner stop during ContainerCreate. A context.Canceled create removes whatever the daemon may have created and answers container_start_failed ("cut short"); pastDeadline's nil is never dereferenced. Go test: the fake engine cancels the context once it has made the container and never answers; container.start returns a result and nothing is left.
  3. Docs on the sequence. PROTOCOL.md §6: finished ops are kept 7 days, and sequence comes from a per-machine counter. The prune bullet below is corrected, and this description now has Fix CR round 4 and 5 sections.
  4. No runtime call inside a database transaction.
    • BaseRuntime states the contract for every runtime, hosted included: a runtime call is external I/O and is never made inside a transaction. Runners::Operations.enqueue! may still join a caller's transaction; waiting for the op's result inside it is what deadlocks.
    • test/support/runtime_transaction_guard.rb prepends a check to every BaseRuntime subclass, FakeRuntime included. A runtime call made while a joinable transaction is open is recorded, and the test fails at teardown. The test's own wrapping transaction is opened non-joinable, so it does not count. It is recorded rather than raised because the code under test may rescue what the call raises (SecretRegistry does).
    • Sessions::SecretRegistry#publish! writes the list outside any transaction. A session's publications stay in order through pg_advisory_lock before and pg_advisory_unlock in ensure, on the same key.
    • Tests: RuntimeTransactionGuardTest, and SecretRegistryRunnerTest, which publishes through a real RunnerRuntime answered by FakeHostRunner: the write_file op completes before its deadline and the list holds the secret. SecretRegistryConcurrencyTest still passes with the connection-level lock.
  5. The cleanup waits for unfinished environment ops too. RunnerRuntime#cleanup_ready? is false while any pending or delivered op exists on the machine the session holds, not only ops with its terminal_session_id. Test: with an env.reset pending, the cleanup is not ready until that reset expires or finishes, and nothing else is queued.
  6. The container name is the platform's. create_container returns container_name(session) (aixle-<key>-<session_id>). A container.start answer naming another container raises a plain RuntimeError, so the create stays uncertain and the cleanup still resets the machine. No new index and no new migration. Test: two sessions on two runners, and a container.start answer naming the other session's container. The create fails, the session's later status and cleanup reach only its own machine, and the other session's container is untouched.

Docs: PROTOCOL.md §6 and §6.1; DESIGN.md §5.3 (create_container, cleanup) and row 8a.

Run on Coder workspace aixle-prod-2c822a0f at 24df2bd3, logs in /var/lib/aixle-jobs/runner-8a-fixcr5-24df2bd/:

  • Go (gofmt -l ., go vet ./..., go test -race ./..., go mod tidy -diff, golang:1.27.3): pass (01-go.log).
  • Rubocop on the 7 Ruby files this round changed: no offenses (20-rubocop.log).
  • The whole Rails unit suite (bin/vite build, then rails test): 9891 runs, 0 failures, 0 errors, with the transaction guard active for every test (31-rails-with-assets.log). A first run without the Vite build (30-rails.log) had 0 failures and 673 errors, all "Vite Ruby can't find … in the manifests".
  • GitHub CI at 24df2bd3: all 17 checks pass.

Fix CR round 4 (Alex, 2026-11-08)

Commits: 099eedf0 (runner and the Dockerfile move), db88af2b (platform, migration and docs), 945c5f43 (fixes the first test run found).

  • A stop during the image pull. The Go container.start runs the pull, the volumes, ContainerCreate and ContainerStart under context.WithDeadline(op.DeadlineAt) and creates nothing past it. On the platform, BaseRuntime#cleanup_ready? lets RunnerRuntime answer false while an op is unfinished on the session's machine, so the cleanup returns cleanup_pending and is retried.
  • Registry credentials. The pull resolves the image registry's credentials with docker/cli's LoadDefaultConfigFile and GetAuthConfig, credential helpers included, and passes them as ImagePullOptions.RegistryAuth. With none, the pull is anonymous.
  • Answered refusals. ContainerRuntime::CreateRefusedError is resolved in record_failed_operation; RunnerRuntime::PullFailed is removed. An expired create stays uncertain.
  • The sequence moved to runner_environments.op_sequence (migration 20261108100000, backfilled), and the prune deletes every old finished op. ON DELETE CASCADE stays.
  • Holder checked at enqueue. enqueue!(…, session:) creates an op only while that session holds the machine, under the environment lock. This replaced the model validation, and acquire! no longer touches the caller's session.
  • Machines.fail!(env, reason, holder:) is a compare-and-set; unregister! clears the hold; acquire! is idempotent for one session; Machines.availability answers :available, :none_registered or :all_failed.
  • Composite company keys from runner_operations and runner_environments to terminal_sessions (id, company_id).
  • Go SessionHandler(ctx, sessionID, payload); WithOpSession is removed.
  • The Compose service uses image: ${RUNNER_IMAGE:-runner}, and the Dockerfile is docker/runner/local/Dockerfile.
  • Tested on Coder workspace aixle-prod-2c822a0f at 945c5f43 (logs in /var/lib/aixle-jobs/runner-8a-fixcr4-945c5f4/): Go pass, migration with no schema diff, rubocop clean, 1307 Rails runs with 0 failures.

Fix CR round 3 (Alex, 2026-11-07): the image is pulled as on Kubernetes, and RunnerRuntime is not bound to a session

Commits: f924a28f (runner), 7aa55e31 (platform and docs), 80ea0c70 and 0dd88495 (fixes found by the test run).

  1. The image is pulled as on Kubernetes.
    • RunnerRuntime#pull_image does nothing, like KubernetesRuntime#pull_image. The machine is taken in create_container.
    • The Go container.start always pulls the reference, then creates and starts the container (Docker's create API does not pull). The pull runs after the cheap refusals (session_mismatch, container_exists), so a refused start pulls nothing. A failed pull is image_pull_failed, with nothing created; image_not_found is gone.
    • image.ensure is removed everywhere: RunnerOperation::OPS, RunnerRuntime, FakeHostRunner, PROTOCOL.md (§6.1 is now "The agent image", which says how container.start pulls), ops/image_ensure.json, the Go handler and its tests. The pull helpers moved to runner/internal/docker/image.go, and container_start.json gained an image_pull_failed case.
    • identity_before_pull? and persist_identity_before_pull are removed. AdmittedPhaseActivity already persisted the identity before create_container for every runtime.
    • A runner's failed pull raises RunnerRuntime::PullFailed (an ImagePullError). The runner answers it only when nothing was created, so record_failed_operation treats it as resolved and the cleanup releases the admission. Without this the create operation stayed pinned (unresolved_operation).
    • The agent session's create_container budget is 600 s (AgentSessionStrategy#phase_config). DESIGN.md §12.3 records this as a deliberate change to hosted: a larger timeout only.
  2. RunnerRuntime is not bound to a session. RunnerRuntime.new(op_timeout:); one object serves any session.
    • create_container(spec) takes the session from the spec's aixle.session_id label. A spec without it is refused before anything is sent.
    • Every other call takes it from the admission whose runtime_id its id is (runtime_kind = RunnerRuntime), whether that id is the cleanup identity runner-session-<id> or the container's name. An id that no runner admission has answers no_session_container and sends nothing.
    • A new partial index, index_session_admissions_on_runner_runtime_id (runtime_id, runner admissions only), keeps that lookup off a table scan.
    • op_timeout stays a setting of the object. ContainerRuntime.for_session still decides between a runner and hosted.
  3. Cancellation while waiting for an op. The wait heartbeats and calls cancellation.check! on every look, as ToolStrategy#wait_with_heartbeat does. The op itself is left to its deadline.
  4. Runners::Operations.await has a comment: polling the database is to be revisited with P1 (DESIGN.md §16), for example with a wake-up on the pub/sub the long-poll uses.
  5. ContainerRuntime.for_session uses session&.runner_id.
  6. Credential reuse moves the machine to failed. Runners::Credentials.rotate! calls Runners::Machines.fail!(environment, "credential reuse detected"): failed, the reason in state_reason, held by no session. The DESIGN.md §2.2 note is updated. A new test shows that such a machine is not given a session.

Docs: DESIGN.md §2.2, §2.4, §5.3 (both phase tables, the for_session snippet, the wait), the §6.4 op table, §6.8, §8, §12.3, and rows 6a and 8a. PROTOCOL.md §6, §6.1, §6.2 and §6.4.

Tests (adapted): runner_runtime_test.rb drives one runtime across sessions through their admissions (FakeHostRunner.identify!). It adds a test of one runtime serving two sessions on two machines, a test of an unknown id, a test that the cleanup identity finds the session, and a cancellation test. runner_session_launch_test.rb now has the pull failing in container.start, the capacity wait in create_container, and a stop before the create that takes no machine. There are also the contract test, AuthPause, ContainerRuntimeTest, AgentSessionStrategyTest (600 s) and CredentialsTest. In Go: container.start always pulls (tag, digest, untagged as :latest), a failed pull creates nothing, and a refused start pulls nothing.

Run on Coder workspace aixle-prod-2c822a0f:

  • At 80ea0c70, logs in /var/lib/aixle-jobs/runner-8a-fixcr3-80ea0c7/:
    • Go (gofmt -l, go vet ./..., go test -race ./...): pass.
    • The migration: the 0994730d schema loaded, db:migrate, and the dumped db/schema.rb equals the committed one.
    • Rubocop on the 18 changed Ruby files: no offenses.
    • Regression set (container strategies, sessions, agents, internal tools, trackers, session context, session service, admission recovery, Temporal workflows, test/docs, test/config): 1561 runs, 0 failures, 0 errors.
  • At 0dd88495, logs in /var/lib/aixle-jobs/runner-8a-fixcr3-0dd8849/:
    • Rubocop: 18 files, no offenses.
    • The runner and runtime set (test/services/container_runtime, container_runtime_test.rb, test/services/runners, the runner models, every Temporal activity, the runner launch, failed-machine, gateway, gateway-ops, conformance and container-workflow integration tests, HostedRuntimeUnchangedTest (§12.3), AgentSessionStrategyTest and AuthPauseTest): 794 runs, 0 failures, 0 errors.

The open review threads of rounds 2 and 3 are untouched, as Alex asked.


Fix CR round 2 (Alex, 2026-11-07): the runtime is picked in one place and passed explicitly

This round is a refactor with no behaviour change. Commits: db8d6534 (the refactor) and 0994730d (a test).

The rule. ContainerRuntime.for_session is the only place that picks a runtime. No runtime lives in Thread.current, a global or class-level state. A runtime reaches the code that uses it as an argument or a constructor dependency.

Places changed:

  • SessionContextService is one object per assembly, SessionContextService.new(container_id, session, runtime:). It holds the container, the session, its runtime and the context log.
    • SessionContextService.assemble_session_context is the thin entry point. It calls ContainerRuntime.for_session(session) once and builds the object.
    • Removed: Thread.current[:session_context_runner_runtime], Thread.current[:session_context_runtime], assemble_on_runner and runner_session?.
    • The helpers lose their container_id and session arguments, and inject_oauth_token! loses its session.nil? guard, because the session is always there.
    • Sessions::SecretRegistry.publish! in the MCP config step now gets the assembly's runtime instead of building its own.
    • I chose the object over passing runtime to each helper, because every helper that touches the container would otherwise take one more argument.
  • AgentCredential#write_to_container(container_id, workflow_config = {}, runtime:): runtime: is required, and the method calls AgentCredentialsService.for(agent_type, runtime: runtime) with no conditional.
  • The scanners ScanDeadContainersActivity, ScanNoOutputSessionsActivity and ScanQuotaErrorsActivity: runtime_for is deleted. Each calls ContainerRuntime.for_session(session, op_timeout: Settings.runners.scan_op_timeout) once per session and passes the result to the methods that use it.
  • CleanupStaleActivity: the hosted-only runtime is deleted, and the hosted path calls for_session the same way. The runner_id branch that moves a held machine to failed stays (round 1, item 8).
  • Agents::CredentialDelivery takes each holder's runtime from for_session. Its runtime: constructor parameter, unused since round 1, is removed.
  • AdmittedPhaseActivity#persist_identity_before_pull: only identity_before_pull? decides, and the runner_id check is gone. A hosted session's runtime is now built at pull_image. It answers false, so nothing is persisted there.
  • RunnerRuntime requires temporalio/activity (the [Note] from verification round 1).
  • Docs: DESIGN.md row 8a states the rule. The session_context_service.rb line references in docs/project/context.md and docs/architecture/implementation-patterns.md follow the move.

Reusing one hosted runtime: not measured on a cluster, chosen from the code.

  • DockerRuntime holds no state, because it uses docker-api's process-wide connection. A runtime per session costs one allocation.
  • KubernetesRuntime builds its Kubeclient clients lazily per instance, and a client's first call adds one discovery request (GET /api/v1). A runtime per session therefore costs the three per-minute scanners one extra small GET per hosted session per sweep, on top of the reads they already make.
  • Reusing one hosted runtime inside ContainerRuntime would need process-level mutable state, which the rule excludes. So I chose one runtime per session per sweep. If the extra GETs matter, a cache belongs in KubernetesRuntime's clients, which is a hosted change outside this task.

Tests.

  • The tests that reset Thread.current now build the assembly with its runtime.
  • AgentSessionStrategyTest's inject_credential expectations were dead, because that method is no longer on the class. They now expect a single assemble_session_context.
  • A new test checks that every write of an assembly, the credential's included, goes through the runtime for_session gives.

Run on Coder workspace aixle-prod-2c822a0f at 0994730d, with logs in /var/lib/aixle-jobs/runner-8a-fixcr2/:

  • Rubocop on the changed Ruby files: 15 files, no offenses.
  • The changed tests (session context, BMAD e2e, agent session strategy, the agent credentials service and model, the session service): 341 runs, 0 failures, 0 errors.
  • The runtimes, Runners::*, every Temporal activity, the runner launch, failed-machine, conformance and gateway tests, HostedRuntimeUnchangedTest (§12.3) and ContainerWorkflowIntegrationTest: 675 runs, 0 failures, 0 errors.
  • The container strategies, sessions, agents, internal tools, trackers, admission recovery, Temporal workflows, test/docs and test/config: 1420 runs, 0 failures, 0 errors.

The four review-round-2 threads stay open for Alex's decision.


Fix CR round 1 (Alex's decisions, 2026-11-07)

No digest (Alex's decision, replacing the platform-side pin):

  • Runners::ImagePin and its tests are deleted. The platform never contacts a registry, which also resolves the SSRF thread.
  • image.ensure, container.start and the helper container of env.scrub take {"image": <reference>}: the reference as the user gave it, a tag or a digest, container.image_override included (now for image.ensure too, so the image pulled is the image started).
  • The Go runner always pulls the reference. pulled says whether the pull brought a new image: the daemon did not have it, or the reference now names another image ID. A failed pull is image_pull_failed, even with an older copy on the daemon. No op returns a digest. A reference with neither tag nor digest is read as :latest.
  • PROTOCOL.md §6.1, §6.2 and §6.4, the fixtures, and DESIGN.md (§5.3, the §6.4 op table, §6.8, §7.2, rows 6a, 6b and 8a) are updated. bin/runner-local keeps the note that the agent images must come from a registry.

The fixes:

  1. [Must] Machine held after a failure or a stop in pull_image. AdmittedPhaseActivity persists RunnerRuntime's identity (runner-session-<id>, runtime_kind) before pull_image (BaseRuntime#identity_before_pull?, true only for RunnerRuntime; a hosted session's runtime is not built there). Tests: image.ensure fails, and a stop between pull_image and create_container. In both, the cleanup runs container.stop and env.reset and the machine is free.
  2. [Must] SSRF in ImagePin. Resolved by the deletion above.
  3. Deadline vs expiry. Runners::Operations.await stops at the op's deadline_at and expires the op. EXPIRY_GRACE (10 s) is only in expire_overdue!, the sweep for ops nobody waits for. An op's deadline is at most the activity's end less RunnerRuntime::ACTIVITY_MARGIN (5 s), so the activity acts on the expired outcome before Temporal times it out. A scanner pays exactly scan_op_timeout per unanswered op. Test: cleanup_session in an activity context with an unanswered env.reset leaves the machine failed with the reason.
  4. AuthPause#heal! no longer passes its runtime. Each holder is written through its own runtime. Test: a hosted paused session and a runner holder of the same credential.
  5. docs/project/context.md now describes Docker's exec!. DESIGN.md §12.3 records this deliberate change to hosted.
  6. Stale DESIGN.md statements: no batch in RunnerRuntime, and the session's identity is only in the envelope.
  7. [Must] A failed reset is a state. RunnerEnvironment.state gets failed. A failed or unanswered env.reset moves the machine to failed, clears current_session_id and keeps the reason in state_reason, as text for people. Machines::RESET_FAILED and reset_failed? are removed. A free machine is registered with no session, so deleting the session frees nothing. session_absent? is true once the session holds no machine. A runner whose every machine is failed fails the launch at once (Runners::Resolver and Runners::Machines). The message names the machines and their reasons and says how to bring one back: aixle-runner unregister, then configure. The capacity_wait message counts only registered machines. The gateway still accepts a failed machine's credentials (test). Regression test: test/integration/runner_failed_machine_test.rb fails env.reset, releases the admission, deletes the session through DELETE /api/v1/terminal_sessions/:id, and shows that no other session can take the machine.
  8. The stale-session fallback. CleanupStaleActivity sends a runner nothing. If a stale runner session still holds a machine, the machine moves to failed with "held by stale session " and the move is logged. Tests cover a session with a machine and one without.
  9. session_mismatch from the lifecycle ops. RunnerRuntime sends an op only while the session holds its machine (runner_environments.current_session_id). Otherwise it answers no_session_container itself and enqueues nothing. On the Go side, container.stop without this session's container answers session_mismatch (another session's container) or no_session_container (none). container.start over another session's container answers session_mismatch, and over its own container or an unlabelled leftover it answers container_exists. cleanup_session logs a failed container.stop and goes on to env.reset. RunnerRuntime#stop_container treats no_session_container as already stopped, as Docker does. PROTOCOL.md §6 and §6.2, the fixtures and the Go tests are updated, including TestASessionOpOfAnotherSessionIsRefused.

Fix CR round 1 tests: on Coder workspace aixle-prod-2c822a0f, logs in /var/lib/aixle-jobs/runner-8a-fixcr1/:

  • go: gofmt -l ., go vet ./... and go test -race ./... pass.
  • Rubocop on the changed Ruby files: no offenses.
  • The runner and runtime set (test/services/container_runtime, test/services/runners, the runner launch, failed-machine, gateway, conformance and selection integration tests, HostedRuntimeUnchangedTest, AuthPause, CleanupStaleActivity, the sweep, the runner models): 451 runs, 0 failures.
  • The wider regression set (container strategies, session context, sessions, internal tools, trackers, every Temporal activity, ContainerWorkflowV2 with history replay, admission, test/config, test/docs, the terminal-sessions API): 1503 runs. 1498 passed. The other 5 were image-name assertions in AgentAuthStrategyTest, which failed because a previous run had left AGENT_IMAGE_PREFIX in the workspace's .env. With that line removed, the file passes on its own: 56 runs, 0 failures.

Summary

Board task #207, Runners 8a: RunnerRuntime and the op path, session_id in the op envelope, and the dev local adapter. Design: docs/design/agent-runtimes/DESIGN.md §15 row 8a.

What changed

ContainerRuntime.for_session and RunnerRuntime (§5.3)

  • ContainerRuntime.for_session(session) gives a session with a runner ContainerRuntime::RunnerRuntime. Every other session gets ContainerRuntime.build, unchanged.
  • These call sites go through it, because each one acts on one session:
    • BaseStrategy#runtime (and #resolve_container) and AdmittedPhaseActivity (create and cleanup);
    • SessionContextService, and the credential write it makes, which passes the runtime to AgentCredentialsService;
    • Sessions::LiveLogReader, Sessions::AuthPause, Sessions::SecretRegistry, Trackers::Workspace and Agents::CredentialDelivery;
    • the internal tools that read a session's files;
    • the scanners ScanDeadContainersActivity, ScanQuotaErrorsActivity, ScanNoOutputSessionsActivity and CleanupStaleActivity.
  • ContainerSweepOrphanedResourcesActivity sweeps the hosted runtime's own objects, so it is unchanged.
  • One runtime call is one runner op. RunnerRuntime enqueues the op with Runners::Operations.enqueue! and waits for its result with Runners::Operations.await, which heartbeats the activity. It then answers what DockerRuntime answers.
  • An op that ends error or expired gives the strategy what a hosted failure gives: ContainerUnreachableError from exec! without the session's container, exit code 1 from exec, false from write_file, nil from read_file, :missing from container_status.
  • There is no batch grouping (decision 5).
  • Deadlines. An op's deadline_at is at most the end of the activity that sends it, less 5 s. The wait stops at the deadline and expires the op. Inside that, each op has its own budget:
    • an exec: its timeout + 30 s;
    • other session ops: Settings.runners.op_timeout, 60 s, which is what DockerRuntime#exec waits by default;
    • lifecycle ops: lifecycle_op_timeout, 600 s.
    • The scanners cap every op at scan_op_timeout (15 s). A machine that does not answer reads as unknown, never as dead or idle, and cannot hold up the hosted sessions' sweep.
  • The phases:
    • pull_image does nothing (Fix CR round 3). create_container takes a free machine and sends container.start, which always pulls the image reference as given, a tag or a digest (Fix CR round 1: no digest).
    • create_container sends container.start. See "Decisions to review" for why it is here.
    • start_container and wait_for_ready wait for status running.
    • cleanup collects the logs and outputs through the same strategy code, then sends container.stop and env.reset, then frees the machine.
  • The container's options come from the runner's config.container (§2.7). Its resources are the hosted container's limits unless container.resources sets them.
  • Runners::Resolver no longer refuses with runner_execution_not_enabled. A runner with no registered machine is refused at launch with runner_unreachable and a message that names the runner.
  • DockerRuntime#exec! raises ContainerUnreachableError for a container the daemon does not know. Before, it raised NoMethodError on nil. The contract test's "exec! with no container" scenario needs this.

Which machine takes the session (decision 2): Runners::Machines

  • A session takes a free registered machine of its runner, one session per machine. The machine is taken under its row lock (FOR UPDATE SKIP LOCKED).
  • The assignment is recorded in terminal_sessions.runner_environment_id and in runner_environments.current_session_id (unique). The second one is the hold.
  • Every machine busy raises ContainerRuntime::CapacityError, so the session waits in capacity_wait.
  • After the session, the machine gets env.reset and is free again.
  • A failed or unanswered reset moves the machine to failed, held by no session, with the reason in state_reason, so it takes no other session (Fix CR round 1). The session's reservation is still released.

session_id in the op envelope (requirement 1)

  • New column runner_operations.terminal_session_id.
  • A session op must name a session that runs on the op's machine. An environment op names none. The gateway sends session_id only for session ops.
  • session_id left the payloads of container.start and container.stop.
  • The Go host runner reads session_id from the envelope:
    • a session op without one is refused with session_required;
    • a session op whose container carries another session's aixle.com/session label is refused with session_mismatch, and the container is not touched;
    • container.start names and labels the container from the envelope.
  • PROTOCOL.md §5.4 and §6 are updated, and the §8 item is removed. The fixtures have the new session_on_machine setup step, implemented by both harnesses.

The queue's housekeeping

  • An op without a result is expired by the platform and its payload is nulled. Two things do this:
    • the wait that sent it, at the op's deadline_at;
    • RunnerOperationsSweepWorkflow, every 5 minutes, for ops nobody waits for, 10 s past their deadline_at, pending or delivered.
  • Prune: the sequence is a counter on the machine (Fix CR round 4, chosen over keeping each environment's newest row). enqueue! takes the next sequence from runner_environments.op_sequence, on the row it already locks. Runners::Operations.prune! deletes every completed, failed and expired op older than 7 days, the newest included, and a session's deletion takes its ops with it (ON DELETE CASCADE). The counter never goes back, so sequence keeps growing after a prune.

The dev local adapter (§12.2)

  • The runner-local Compose service, under the runners profile, builds aixle-runner from runner/ (docker/runner-local/Dockerfile).
  • It runs in web's network namespace, so it reaches the gateway on 127.0.0.1:4003, the only address aixle-runner accepts plain http on. It uses this machine's Docker socket.
  • bin/runner-local register <runner id> mints a registration token, runs configure and starts the service. bin/runner-local unregister and bin/runner-local logs also exist.

Docs: PROTOCOL.md, fixtures/README.md and DESIGN.md:

  • §15: rows 8a (done), 8b (with decision 4) and 8c (with decision 3);
  • §5.3 and §2.4: what 8a built;
  • §2.3: expiry and prune;
  • §6.4: session_id in the envelope;
  • §6.9.7: decision 4;
  • §16: P1 deferred, with no fixed target.

Decisions to review

  • container.start is sent in create_container, not in start_container. The container's environment holds the session's secrets: session keys, the VS Code token, credential-sync keys. It exists only in the create phase, because ContainerService::CREATE_ONLY_KEYS drops it from the phase state, which Temporal history and the admission record persist. So the runner creates and starts the container in that one op, the way a Kubernetes pod is created running. start_container then waits for nothing more than the container running. A retried create that finds its own container running adopts it.
  • The machine is taken in create_container (Fix CR round 3), the first phase that needs it, since container.start pulls the image there.
  • The image is pinned on the platform. Fix CR round 1 replaced this with Alex's decision: no digest, and the runner always pulls the reference it is given. For the dev local adapter, point the agent images at a registry, for example AGENT_IMAGE_PREFIX=ghcr.io/aixlehq/flow-.
  • 409 busy on DELETE /registration is not built. It is not in 8a's scope list. A machine unregistered during a session leaves the session's next ops unanswered until they expire. PROTOCOL.md §8 says so.

What answers RunnerRuntime's ops in the tests, and why

  • ContainerRuntime::FakeHostRunner (test/support/fakes/fake_host_runner.rb) subscribes to enqueued.runner_operations. It answers each op on the machine's real queue the moment the op is enqueued, through Runners::Operations.record_result!, with the result PROTOCOL.md §6 specifies. It answers from an in-memory machine (FakeMachine).
  • That is the boundary RunnerRuntime talks to: the queue and the op results. The gateway's HTTP is covered by RunnerGatewayOperationsTest and the conformance fixtures. The Go runner's Docker calls are covered by its own tests.
  • In the contract test (test/services/container_runtime/runner_runtime_contract_test.rb), DockerRuntime runs unchanged, through docker-api, against the Docker Engine API. FakeDockerEngine serves that API over WebMock from the same machine. Each scenario runs on both runtimes, and the strategy must get the same result:
    • a step that succeeds;
    • an exec with a non-zero code;
    • a failed write;
    • exec! with no container;
    • Sessions::LiveLogReader reading a live and a gone container.

How was this tested?

  • Rails:
    • bin/rails test test/services/container_runtime test/services/container_runtime_test.rb test/services/runners test/integration/runner_session_launch_test.rb test/integration/hosted_runtime_unchanged_test.rb test/integration/runner_protocol_conformance_test.rb test/integration/runner_gateway_operations_test.rb test/temporal/activities/runner_operations.
    • The §12.3 test now also runs the live log and the scanners on a hosted session, with the flag off and on.
  • Go: cd runner && gofmt -l . && go vet ./... && go test -race ./....
  • Locally, with the stack up:
    1. Create a manual runner in a company with external_runners on.
    2. Run AGENT_IMAGE_PREFIX=ghcr.io/aixlehq/flow- make up, then bin/runner-local register <runner id>.
    3. Start a non-interactive session on the runner.

Run on a Coder workspace (aixle-prod-2c822a0f, earlier aixle-prod-ee0c28d5), in the web image of this branch:

  • go: gofmt -l ., go vet ./..., go test -race ./... in runner/ (golang:1.27.3). All passed.
  • Migration: bin/rails db:migrate on the develop schema. The dumped db/schema.rb matches the committed one.
  • Rubocop: bundle exec rubocop --force-exclusion <changed .rb files>. No offenses.
  • Rails, at c5d340b: the container strategies, SessionContextService, the sessions services, the internal tools, the trackers, every Temporal activity, ContainerWorkflowV2 and the history replay, the container runtimes, Runners::*, the runner gateway and conformance, HostedRuntimeUnchangedTest, the runner selection and launch tests, the admission services, test/config and test/docs. 1904 runs, 0 failures, 0 errors. CI runs the full suite.

Related issues

Board task #207 (Runners 8a). The next parts are 8b (the callback proxy) and 8c (the live log and parity with hosted).

Type of change

  • New feature
  • Documentation

Checklist

  • All my commits are signed off for the DCO (git commit -s).
  • I added/updated tests where it makes sense.
  • I updated documentation where it makes sense.
  • User-visible changes have an entry under [Unreleased] in CHANGELOG.md. There is none: runner execution is behind external_runners, which only the test company has, as for the earlier runner tasks.

Aixle Flow added 12 commits November 7, 2026 10:28
…velope, the dev local adapter (task 8a)

Signed-off-by: Aixle Flow <[email protected]>
…he machine, and the scanners cap a runner op

Signed-off-by: Aixle Flow <[email protected]>
…he web container's output

Signed-off-by: Aixle Flow <[email protected]>
…ig, whose keys arrive as symbols

Signed-off-by: Aixle Flow <[email protected]>
Comment thread app/services/runners/image_pin.rb Resolved
Comment thread docs/design/agent-runtimes/DESIGN.md Resolved
Comment thread runner/internal/docker/container.go Resolved
Aixle Flow added 3 commits November 7, 2026 16:23
…d container.start and container.stop refuse another session's container

image.ensure, container.start and env.scrub take {image}: the reference as the
user gave it, a tag or a digest. The runner always pulls it and reports whether
the pull brought a new image; no digest is sent or returned.

container.stop without this session's container answers session_mismatch when
the environment's session container is another session's, and
no_session_container when there is none. container.start over another
session's container answers session_mismatch; over its own or an unlabelled
leftover, container_exists as before.

PROTOCOL.md §6, §6.1, §6.2 and §6.4 and the fixtures are updated.

Signed-off-by: Aixle Flow <[email protected]>
… a session's ops reach its machine only while it holds it

- Runners::ImagePin is deleted: RunnerRuntime sends the image reference as it
  was given, container.image_override included, and the platform never
  contacts a registry.
- AdmittedPhaseActivity persists RunnerRuntime's identity before pull_image, so
  a pull that fails, or a stop before the create, still runs cleanup_session and
  frees the machine.
- A failed or unanswered env.reset moves the machine to failed and clears
  current_session_id; deleting the session frees nothing. A runner whose every
  machine failed fails the launch at once, naming them and how to bring one
  back (Runners::Machines, Runners::Resolver).
- RunnerRuntime sends an op only while the session holds its machine, and stops
  waiting at the op's deadline, which is the activity's end less 5 s; the
  sweep's grace is for the ops nobody waits for.
- AuthPause#heal! lets each holder be written through its own runtime.
- CleanupStaleActivity sends a runner nothing, and moves a machine a stale
  session still holds to failed.
- DESIGN.md, docs/project/context.md and bin/runner-local follow.

Signed-off-by: Aixle Flow <[email protected]>
Comment thread app/services/runners/machines.rb Resolved
Comment thread app/services/runners/machines.rb Resolved
Comment thread app/models/agent_credential.rb Resolved
Comment thread app/services/session_context_service.rb Resolved
Aixle Flow added 3 commits November 8, 2026 07:45
…ner.start stops at its deadline, and the pull sends the registry's Docker credentials

Fix CR round 4 (Alex, comments 68781 and 68791), the runner side:

- Session ops get their own handler type, SessionHandler, with the
  envelope's session_id as a parameter. sessionOp reads it once and
  refuses a missing or non-positive one; WithOpSession and OpSession
  are removed.
- container.start runs the pull, the volumes, the create and the start
  under context.WithDeadline(op.DeadlineAt): past it, it creates
  nothing and the ops loop moves on.
- The pull resolves the credentials of the image's registry as the
  Docker CLI does (LoadDefaultConfigFile, GetAuthConfig, credential
  helpers included) and passes them as ImagePullOptions.RegistryAuth;
  with none, the pull stays anonymous.
- PROTOCOL.md and the fixtures README say so.

Signed-off-by: Aixle Flow <[email protected]>
…ine, and the cleanup waits for an unfinished start

Fix CR round 4 (Alex, comments 68781 and 68791), the platform side:

- Runners::Operations.enqueue! takes the session of every op,
  environment ops included, and creates the op only while that session
  holds the environment, under the row lock it already takes. It
  replaces RunnerOperation#session_is_on_the_environment.
- The op sequence is a counter on runner_environments (op_sequence), so
  the prune and a session's deletion remove any finished op.
- Machines.acquire! no longer touches the caller's session and answers
  the winner's hold when two attempts of one session race;
  Machines.fail!(..., holder:) is a compare-and-set; unregistering a
  machine ends its hold; Machines.availability answers a symbol and one
  method words the refusal.
- The company keys of the session references, with a unique index on
  terminal_sessions (id, company_id).
- The cleanup sends nothing while an op of the session is unfinished on
  its machine (BaseRuntime#cleanup_ready?).
- An answered container.start refusal is a
  ContainerRuntime::CreateRefusedError and pins no reservation;
  RunnerRuntime::PullFailed is removed.
- The SessionContextService tests inject the runtime.
- The local runner's Dockerfile moves to docker/runner/local, and its
  image is ${RUNNER_IMAGE:-runner}.
- DESIGN.md is updated.

Signed-off-by: Aixle Flow <[email protected]>
…lete key, and the enqueue leaves its transaction with next

Fixes the Coder run of db88af2 found: the dumped schema orders the
runner_environments keys the other way, the company-key test of
runner_operations saved without the op's runner and company, and
enqueue! returned from inside its transaction block.

Signed-off-by: Aixle Flow <[email protected]>
Comment thread runner/internal/docker/image.go Resolved
Comment thread runner/internal/docker/container.go Resolved
Comment thread runner/protocol/PROTOCOL.md Resolved
Aixle Flow added 2 commits November 8, 2026 12:02
…ores them, and a runner stop during ContainerCreate answers a result

- registryAuth maps docker.io and index.docker.io to https://index.docker.io/v1/,
  as the Docker CLI's getAuthConfigKey does.
- container.start handles context.Canceled during ContainerCreate apart from the
  deadline: it removes what the daemon may have created and answers
  container_start_failed, with no nil dereference.
- PROTOCOL.md §6: finished ops are kept 7 days, and sequence comes from the
  per-machine counter; §6.1 names the Docker Hub key.

Signed-off-by: Aixle Flow <[email protected]>
… for any unfinished op, and the container name is the platform's

- BaseRuntime: a runtime call is external I/O and is never made inside a
  database transaction; test/support/runtime_transaction_guard.rb fails a test
  that makes one inside an application transaction.
- Sessions::SecretRegistry#publish! writes the list outside any transaction,
  serialized with a connection-level advisory lock.
- RunnerRuntime#cleanup_ready? is false while any op is pending or delivered on
  the machine the session holds, env.reset included.
- RunnerRuntime#create_container returns container_name(session); an answer
  naming another container is an error.
- DESIGN.md §2.4/§5.3 and row 8a.

Signed-off-by: Aixle Flow <[email protected]>
… NoMachine is never dispatched, and the transaction guard checks the whole runtime interface

Signed-off-by: Aixle Flow <[email protected]>
…he round 7 docs and comments

The host runner cuts a positive exec timeout to the seconds left until the op's deadline_at, as it already bounds an exec without one, so an exec never holds the serial ops loop past its op's deadline.

DESIGN.md: row 8c says how a terminal log over 1 MiB is stored until 8c, row 11 notes the bounded removal of the scrub helper container. The transaction guard's and NEVER_DISPATCHED's comments say exactly what holds.

Signed-off-by: Aixle Flow <[email protected]>
@aixle-com

aixle-com Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

Fix CR round 7 (Alex, 2026-11-08)

Commit: aaa9b6d2 (runner, docs and two comments). No schema change.

  1. An exec's timeout is capped by its op's deadline. The Go exec handler cuts a positive timeout to the seconds left until the op's deadline_at, as it already bounds an exec without one. Go test: TestAnExecTimeoutLongerThanTheOpsDeadlineIsCutToIt. PROTOCOL.md §6.3 updated.
  2. Oversized terminal log, deferred to 8c. DESIGN.md §15 row 8c: until 8c a terminal log over 1 MiB is stored as the logs tail, and 8c replaces it with the full log through a signed URL.
  3. Two comments corrected: runtime_transaction_guard.rb and admitted_phase_activity.rb.
  4. DESIGN.md §15 row 11: the scrub helper container's removal in scrub.go gets a bounded timeout when env.scrub is first sent.

No change, as Alex decided: the serial scanner budget, the exec options env/cwd/user, and the per-op budget of wait_for_ready/wait_container.

Tests (Coder workspace aixle-prod-2c822a0f, checkout aaa9b6d2, job b01f6d3f3582, logs in /var/lib/aixle-jobs/runner-8a-fixcr7-aaa9b6d/)

  • Go, golang:1.27.3: gofmt -l . (clean), go vet ./..., go test -race ./..., go test -race -count=1 -run Exec -v ./internal/docker/, go mod tidy -diff: pass (01-go.log).
  • rubocop --force-exclusion on the 2 changed .rb files: no offenses (20-rubocop.log).
  • Rails: runtime_transaction_guard_test.rb, admitted_phase_activity_test.rb, runner_runtime_contract_test.rb: 32 runs, 0 failures, 0 errors (30-rails.log). The Ruby changes are comments only.

@NOX73
NOX73 merged commit e4d422f into develop Nov 8, 2026
17 checks passed
@NOX73
NOX73 deleted the feature/runners-8a-runner-runtime branch November 8, 2026 16:50
aixle-com Bot pushed a commit that referenced this pull request Nov 8, 2026
Conflicts were between the squash merges of #665 and #666 on develop and the earlier feature-branch versions of the same PRs already on staging. Every conflicted file was touched on staging only by those two branches, so each takes develop's final version.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant