Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(dev): tear down profile-gated containers in crbn down

Raul2d1a5eae17e9
diff --git a/packages/dev/src/services/compose.test.ts b/packages/dev/src/services/compose.test.ts
new file mode 100644
index 0000000000..7ed8b2c8e0
--- /dev/null
+++ b/packages/dev/src/services/compose.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from "vitest";
+import { buildDownArgs, buildUpArgs } from "./compose.js";
+
+// The teardown itself talks to the Docker daemon and isn't unit-testable. What
+// IS testable — and what a mistake here actually costs — is the profile set on
+// the `down` argv. Compose treats a profile-gated service as "defined but not
+// enabled" rather than an orphan, so a `down` missing a profile exits 0 having
+// silently left those containers running. They accumulate per worktree until a
+// Docker restart recreates the project network, at which point the stale
+// containers hold a dead network id and the next `crbn up` fails with
+// "network <id> not found".
+
+const ROOT = "/tmp/carbon-worktree";
+const SLUG = "carbon-test";
+
+/** Values of every `--profile <name>` pair in an argv array. */
+function profilesIn(args: string[]): string[] {
+ return args.flatMap((arg, i) => {
+ const value = args[i + 1];
+ return arg === "--profile" && value !== undefined ? [value] : [];
+ });
+}
+
+describe("buildDownArgs", () => {
+ it("enables every profile that buildUpArgs can enable", () => {
+ // Union of the profiles reachable from any `crbn up` invocation.
+ const bootable = new Set([
+ ...profilesIn(buildUpArgs(ROOT, SLUG)),
+ ...profilesIn(buildUpArgs(ROOT, SLUG, { chrome: true })),
+ ...profilesIn(buildUpArgs(ROOT, SLUG, { minimal: true }))
+ ]);
+ const tearable = new Set(profilesIn(buildDownArgs(ROOT, SLUG, false)));
+
+ for (const profile of bootable) {
+ expect(
+ tearable.has(profile),
+ `up can boot --profile ${profile} but down never enables it — those containers would survive teardown`
+ ).toBe(true);
+ }
+ });
+
+ it("covers the profile-gated services by name", () => {
+ // Guards against the union test passing vacuously if buildUpArgs ever
+ // stops pushing profiles at all. `full` = studio/meta/inbucket,
+ // `chrome` = the opt-in thumbnail Chromium (`crbn up --thumbnails`).
+ expect(profilesIn(buildDownArgs(ROOT, SLUG, false))).toEqual(
+ expect.arrayContaining(["full", "chrome"])
+ );
+ });
+
+ it("preserves volumes unless explicitly asked to remove them", () => {
+ // A stray -v here silently destroys a developer's local database.
+ expect(buildDownArgs(ROOT, SLUG, false)).not.toContain("-v");
+ expect(buildDownArgs(ROOT, SLUG, true)).toContain("-v");
+ });
+
+ it("still removes orphans", () => {
+ expect(buildDownArgs(ROOT, SLUG, false)).toContain("--remove-orphans");
+ });
+});
+
+describe("buildUpArgs", () => {
+ // Locking in the pre-existing boot behavior, which the extraction preserved.
+ it("enables the full profile by default", () => {
+ expect(profilesIn(buildUpArgs(ROOT, SLUG))).toEqual(["full"]);
+ });
+
+ it("drops the full profile under --minimal", () => {
+ expect(profilesIn(buildUpArgs(ROOT, SLUG, { minimal: true }))).toEqual([]);
+ });
+
+ it("adds the chrome profile only when asked", () => {
+ expect(profilesIn(buildUpArgs(ROOT, SLUG, { chrome: true }))).toEqual([
+ "full",
+ "chrome"
+ ]);
+ });
+
+ it("activates no profiles when specific services are named", () => {
+ // Compose starts named services plus dependencies regardless of profiles;
+ // activating them here would pull in unrelated containers.
+ const args = buildUpArgs(ROOT, SLUG, {
+ services: ["postgres"],
+ chrome: true
+ });
+ expect(profilesIn(args)).toEqual([]);
+ expect(args).toContain("postgres");
+ });
+});
diff --git a/packages/dev/src/services/compose.ts b/packages/dev/src/services/compose.ts
index 1c71cf3f31..2ff6b1dd21 100644
--- a/packages/dev/src/services/compose.ts
+++ b/packages/dev/src/services/compose.ts
@@ -53,11 +53,20 @@ export type Container = {
// Lifecycle
// ---------------------------------------------------------------------------
-export async function bootStack(
+// Every profile any `bootStack` call can enable. Teardown must activate all of
+// them: compose treats a profile-gated service as "defined but not enabled"
+// rather than an orphan, so a `down` without the profile skips those
+// containers entirely — `--remove-orphans` does not catch them either.
+// Keep this in sync when adding a profile to the compose file; the residual
+// sweep in `stopStack` is the backstop if it ever falls behind.
+const COMPOSE_PROFILES = ["full", "chrome"] as const;
+
+// Exported for tests: the exact `docker compose … up -d` argv.
+export function buildUpArgs(
root: string,
slug: string,
opts?: { minimal?: boolean; services?: string[]; chrome?: boolean }
-) {
+): string[] {
const args = devArgs(root, slug, "--env-file", ".env.local");
// When specific services are requested, don't activate profiles — compose
// starts only the named services (+ dependencies) regardless of profiles.
@@ -66,7 +75,31 @@ export async function bootStack(
if (!opts?.services && opts?.chrome) args.push("--profile", "chrome");
args.push("up", "-d");
if (opts?.services) args.push(...opts.services);
- await execStrict("docker", args, root);
+ return args;
+}
+
+// Exported for tests: the exact `docker compose … down` argv. Enables every
+// profile unconditionally — a profile that was never booted simply matches no
+// running containers, so over-enabling on teardown is free, while
+// under-enabling silently leaks containers.
+export function buildDownArgs(
+ root: string,
+ slug: string,
+ withVolumes: boolean
+): string[] {
+ const args = devArgs(root, slug, "--env-file", ".env.local");
+ for (const profile of COMPOSE_PROFILES) args.push("--profile", profile);
+ args.push("down", "--remove-orphans");
+ if (withVolumes) args.push("-v");
+ return args;
+}
+
+export async function bootStack(
+ root: string,
+ slug: string,
+ opts?: { minimal?: boolean; services?: string[]; chrome?: boolean }
+) {
+ await execStrict("docker", buildUpArgs(root, slug, opts), root);
}
// `docker compose restart` a subset of services. Used by the storage-stuck
@@ -177,27 +210,49 @@ export async function allImagesPresentLocally(
// failures (missing .env.local, profile issues, renamed compose file), falls
// back to raw `docker rm -f` via destroyProject so the stack is always torn
// down even when compose can't parse the project to find its containers.
+//
+// The fallback is keyed on containers actually remaining, NOT on the exit code
+// alone: compose exits 0 after a teardown that skipped services it had no
+// profile for, so a partial teardown looks like a success and would otherwise
+// leave those containers running until the next Docker restart turned them
+// into a stale-network boot failure.
export async function stopStack(
root: string,
slug: string,
withVolumes: boolean
): Promise<number> {
- const args = devArgs(
- root,
- slug,
- "--env-file",
- ".env.local",
- "down",
- "--remove-orphans"
- );
- if (withVolumes) args.push("-v");
- const r = await execa("docker", args, { cwd: root, reject: false });
- if (r.exitCode !== 0) {
- await destroyProject(projectName(slug), withVolumes);
+ const r = await execa("docker", buildDownArgs(root, slug, withVolumes), {
+ cwd: root,
+ reject: false
+ });
+ const project = projectName(slug);
+ const leftovers = await projectContainerIds(project);
+ if (r.exitCode !== 0 || leftovers.length > 0) {
+ await destroyProject(project, withVolumes);
}
return r.exitCode ?? 0;
}
+// Container ids belonging to a compose project, found by label so it works
+// even when the compose file or worktree directory is gone.
+async function projectContainerIds(project: string): Promise<string[]> {
+ const r = await execa(
+ "docker",
+ [
+ "ps",
+ "-a",
+ "-q",
+ "--filter",
+ `label=com.docker.compose.project=${project}`
+ ],
+ { reject: false }
+ );
+ return (r.stdout ?? "")
+ .split("\n")
+ .map((s) => s.trim())
+ .filter(Boolean);
+}
+
// One redis per host, run directly via `docker run` (no compose file).
// Idempotent: reuse a running container, start a stopped one, otherwise create.
export async function bootSharedRedis() {
@@ -405,21 +460,7 @@ export async function dockerProjectStates(): Promise<Map<string, string>> {
// false (plain `crbn down`), preserves the project's data volumes.
export async function destroyProject(project: string, withVolumes = true) {
// Find containers belonging to the project.
- const ctr = await execa(
- "docker",
- [
- "ps",
- "-a",
- "-q",
- "--filter",
- `label=com.docker.compose.project=${project}`
- ],
- { reject: false }
- );
- const ids = (ctr.stdout ?? "")
- .split("\n")
- .map((s) => s.trim())
- .filter(Boolean);
+ const ids = await projectContainerIds(project);
if (ids.length > 0) {
await execa("docker", ["rm", "-f", ...ids], {
reject: false,