Skip to content

Two isolation drivers behind one interface

Relay’s job runner had a if (process.platform === "linux") in nine places. Each one chose between “run the job in a sandbox” and “run it directly”. Over a year the two branches drifted: the sandbox path got timeouts and the direct path did not, and a bug fix landed in one and not the other. Nobody could say what a job did on a developer’s laptop compared with production.

tsbox has the same fork, and a worse one, because the two sides really are different. Lessons 4 and 5 build isolation with namespaces and cgroups, which exist only on Linux. On macOS there is nothing to call. The solution is to put the fork in one place, behind one interface, and to make the difference visible instead of hiding it.

A driver is the thing that turns a ContainerSpec into a running container and back. The interface is the one the rest of tsbox (the CLI, the monitor) sees, and it is small:

type ContainerState =
| { readonly _tag: "Created" }
| { readonly _tag: "Running"; readonly pid: number; readonly startedAt: number }
| { readonly _tag: "Exited"; readonly code: number; readonly finishedAt: number }
type DriverError =
| { readonly _tag: "NotFound"; readonly id: string }
| { readonly _tag: "AlreadyExists"; readonly id: string }
| { readonly _tag: "InvalidState"; readonly id: string; readonly state: ContainerState["_tag"] }
type Result<T, E> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: E }
interface Driver {
readonly name: string
create(id: string): Promise<Result<void, DriverError>>
start(id: string): Promise<Result<ContainerState, DriverError>>
stop(id: string, graceMs: number): Promise<Result<ContainerState, DriverError>>
inspect(id: string): Promise<Result<ContainerState, DriverError>>
}

This is a port in the sense of dependencies as types. Everything that can go wrong is in the return type as a tagged error (errors as values), so a caller handles “no such container” and “already running” without a try. Two real implementations sit behind it:

  • the namespace driver (Linux): the RunPlan of lesson 4, the cgroup writes of lesson 5, a monitor from lesson 6. The container sees its own filesystem, process tree and hostname, and the limits hold.
  • the process driver (any POSIX system, including macOS): Bun.spawn of the command as an ordinary child. The “container” is a process. It sees the host’s files, processes and network, and nothing enforces a limit.

The second one is useful: it lets you develop and test tsbox on a Mac, and run a program under the same lifecycle (created, running, exited, stopped with a grace period, as in signals). It is also a lie if tsbox lets you believe it isolates anything. So the difference is made explicit.

Each driver carries a capabilities value, and the value is a literal type:

interface Capabilities {
readonly isolation: "namespaces" | "none"
readonly enforcesLimits: boolean
}
interface Driver<C extends Capabilities = Capabilities> {
readonly name: string
readonly capabilities: C
}
type EnforcingCaps = { readonly isolation: "namespaces"; readonly enforcesLimits: true }
const processCaps = { isolation: "none", enforcesLimits: false } as const satisfies Capabilities
declare const processDriver: Driver<typeof processCaps>
function createLimited(driver: Driver<EnforcingCaps>, memoryBytes: number): string {
return `${driver.name} limited to ${memoryBytes} bytes`
}
// @ts-expect-error: the process driver cannot enforce limits
createLimited(processDriver, 256 * 1024 * 1024)

as const keeps "none" and false as literals. satisfies still checks them against Capabilities, so a typo is an error, without widening them to string and boolean. A function that must not run on a driver without isolation asks for Driver<EnforcingCaps>, and passing the process driver is a compile error. This is the same idea as the state-typed APIs of M2: an operation that only makes sense in some situations is unavailable in the others.

Most decisions still happen at runtime, because the driver is chosen when tsbox starts. That is why capabilities are also plain data. isolationNotice(caps) returns a warning to print when isolation is "none", and checkSupported(caps, spec) refuses a spec with --memory when the driver cannot enforce it. tsbox’s first draft accepted --memory 256m on macOS and ran with no limit: refusing is the honest behaviour, and the error says which limits were not enforced.

