DEV Community

Sandscale
Sandscale

Posted on Originally published at sandscale.dev

Use case: testing the code snippets in your docs, one sandbox per page

Every documentation site has examples that stopped working months ago. A renamed function, a changed default, a dependency that moved, and the snippet in your quickstart now throws. Nobody notices until a new user does, and by then their first impression is a stack trace.

The fix is to run your docs. The trick is running them somewhere that is clean every time, so a snippet does not pass only because a previous one left a file behind, and safe, so a rm -rf in a bash example cannot touch your CI runner. This use case runs each docs page's snippets in its own Sandscale sandbox.

Mark what should run

Not every code block is meant to run: some are fragments, some are output, some need credentials. Opt in explicitly by adding test to the fence:

```python test
from mylib import parse
assert parse("P1D") == 86400
```
Enter fullscreen mode Exit fullscreen mode

Snippets on one page run in order in the same sandbox, so a later block can use a file or variable an earlier block set up, exactly as a reader following the page would.

The runner

Type-checked with tsc --strict against @sandscale/sdk 1.0. The Sandscale calls are sandboxes.create, writeFile, run and stop from the TypeScript SDK reference.

import { readFile, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { Sandscale } from '@sandscale/sdk';

const sandscale = new Sandscale(); // reads SANDSCALE_API_KEY

interface Snippet {
  file: string;
  line: number;
  lang: 'python' | 'bash' | 'js';
  code: string;
}

// Only fences marked "test" run, e.g. ```
{% endraw %}
python test
const FENCE = /^
{% raw %}
```(python|bash|js) test\s*$/;

export function extractSnippets(file: string, text: string): Snippet[] {
  const lines = text.split('\n');
  const out: Snippet[] = [];
  for (let i = 0; i < lines.length; i++) {
    const m = lines[i].match(FENCE);
    if (!m) continue;
    const start = i + 1;
    const body: string[] = [];
    for (i = start; i < lines.length && !lines[i].startsWith('```
{% endraw %}
'); i++) body.push(lines[i]);
    out.push({ file, line: start, lang: m[1] as Snippet['lang'], code: body.join('\n') + '\n' });
  }
  return out;
}

const RUNNERS: Record<Snippet['lang'], { path: string; cmd: string[] }> = {
  python: { path: '/workspace/snippet.py', cmd: ['python3', '/workspace/snippet.py'] },
  bash: { path: '/workspace/snippet.sh', cmd: ['bash', '-euo', 'pipefail', '/workspace/snippet.sh'] },
  js: { path: '/workspace/snippet.mjs', cmd: ['node', '/workspace/snippet.mjs'] },
};

export interface Failure {
  where: string;
  exitCode: number;
  timedOut: boolean;
  stderr: string;
}

// One sandbox per page: snippets on a page often build on each other, pages never do.
export async function testPage(file: string, snippets: Snippet[], template: string): Promise<Failure[]> {
  const sb = await sandscale.sandboxes.create({
    template,
    timeoutSeconds: 900,
    labels: { app: 'docs-snippet-tests' },
  });
  const failures: Failure[] = [];
  try {
    for (const s of snippets) {
      const runner = RUNNERS[s.lang];
      await sandscale.sandboxes.writeFile(sb.id, runner.path, s.code, { region: sb.region });
      const r = await sandscale.sandboxes.run(sb.id, runner.cmd, {
        region: sb.region,
        workdir: '/workspace',
        timeoutSeconds: 120,
      });
      if (r.exitCode !== 0 || r.timedOut) {
        failures.push({
          where: {% raw %}`${s.file}:${s.line}`,
          exitCode: r.exitCode,
          timedOut: r.timedOut,
          stderr: r.stderr.slice(-2_000),
        });
        break; // later snippets on the page usually depend on this one
      }
    }
  } finally {
    await sandscale.sandboxes.stop(sb.id, { region: sb.region });
  }
  return failures;
}

// Free allows 3 boxes at once, Pro and Team 30: keep concurrency within your plan.
export async function main(docsDir: string, template = 'builtin:python', concurrency = 3) {
  const files = (await readdir(docsDir, { recursive: true })).filter((f) => f.endsWith('.md'));
  const pages: { f: string; snippets: Snippet[] }[] = [];
  for (const f of files) {
    const snippets = extractSnippets(f, await readFile(join(docsDir, f), 'utf8'));
    if (snippets.length) pages.push({ f, snippets });
  }
  const failures: Failure[] = [];
  let next = 0;
  const worker = async () => {
    while (next < pages.length) {
      const p = pages[next++];
      failures.push(...(await testPage(p.f, p.snippets, template)));
    }
  };
  await Promise.all(Array.from({ length: Math.min(concurrency, pages.length) }, worker));
  for (const fl of failures) {
    console.error(`FAIL ${fl.where} exit=${fl.exitCode}${fl.timedOut ? ' (timed out)' : ''}\n${fl.stderr}\n`);
  }
  console.log(`${pages.length} pages, ${failures.length} failing`);
  process.exitCode = failures.length ? 1 : 0;
}


Enter fullscreen mode Exit fullscreen mode

Why it is built this way

One sandbox per page, not per snippet. Pages are written to be followed top to bottom; snippets build on each other. Pages are independent, so each gets a fresh box, and nothing from the install guide leaks into the API reference.

Stop at the first failure on a page. Later snippets usually depend on the one that failed, so their errors would be noise. The report points at the first broken one, by file and the line of its opening fence.

Bash runs strict. bash -euo pipefail makes a failing command in the middle of a shell example fail the snippet, instead of being hidden by a later echo.

Each snippet has a time limit. timeoutSeconds: 120 per run. A snippet that waits on input or loops forever fails with timedOut, which the report shows.

Concurrency within your plan. Boxes at once are a plan limit: 3 on Free, 30 on Pro and Team, per the plans reference. The runner keeps a fixed number of workers, 3 by default. Raise it on a paid plan for a big docs tree.

The sandbox has no network. It is created without a network option, and the SDK's default is none. That is a feature here: a snippet that silently depends on downloading something is a snippet that will break for readers behind a proxy. If your examples legitimately need the network, use your organization's allowlist where your plan includes it.

Getting your library into the box

The snippets need the thing they document. Three options, from simplest:

  1. Write it in. If your library is a few files, writeFile them into /workspace at the start of testPage.
  2. A snapshot. Prepare one sandbox with your package installed under /workspace, call sandboxes.snapshot, and pass snapshotId instead of a template. Every page starts from that state. Starting agent runs from a prepared snapshot shows the pattern.
  3. A template. Register your own OCI image, pinned by digest, as an organization template with your package and its dependencies installed.

In CI

Run it on every pull request that touches docs or the library, with the API key in your CI secrets. A two-line entry file that calls main(process.argv[2]) is enough:


bash
npx tsx test-docs.ts ./docs


Enter fullscreen mode Exit fullscreen mode

main sets a nonzero exit code when any page fails, so the job fails. Keep the key's scopes to creating and using sandboxes; see scoping API keys.

Variations

  • Check output, not just exit codes. Add an # expect: comment convention and compare the snippet's stdout.
  • Several languages per page. The RUNNERS table maps a fence language to a file and command. Add go with builtin:go, or TypeScript with a template that has your toolchain.
  • Docs written by agents. If an agent drafts or updates your docs, run this before merge. It is a cheap way to catch an example that looks right and is not.

Cost

Each page's sandbox uses awake vCPU-hours only while it runs. A docs tree of a few dozen pages with short snippets uses a small slice of the Free plan's 100 hours a month.

Originally published on the Sandscale blog.

Top comments (0)