Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions services/platform/tests/manual/reference/automation.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s
| [navigation](../suites/navigation.md) | `NAV-B12` (the logic half): a read TanStack Query cancels when a navigation unmounts its page rejects as an `AbortError` that never flags the backend unreachable, so the offline overlay stays down; an event whose thrown value is an `AbortError` — also in the SDK's `AbortError: …` and stringified `Error: AbortError: …` shapes — is dropped before it is sent, while a failure merely caused by one is kept | 🔶 unit + component | `app/lib/backend/api-client.test.ts`, `app/components/connectivity/online-gate.test.tsx` (a real `QueryClient` read cancelled by an unmount, under the real connection state), `app/lib/sentry-normalize.test.ts`, `lib/utils/abort-error.test.ts`; the throttled real-browser round with a live DSN stays manual |
| [navigation](../suites/navigation.md) | `NAV-B14`: the error displays' **contact support** link follows `TALE_CONTACT_SUPPORT_URL` from the environment through `window.__ENV__` and the app-root `SupportUrlProvider` to the rendered link, which opens in a new tab with the organization as `organizationId` (replacing one the URL carries). The web tier hands the page the value only as an absolute http(s) URL, verbatim and script-safe, and leaves anything else out with a warning, so the link keeps `https://tale.dev/contact`; a display's own `supportUrl` wins over the provider | ✅ e2e + component + server | `tests/e2e/specs/navigation.spec.ts` (*the contact-support link opens the operator's page*), `packages/ui/src/components/error-boundaries/core/support-url.test.tsx`, `packages/ui/src/components/error-boundaries/displays/error-display-compact.test.tsx`, `packages/ui/src/components/error-boundaries/displays/global-error-display.test.tsx`, `lib/contact-support-url.test.ts`, `lib/utils/inline-script.test.ts`, `vite-plugins/inject-env.test.ts`, `server.test.ts` |
| [settings](../suites/settings.md) | Foreground egress proxy boots, stops gracefully and restarts with read-only `/tmp` | ✅ automated | `tests/integration/container-smoke-test.ts` and `compose.test.yml` (real proxy health, refused temporary-file creation, shutdown exit/log and same-container restart) |
| [settings](../suites/settings.md) | Sandbox memory lifetime: completed commands release request/consumer data while a sibling remains active; held-open stdin refuses whole lines above its 8 MiB pending queue and accepts again after draining; HTTP intake and device tunnel completion detach their listeners | 🔶 unit + real processes + HTTP | `services/sandbox-runtime/daemon/src/exec-manager.memory.test.ts` (bundled manager under Node), `exec-manager.test.ts`, `http-body.test.ts`, `main.test.ts`; `services/sandbox/src/devices/tunnel.test.ts`; production workload memory profiling remains operational |
| [settings](../suites/settings.md) | The egress proxy serves `SANDBOX_EGRESS_MAX_CLIENTS` connections at once (2000 by default) for the whole fleet, keeps its 600 s tunnel timeout, refuses to start on a value that is no whole number above 0, raises its soft open-file limit to two descriptors per connection as far as the hard limit allows (a Kubernetes Pod sets none) and leaves a limit that already holds them alone, and warns when even the hard limit cannot hold them; both compose pipelines pass the same default and size the container's pids and open-file limits for it | ✅ automated | `services/sandbox/src/egress-proxy-config.test.ts` (the real entrypoint and template), `tools/cli/src/lib/compose/services/compose-parity.test.ts` (`egress connection capacity parity`) |
| [settings](../suites/settings.md) | Explicit native configuration recovery retains the superseded plan and verified writes; rejects unrelated edits, omitted resources and wrong organizations; replays interrupted replacement through managed provisioning | ✅ automated | `tools/cli/src/lib/config/platform-apply.test.ts` |
| [settings](../suites/settings.md) | Managed Compose failures identify validation or startup and preserve pending runtime receipts without exposing private inputs | ✅ automated | `tools/cli/src/lib/deployment/runtime-command.test.ts` (exit/exception paths, safe fallback and failure propagation through the real runtime orchestration with injected Docker responses) |
Expand Down
6 changes: 6 additions & 0 deletions services/sandbox-runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ which the history present at attachment has been delivered. Session idle and
TTL cleanup atomically checks the current work generation and activity clock
before freezing compute; see the [session contract](../sandbox/docs/sessions.md).

Completed commands release their request and consumer data even while another
command keeps the session active. Process cleanup retains only the ownership
and liveness data it still needs. Held-open stdin has an 8 MiB pending-write
ceiling: a nonreading command refuses further lines with `WRITE_FAILED` until
its pipe drains, without partially accepting the refused line.

File staging streams each URL into a temporary file beside its destination
and replaces the destination only after a complete, bounded download. Cancelling
or failing a download preserves the previous file. At most two stage requests
Expand Down
234 changes: 234 additions & 0 deletions services/sandbox-runtime/daemon/src/exec-manager.memory.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
// Production Node owns child-process buffers and closure lifetimes. Run the
// bundled manager there so Bun's different stream implementation cannot hide
// retained requests or an unbounded held-stdin queue.
import { afterAll, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';

const roots: string[] = [];
afterAll(() => {
for (const root of roots) rmSync(root, { recursive: true, force: true });
});

async function runInNode(body: string, withHttpServer = false): Promise<void> {
const root = realpathSync(mkdtempSync(`${tmpdir()}/runnerd-memory-`));
roots.push(root);
writeFileSync(
`${root}/entry.ts`,
`import assert from 'node:assert/strict';
import { writeFileSync } from 'node:fs';
import { ExecManager } from ${JSON.stringify(`${import.meta.dir}/exec-manager.ts`)};
import { EnvStore } from ${JSON.stringify(`${import.meta.dir}/env-store.ts`)};
import { RUNNERD_MAX_REQUEST_BODY_BYTES } from ${JSON.stringify(`${import.meta.dir}/protocol.ts`)};
process.env.TALE_WORKSPACE_ROOT = ${JSON.stringify(root)};
const root = ${JSON.stringify(root)};
const base = { timeoutMs: 30000, stdoutMaxBytes: 0, stderrMaxBytes: 0 };
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
${body}`,
);
const built = await Bun.build({
// Keep main separate so its entry-file check does not listen on import.
entrypoints: [
`${root}/entry.ts`,
...(withHttpServer ? [`${import.meta.dir}/main.ts`] : []),
],
outdir: `${root}/dist`,
target: 'node',
naming: '[name].js',
});
expect(built.success).toBe(true);
const result = spawnSync('node', ['--expose-gc', `${root}/dist/entry.js`], {
encoding: 'utf8',
timeout: 15_000,
});
expect({
status: result.status,
error: result.error,
stderr: result.stderr,
}).toEqual({
status: 0,
error: undefined,
stderr: '',
});
}

describe('ExecManager memory under Node', () => {
for (const consumerMode of ['exec', 'attach'] as const) {
test(`a disconnected HTTP ${consumerMode} consumer is collected while its exec keeps running`, async () => {
await runInNode(
String.raw`
const consumerMode = ${JSON.stringify(consumerMode)};
process.env.TALE_RUNNERD_TOKEN = '';
const { request } = await import('node:http');
const mainUrl = new URL('./main.js', import.meta.url);
const { server } = await import(mainUrl.href);
const refs = [];
server.prependListener('request', (req, res) => {
if (refs.length === 0 && (consumerMode === 'exec' ? req.method === 'POST' && req.url === '/execs' : req.url === '/execs/http-consumer/attach')) {
refs.push(new WeakRef(req), new WeakRef(res));
// Keep replay waiting on its real Node drain/abort promise until the
// client disconnects, even when loopback would otherwise drain at once.
if (consumerMode === 'attach') Object.defineProperty(res, 'writableNeedDrain', { value: true });
}
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const url = 'http://127.0.0.1:' + server.address().port;
const execId = 'http-consumer';
async function disconnect() {
await new Promise((resolve, reject) => {
const payload = JSON.stringify({
...base, execId,
command: [process.execPath, '-e', "process.stdin.resume(); process.stdin.on('end', () => { process.stdout.write('ready\\n'); setTimeout(() => {}, 30000); })"],
stdinBase64: Buffer.alloc(1024 * 1024, 120).toString('base64'),
});
const client = request(url + '/execs', {
method: 'POST', agent: false,
headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) },
});
client.once('error', reject);
client.once('response', response => {
let received = '';
response.setEncoding('utf8');
response.on('data', chunk => {
received += chunk;
if (!received.includes('"t":"stdout"')) return;
response.removeAllListeners('data');
response.destroy();
client.destroy();
resolve();
});
});
client.end(payload);
});
}
async function disconnectReplay() {
await new Promise((resolve, reject) => {
const client = request(url + '/execs/' + execId + '/attach', { agent: false });
client.once('error', reject);
client.once('response', response => {
response.once('data', () => {
assert(refs[1].deref()?.listenerCount('drain') > 0, 'replay must be waiting for drain before disconnect');
response.destroy();
client.destroy();
resolve();
});
});
client.end();
});
}
const status = async () => (await fetch(url + '/execs/' + execId)).json();
try {
await disconnect();
if (consumerMode === 'attach') await disconnectReplay();
assert.equal(refs.length, 2);
let retained = refs.length;
for (let round = 0; round < 30; round++) {
// A dereference roots its target until this job ends: await BEFORE GC.
await wait(10);
global.gc();
retained = refs.filter(ref => ref.deref() !== undefined).length;
if (retained === 0) break;
}
assert.equal(retained, 0, 'detached request/response must not survive through the abort reason stack');
assert.equal((await status()).state, 'running');
const health = await (await fetch(url + '/healthz')).json();
assert.equal(health.activity.activeOperations, 0);
// Only the first attach is stalled; the next consumer must replay normally.
const response = await fetch(url + '/execs/' + execId + '/attach');
assert.equal(response.status, 200);
const output = response.text();
const cancellation = await (await fetch(url + '/execs/' + execId + '/cancel', { method: 'POST' })).json();
assert.equal(cancellation.killed, true);
const events = (await output).trim().split('\n').map(line => JSON.parse(line));
assert(events.some(event => event.t === 'stdout' && Buffer.from(event.b64, 'base64').toString().includes('ready')));
assert(events.some(event => event.t === 'exit' && event.cancelled));
assert.equal((await status()).state, 'exited');
} finally {
await fetch(url + '/execs/' + execId + '/cancel', { method: 'POST' }).then(response => response.json());
server.closeAllConnections();
await new Promise(resolve => server.close(resolve));
}
`,
true,
);
}, 20_000);
}

test('completed requests and consumers are released while sibling and shim pipes remain live', async () => {
await runInNode(String.raw`
const shim = root + '/shim';
writeFileSync(shim, '#!/bin/sh\nshift\nprintf "pid %s\\n" "$$" >&3\n"$@"\ncode=$?\nprintf "exit %s\\n" "$code" >&3\nif [ "$TALE_EXEC_ID" = background ]; then printf partial >&3; sleep 30; fi\nexit "$code"\n', { mode: 0o755 });
const manager = new ExecManager(new EnvStore(), () => {}, undefined, {}, { execShim: shim });
const running = manager.run({ ...base, execId: 'sibling', command: ['sleep', '30'] }, () => {});
const refs = [];
let shimPid;
async function complete(execId) {
const request = { ...base, execId, command: ['/bin/sh', '-c', 'cat >/dev/null; echo "$PPID"'], stdinBase64: Buffer.alloc(1024 * 1024, 120).toString('base64') };
const emit = event => {
if (execId === 'background' && event.t === 'stdout') shimPid = Number(Buffer.from(event.b64, 'base64').toString().trim());
};
refs.push(new WeakRef(request), new WeakRef(emit));
await manager.run(request, emit);
}
try {
// Exceed the recent replay window; the completed shim targets stay deferred.
for (let i = 0; i < 20; i++) await complete('done-' + i);
await complete('background');
assert.equal(manager.liveCount(), 1);
assert.equal(manager.leftoverCount(), 21);
assert.equal(manager.canAttach('done-0'), false);
process.kill(shimPid, 0);
let retained = refs.length;
for (let i = 0; i < 20; i++) {
await wait(10);
global.gc();
retained = refs.filter(ref => ref.deref() !== undefined).length;
if (retained === 0) break;
}
assert.equal(retained, 0, 'completed requests/consumers must not be retained by leftovers or open pipes');
} finally {
if (shimPid > 1) process.kill(-shimPid, 'SIGKILL');
manager.cancel('sibling');
await running;
manager[Symbol.dispose]();
}
`);
}, 20_000);

test('held stdin refuses excess input before queuing it and accepts again after draining', async () => {
await runInNode(String.raw`
const manager = new ExecManager(new EnvStore(), () => {});
const ready = root + '/ready';
let outputBytes = 0;
const running = manager.run({ ...base, execId: 'input', stdinMode: 'hold', command: ['/bin/sh', '-c', 'while [ ! -f "$1" ]; do sleep 0.01; done; exec cat', 'sh', ready] }, event => {
if (event.t === 'stdout') outputBytes += Buffer.from(event.b64, 'base64').length;
});
try {
const line = JSON.stringify({ message: 'x'.repeat(60000) }) + '\n';
const b64 = Buffer.from(line).toString('base64');
let accepted = 0;
for (let i = 0; i < 1000; i++) {
const response = manager.writeStdin('input', { b64 });
if (response.ok) accepted++;
else assert.equal(response.reason, 'WRITE_FAILED');
}
assert(accepted > 0);
assert(accepted <= Math.ceil(RUNNERD_MAX_REQUEST_BODY_BYTES / Buffer.byteLength(line)) + 1, 'stdin accepted an unbounded queue');
assert.deepEqual(manager.writeStdin('input', { b64, eof: true }), { ok: false, reason: 'WRITE_FAILED' });
writeFileSync(ready, 'ready');
const expected = accepted * Buffer.byteLength(line);
for (let i = 0; i < 500 && outputBytes !== expected; i++) await wait(10);
assert.equal(outputBytes, expected, 'refused bytes must not enter the pipe');
const tail = Buffer.from('{"tail":true}\n');
assert.deepEqual(manager.writeStdin('input', { b64: tail.toString('base64'), eof: true }), { ok: true });
await running;
assert.equal(outputBytes, expected + tail.length);
} finally {
manager.cancel('input');
await running;
manager[Symbol.dispose]();
}
`);
}, 20_000);
});
55 changes: 55 additions & 0 deletions services/sandbox-runtime/daemon/src/exec-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1043,6 +1043,61 @@ describe('ExecManager', () => {
}
}, 30_000);

test('the primary consumer detaches without stopping the exec or its other subscribers', async () => {
using mgr = new ExecManager(new EnvStore(), () => {});
const primary = collect();
const controller = new AbortController();
const done = mgr.run(
{
...base,
execId: 'primary-drop',
command: ['cat'],
cwd: ROOT,
stdinMode: 'hold',
},
primary.emit,
controller.signal,
);
const follower = collect();
const attached = mgr.attach('primary-drop', follower.emit);
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(1);
controller.abort();
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);
const before = primary.events.length;
expect(mgr.status('primary-drop')?.state).toBe('running');
expect(
mgr.writeStdin('primary-drop', {
b64: Buffer.from('{"after":"disconnect"}\n').toString('base64'),
eof: true,
}),
).toEqual({ ok: true });
await done;
await attached;
expect(primary.events).toHaveLength(before);
expect(decode(follower.events, 'stdout')).toBe('{"after":"disconnect"}\n');
expect(follower.events.at(-1)?.t).toBe('exit');
const replay = collect();
await mgr.attach('primary-drop', replay.emit);
// The journal's catch-up marker records a different boundary for an
// attach during execution versus one after exit. Recorded events match.
expect(replay.events.filter((event) => event.seq !== undefined)).toEqual(
follower.events.filter((event) => event.seq !== undefined),
);
});

test('primary consumer abort listeners are removed on exit and spawn failure', async () => {
using mgr = new ExecManager(new EnvStore(), () => {});
for (const command of [['true'], [`${ROOT}/missing-command`]]) {
const controller = new AbortController();
await mgr.run(
{ ...base, execId: 'primary-cleanup', command, cwd: ROOT },
() => {},
controller.signal,
);
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);
}
});

test('a consumer that goes away stops following and settles its attach at once', async () => {
using mgr = new ExecManager(new EnvStore(), () => {});
const { emit } = collect();
Expand Down
Loading