Which driver to use depends on facts about the host: the platform, whether user namespaces are allowed and whether the unified cgroup tree is mounted. Reading them is I/O (process.platform, files under /proc and /sys). Deciding from them is a pure function:

interface HostInfo {
readonly platform: string
readonly userNamespaces: boolean
readonly cgroupV2: boolean
}
function detectDriver(host: HostInfo): { driver: "namespace" | "process"; reason: string } {
if (host.platform !== "linux") return { driver: "process", reason: `${host.platform} has no namespaces` }
if (!host.userNamespaces) return { driver: "process", reason: "user namespaces are disabled" }
if (!host.cgroupV2) return { driver: "process", reason: "cgroup v2 is not mounted" }
return { driver: "namespace", reason: "linux with user namespaces and cgroup v2" }
}
console.log(detectDriver({ platform: process.platform, userNamespaces: false, cgroupV2: false }))

Checking platform === "linux" alone is the bug from the exercise’s story: plenty of Linux machines (some CI runners, hardened distributions, containers without the right permissions) forbid unprivileged user namespaces. A reason string that explains the choice costs nothing and turns “why is tsbox not isolating?” into one line of tsbox info.

How do you keep two drivers behaving the same? The same way as in fakes and contract tests: write the rules once, as a function that takes any driver, and run it against every implementation. The contract states what the Driver interface promises:

type DriverError = { readonly _tag: "NotFound"; readonly id: string }
type Result<T, E> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: E }
interface Driver {
inspect(id: string): Promise<Result<{ readonly _tag: string }, DriverError>>
}
async function checkUnknownId(driver: Driver): Promise<void> {
const ghost = await driver.inspect("ghost")
if (ghost.ok || ghost.error._tag !== "NotFound") throw new Error("contract: inspect of an unknown id is NotFound")
}

The exercise’s contract is longer: unknown ids, create twice, the legal and illegal state transitions, start returning a pid and the clock time, stop returning Exited with code 143 (128 + SIGTERM) only after the process is really gone, inspect agreeing with what start and stop returned, and stopping twice changing nothing. It uses an injected clock, so startedAt and finishedAt are exact. It throws a plain Error on a broken rule, so any test runner can call it.

A contract is only worth something if it can fail. The test file also runs it against six deliberately broken drivers, each the process driver with one method made too forgiving (a duplicate create accepted, stop of an unknown id succeeding, inspect still reporting Running after a stop, stop returning before the process is gone, and so on). The contract must reject every one of them. That is what stops you from writing a contract that passes everything.

The process driver is real: it spawns, waits, sends SIGTERM, waits graceMs and escalates to SIGKILL, and the tests start an actual sleep. A fake namespace driver is in memory, and passing the same contract is what justifies using it in tests of code that needs “a Linux driver” on a Mac.

Inside the Linux VM, check what detectDriver would see, and run the process-driver tests there too (they pass on Linux as well, which is the point of a contract):

Terminal window
podman machine ssh
cat /proc/sys/kernel/unprivileged_userns_clone 2>/dev/null || echo "no such knob: user namespaces are on by default"
cat /proc/sys/user/max_user_namespaces
stat -fc %T /sys/fs/cgroup

max_user_namespaces above 0 means user namespaces are enabled (a distro can still restrict them with a security module), and cgroup2fs from stat means the unified cgroup tree is mounted. With both, detectDriver picks namespace. On macOS process.platform is "darwin" and it picks process, which is why your tests there run against the process driver and the fake.

Local, because the process driver spawns real programs. Copy driver.ts and process.ts unchanged, copy main.starter.ts as main.ts, add the test file, and run bun test. The tests use sleep and sh, which exist on macOS and Linux.

You write the pure decisions (detectDriver, isolationNotice, checkSupported), the in-memory makeFakeDriver, and runDriverContract. The starter’s detectDriver only looks at the platform, it prints no notice and refuses no limits, its fake driver answers NotFound to everything, and its contract checks nothing, so every broken driver slips through. The tests run your contract on the process driver and on your fake, and your contract must fail all six broken drivers. The last tests spawn real processes: a natural exit with a recorded code, a failed spawn that leaves the container Created, and a child that ignores SIGTERM and has to be killed after the grace period.

driver.ts
export type Result<T, E> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: E }
export const ok = <T>(value: T): Result<T, never> => ({ ok: true, value })
export const err = <E>(error: E): Result<never, E> => ({ ok: false, error })
export interface ContainerSpec {
readonly id: string
readonly image: string
readonly cmd: readonly string[]
readonly env: Readonly<Record<string, string>>
readonly limits: { readonly memoryBytes?: number; readonly cpuQuota?: number; readonly pids?: number }
}
export type ContainerState =
| { readonly _tag: "Created" }
| { readonly _tag: "Running"; readonly pid: number; readonly startedAt: number }
| { readonly _tag: "Exited"; readonly code: number; readonly finishedAt: number }
export type DriverError =
| { readonly _tag: "NotFound"; readonly id: string }
| { readonly _tag: "AlreadyExists"; readonly id: string }
| { readonly _tag: "InvalidState"; readonly id: string; readonly state: ContainerState["_tag"] }
| { readonly _tag: "SpawnFailed"; readonly id: string; readonly message: string }
export interface Capabilities {
readonly isolation: "namespaces" | "none"
readonly enforcesLimits: boolean
}
export interface Clock {
now(): number
}
export interface Driver<C extends Capabilities = Capabilities> {
readonly name: string
readonly capabilities: C
create(spec: ContainerSpec): Promise<Result<void, DriverError>>
start(id: string): Promise<Result<ContainerState, DriverError>>
stop(id: string, graceMs: number): Promise<Result<ContainerState, DriverError>>
inspect(id: string): Promise<Result<ContainerState, DriverError>>
}
export type EnforcingCaps = { readonly isolation: "namespaces"; readonly enforcesLimits: true }
export function createLimited(driver: Driver<EnforcingCaps>, spec: ContainerSpec): Promise<Result<void, DriverError>> {
return driver.create(spec)
}
process.ts
import { err, ok } from "./driver.ts"
import type { Capabilities, Clock, ContainerSpec, ContainerState, Driver, DriverError, Result } from "./driver.ts"
export const processCaps = { isolation: "none", enforcesLimits: false } as const satisfies Capabilities
interface Entry {
readonly spec: ContainerSpec
state: ContainerState
child: Bun.Subprocess<"ignore", "ignore", "ignore"> | undefined
exited: Promise<number> | undefined
}
export function makeProcessDriver(clock: Clock): Driver<typeof processCaps> {
const entries = new Map<string, Entry>()
const notFound = (id: string): Result<never, DriverError> => err({ _tag: "NotFound", id })
return {
name: "process",
capabilities: processCaps,
async create(spec) {
if (entries.has(spec.id)) return err({ _tag: "AlreadyExists", id: spec.id })
entries.set(spec.id, { spec, state: { _tag: "Created" }, child: undefined, exited: undefined })
return ok(undefined)
},
async start(id) {
const entry = entries.get(id)
if (entry === undefined) return notFound(id)
if (entry.state._tag !== "Created") return err({ _tag: "InvalidState", id, state: entry.state._tag })
let child: Bun.Subprocess<"ignore", "ignore", "ignore">
try {
child = Bun.spawn([...entry.spec.cmd], {
env: { ...process.env, ...entry.spec.env },
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
})
} catch (cause) {
return err({ _tag: "SpawnFailed", id, message: cause instanceof Error ? cause.message : String(cause) })
}
entry.child = child
entry.state = { _tag: "Running", pid: child.pid, startedAt: clock.now() }
entry.exited = child.exited.then((code) => {
entry.state = { _tag: "Exited", code, finishedAt: clock.now() }
return code
})
return ok(entry.state)
},
async stop(id, graceMs) {
const entry = entries.get(id)
if (entry === undefined) return notFound(id)
if (entry.state._tag === "Created") return err({ _tag: "InvalidState", id, state: "Created" })
const { child, exited } = entry
if (entry.state._tag === "Running" && child !== undefined && exited !== undefined) {
child.kill("SIGTERM")
let timer: ReturnType<typeof setTimeout> | undefined
const timedOut = new Promise<"timeout">((resolve) => {
timer = setTimeout(() => resolve("timeout"), graceMs)
})
if ((await Promise.race([exited, timedOut])) === "timeout") child.kill("SIGKILL")
clearTimeout(timer)
await exited
}
return ok(entry.state)
},
async inspect(id) {
const entry = entries.get(id)
return entry === undefined ? notFound(id) : ok(entry.state)
},
}
}
main.ts
// tsbox has two ways to run a container: the Linux namespace driver (real isolation, real limits) and the
// process-only driver (macOS, and Linux without user namespaces: no isolation at all). Both sit behind one
// Driver interface, and driver.ts and process.ts (given: copy them unchanged) define it. The first draft
// picked the driver with `process.platform === "linux"`, so a Linux box with user namespaces disabled
// crashed at `unshare`, and on macOS `--memory 256m` was accepted and ignored: the container used 4 GB.
// Rules:
// - detectDriver(host) returns { driver, reason }. Checked in this order: platform not "linux" ->
// process, `<platform> has no namespaces`; no user namespaces -> process, "user namespaces are disabled";
// no cgroup v2 -> process, "cgroup v2 is not mounted"; otherwise namespace, "linux with user namespaces
// and cgroup v2".
// - isolationNotice(caps) is undefined for a driver with isolation, and for one without exactly
// "WARNING: no isolation: this container shares the host's processes, files and network".
// - checkSupported(caps, spec): a driver that does not enforce limits refuses a spec that sets any,
// with `driver cannot enforce limits: <names>` (memoryBytes, cpuQuota, pids, in that order, only the set ones).
// - makeFakeDriver(clock) is an in-memory Driver with capabilities { isolation: "namespaces",
// enforcesLimits: true }, name "fake-namespace", pids from 1000 up, and stop giving Exited code 143.
// - runDriverContract(makeDriver) throws an Error whose message starts with "contract: " when a driver
// breaks a rule. It must check: unknown ids are NotFound for inspect, start and stop; create twice is
// AlreadyExists; a new container is Created; stop on Created and start on Running are InvalidState
// (with the state tag); start returns Running with a positive pid and the clock time; stop returns Exited
// code 143 with the clock time, and inspect agrees with what start and stop returned; stopping an Exited
// container returns the same state; containers do not affect each other. It stops what it started.
// - The test file runs the contract on both drivers, and on six broken drivers that it must reject.
import { err, ok } from "./driver.ts"
import type { Capabilities, Clock, Driver, ContainerSpec, EnforcingCaps, Result } from "./driver.ts"
export interface HostInfo {
readonly platform: string
readonly userNamespaces: boolean
readonly cgroupV2: boolean
}
export interface Choice {
readonly driver: "namespace" | "process"
readonly reason: string
}
export function detectDriver(host: HostInfo): Choice {
return host.platform === "linux"
? { driver: "namespace", reason: "linux" }
: { driver: "process", reason: "not linux" }
}
export function isolationNotice(_caps: Capabilities): string | undefined {
return undefined
}
export function checkSupported(_caps: Capabilities, _spec: ContainerSpec): Result<void, string> {
return ok(undefined)
}
export function makeFakeDriver(_clock: Clock): Driver<EnforcingCaps> {
return {
name: "fake-namespace",
capabilities: { isolation: "namespaces", enforcesLimits: true },
async create() {
return ok(undefined)
},
async start(id) {
return err({ _tag: "NotFound", id })
},
async stop(id) {
return err({ _tag: "NotFound", id })
},
async inspect(id) {
return err({ _tag: "NotFound", id })
},
}
}
export async function runDriverContract(makeDriver: (clock: Clock) => Driver): Promise<void> {
const driver = makeDriver({ now: () => 0 })
await driver.inspect("ghost")
}
main.test.ts
import { afterEach, expect, test } from "bun:test"
import { mkdtempSync, existsSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { createLimited, ok } from "./driver.ts"
import type { Capabilities, Clock, ContainerSpec, Driver } from "./driver.ts"
import { checkSupported, detectDriver, isolationNotice, makeFakeDriver, runDriverContract } from "./main.ts"
import { makeProcessDriver, processCaps } from "./process.ts"
const spec = (overrides: Partial<ContainerSpec> = {}): ContainerSpec => ({
id: "c1",
image: "alpine",
cmd: ["sleep", "30"],
env: {},
limits: {},
...overrides,
})
const dirs: string[] = []
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
test("the process driver passes the contract", async () => {
await runDriverContract((clock) => makeProcessDriver(clock))
})
test("the fake namespace driver passes the same contract", async () => {
await runDriverContract((clock) => makeFakeDriver(clock))
})
const exited = { _tag: "Exited", code: 0, finishedAt: 0 } as const
function mutate(base: Driver, patch: Partial<Driver>): Driver {
return { ...base, ...patch }
}
const mutants: ReadonlyArray<readonly [string, (base: Driver) => Driver, string]> = [
[
"create ignores duplicates",
(base) =>
mutate(base, {
async create(s) {
await base.create(s)
return ok(undefined)
},
}),
"create twice is AlreadyExists",
],
[
"start twice is accepted",
(base) =>
mutate(base, {
async start(id) {
const result = await base.start(id)
return result.ok ? result : base.inspect(id)
},
}),
"start twice is InvalidState",
],
[
"stop of an unknown id succeeds",
(base) =>
mutate(base, {
async stop(id, graceMs) {
const result = await base.stop(id, graceMs)
return !result.ok && result.error._tag === "NotFound" ? ok(exited) : result
},
}),
"stop of an unknown id is NotFound",
],
[
"stop on a Created container succeeds",
(base) =>
mutate(base, {
async stop(id, graceMs) {
const result = await base.stop(id, graceMs)
return !result.ok && result.error._tag === "InvalidState" ? ok(exited) : result
},
}),
"stop on Created is InvalidState",
],
[
"inspect still says Running after stop",
(base) =>
mutate(base, {
async inspect(id) {
const result = await base.inspect(id)
return result.ok && result.value._tag === "Exited" ? ok({ _tag: "Running", pid: 1, startedAt: 0 }) : result
},
}),
"inspect agrees with what stop returned",
],
[
"stop returns before the process is gone",
(base) =>
mutate(base, {
async stop(id, graceMs) {
const before = await base.inspect(id)
if (!before.ok || before.value._tag !== "Running") return base.stop(id, graceMs)
void base.stop(id, graceMs)
return before
},
}),
"stop returns Exited",
],
]
for (const [name, make, expected] of mutants) {
test(`the contract catches a broken driver: ${name}`, async () => {
await expect(runDriverContract((clock) => make(makeProcessDriver(clock)))).rejects.toThrow(expected)
})
}
test("the process driver records a natural exit with the injected clock", async () => {
let time = 10
const clock: Clock = { now: () => time }
const driver = makeProcessDriver(clock)
await driver.create(spec({ cmd: ["sh", "-c", "exit 3"] }))
await driver.start("c1")
time = 99
for (let i = 0; i < 200; i++) {
const state = await driver.inspect("c1")
if (state.ok && state.value._tag === "Exited") break
await Bun.sleep(10)
}
expect(await driver.inspect("c1")).toEqual({ ok: true, value: { _tag: "Exited", code: 3, finishedAt: 99 } })
})
test("a program that cannot start is SpawnFailed and the container stays Created", async () => {
const driver = makeProcessDriver({ now: () => 0 })
await driver.create(spec({ cmd: ["tsbox-no-such-program"] }))
const started = await driver.start("c1")
expect(!started.ok && started.error._tag).toBe("SpawnFailed")
expect(await driver.inspect("c1")).toEqual({ ok: true, value: { _tag: "Created" } })
})
test("stop escalates to SIGKILL when the process ignores SIGTERM", async () => {
const dir = mkdtempSync(join(tmpdir(), "tsbox-"))
dirs.push(dir)
const marker = join(dir, "ready")
const driver = makeProcessDriver({ now: () => 0 })
await driver.create(spec({ cmd: ["sh", "-c", "trap '' TERM; touch \"$1\"; exec sleep 30", "sh", marker] }))
await driver.start("c1")
for (let i = 0; i < 300 && !existsSync(marker); i++) await Bun.sleep(10)
expect(existsSync(marker)).toBe(true)
const began = performance.now()
const stopped = await driver.stop("c1", 150)
expect(stopped).toEqual({ ok: true, value: { _tag: "Exited", code: 137, finishedAt: 0 } })
expect(performance.now() - began >= 140).toBe(true)
})
test("the host decides the driver", () => {
expect(detectDriver({ platform: "darwin", userNamespaces: false, cgroupV2: false })).toEqual({
driver: "process",
reason: "darwin has no namespaces",
})
expect(detectDriver({ platform: "linux", userNamespaces: false, cgroupV2: true })).toEqual({
driver: "process",
reason: "user namespaces are disabled",
})
expect(detectDriver({ platform: "linux", userNamespaces: true, cgroupV2: false })).toEqual({
driver: "process",
reason: "cgroup v2 is not mounted",
})
expect(detectDriver({ platform: "linux", userNamespaces: true, cgroupV2: true })).toEqual({
driver: "namespace",
reason: "linux with user namespaces and cgroup v2",
})
})
test("a driver without isolation says so, and one with isolation stays quiet", () => {
expect(isolationNotice(processCaps)).toBe("WARNING: no isolation: this container shares the host's processes, files and network")
expect(isolationNotice({ isolation: "namespaces", enforcesLimits: true })).toBe(undefined)
})
test("limits are refused when the driver cannot enforce them", () => {
const limited = spec({ limits: { memoryBytes: 1048576, pids: 8 } })
expect(checkSupported(processCaps, limited)).toEqual({ ok: false, error: "driver cannot enforce limits: memoryBytes, pids" })
expect(checkSupported(processCaps, spec())).toEqual({ ok: true, value: undefined })
expect(checkSupported({ isolation: "namespaces", enforcesLimits: true }, limited)).toEqual({ ok: true, value: undefined })
})
test("capabilities are in the type, so the compiler refuses the wrong driver", async () => {
const fake = makeFakeDriver({ now: () => 0 })
const caps: Capabilities = fake.capabilities
expect(caps.isolation).toBe("namespaces")
expect(await createLimited(fake, spec())).toEqual({ ok: true, value: undefined })
const process = makeProcessDriver({ now: () => 0 })
// @ts-expect-error: the process driver does not isolate or enforce limits
void createLimited(process, spec())
})
  • Put the Linux/macOS fork in one place: a Driver port with create, start, stop and inspect, whose errors are values.
  • Be honest about what a driver cannot do. Capabilities are literal types, so the compiler refuses a limit-needing call on the process driver, and plain data, so the CLI can print a warning or refuse a flag.
  • Choose the driver with a pure function of facts about the host, and keep its reason.
  • Write the rules once as a contract, run it against every driver and every fake, and check that the contract itself fails broken drivers.
  • The process driver works anywhere and isolates nothing. It is for developing and testing tsbox, not for running untrusted code.