Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

fix(upgrade): stop telling people to upgrade a backend that is current (#466)

KageBinary671d98c5577c
diff --git a/ix-cli/src/cli/__tests__/upgrade-backend-stamp.test.ts b/ix-cli/src/cli/__tests__/upgrade-backend-stamp.test.ts
new file mode 100644
index 00000000..4c341bbb
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/upgrade-backend-stamp.test.ts
@@ -0,0 +1,800 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { MockInstance } from "vitest";
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+// stampBackendVersionAfterPull is imported dynamically below instead: it reads
+// IX_HOME at module load, so it has to be loaded after the tests set one.
+import {
+ VERSION_RE,
+ backendUpdateAvailable,
+ composeTracksLatestBackend,
+ stampDisagreesWithPull,
+ writeVersionStamp,
+} from "../commands/upgrade.js";
+
+/**
+ * Can a 0444 file actually refuse a write here?
+ *
+ * Two ways it cannot: root bypasses the mode, and some filesystems drop it
+ * entirely (a WSL /mnt/c drvfs mount without metadata, CIFS, exFAT). Only the
+ * first is a property of the process; the second has to be measured. So this
+ * measures — on its OWN throwaway file, never on a fixture, which is what
+ * made the runtime probe this replaces unsound: that one wrote to the stamp
+ * under test to find out, and swallowed the PendingError that `ctx.skip`
+ * throws, so under root it reported "refused" for a write that had succeeded.
+ *
+ * Deliberately not `platform !== "win32" && getuid() !== 0` as in
+ * mcp-install.test.ts: that file needs a READ to fail where a write would
+ * not, which is POSIX-only. A write refusal is not — Node maps 0444 to
+ * FILE_ATTRIBUTE_READONLY and `writeFileSync` throws EPERM on Windows, so
+ * skipping there would drop the whole gate on windows-2022 for nothing.
+ */
+const modeProbe = (() => {
+ // mkdtemp, not a name built from the pid: a predictable path in the shared
+ // temp dir is one an attacker can pre-create as a symlink, and CodeQL flags
+ // it (js/insecure-temporary-file). It also gives each vitest worker and each
+ // parallel CI job its own directory, so the probes cannot collide.
+ const code = (err: unknown) => (err as NodeJS.ErrnoException)?.code ?? "unknown";
+ let dir: string | undefined;
+ let probe: string | undefined;
+ let blocked = false;
+ let why = "";
+ try {
+ dir = mkdtempSync(join(tmpdir(), "ix-mode-probe-"));
+ probe = join(dir, "probe");
+ writeFileSync(probe, "x");
+ try {
+ chmodSync(probe, 0o444);
+ } catch (err) {
+ // Distinct from an unusable temp dir: the directory is fine, chmod is
+ // what is missing (ENOSYS on some FUSE/9p/noacl mounts). Saying "could
+ // not probe the temp dir" here sends the reader after disk space.
+ // Returning rather than throwing-to-be-caught-below: the finally still
+ // runs, so both cleanups still happen, and the message survives a catch
+ // that would otherwise overwrite it.
+ return { blocked: false, why: `chmod is unavailable here (${code(err)})` };
+ }
+ // ATTEMPT THE WRITE. Reading `mode & 0o200` only says the bit was
+ // recorded, which it is for root too — root records 0444 and then
+ // bypasses it, so a bits-only check reports "blocked" for a write that
+ // will succeed, and the gate tests run and fail instead of skipping.
+ // Writing is the only thing that answers the question actually asked.
+ // Safe here and nowhere else: this file is the probe's own, not a fixture.
+ try {
+ writeFileSync(probe, "y");
+ why = "0444 did not refuse a write (running as root, or a filesystem that drops modes)";
+ } catch (err) {
+ // Only a PERMISSION refusal means the mode bit bit. ENOSPC or EMFILE
+ // between the two writes is a transient failure of the probe, and
+ // reading it as "blocked" would let the gate tests run against a
+ // writable stamp — the same misclassification the bits-only version
+ // made. (EACCES on POSIX, EPERM on Windows.)
+ if (code(err) === "EACCES" || code(err) === "EPERM") blocked = true;
+ else why = `probe write failed for an unrelated reason (${code(err)})`;
+ }
+ } catch (err) {
+ // Could not measure at all — a full or unwritable TMPDIR, EMFILE under a
+ // parallel job. Distinct from "measured, and the mode does not bite".
+ why = `could not probe the temp dir (${code(err)})`;
+ } finally {
+ if (probe) {
+ try {
+ chmodSync(probe, 0o644);
+ } catch {
+ /* best effort: the rm below clears the read-only bit itself */
+ }
+ }
+ if (dir) {
+ try {
+ rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
+ } catch {
+ // Never let cleanup of the probe fail COLLECTION: this runs at MODULE
+ // scope, so a throw here is an import error for the whole file — every
+ // test in it, including everything unrelated to file modes.
+ }
+ }
+ }
+ return { blocked, why };
+})();
+
+const modeBlocksWrite = modeProbe.blocked;
+
+/**
+ * `CI=false` is a widely used way of saying "not CI" (react-scripts, Netlify),
+ * and a bare truthiness check reads it as CI. Lower-cased because `CI=False` is
+ * the spelling a PowerShell user is most likely to export, which react-scripts
+ * also handles; `0`, `no` and `off` are the same intent spelled differently, and
+ * "0" is truthy as a string, so they need naming too.
+ */
+const onCI =
+ !!process.env.CI && !["false", "0", "no", "off"].includes(process.env.CI.toLowerCase());
+
+if (!modeBlocksWrite) {
+ // stderr directly, not console.warn: vitest's default reporter prints
+ // console output from a passing file nowhere at all — measured — so the
+ // warning would be silent on exactly the runs it exists for. A raw stderr
+ // write is not intercepted and does show up.
+ //
+ // Unconditional, NOT `&& !onCI`. Suppressing it on CI made one env-var read
+ // the only gate on both signals at once: an `onCI` that is wrongly false
+ // skips the assertion AND, with the guard, silenced this. Saying the reason
+ // twice on a CI failure is cheap; saying it nowhere is the failure this
+ // whole mechanism exists to prevent.
+ process.stderr.write(`[stamp gate skipped] ${modeProbe.why}\n`);
+}
+
+/**
+ * What the user actually sees. Both branches of `checkForUpdate` made this
+ * decision inline, so a change to one did not reach the other; it is one pure
+ * function now, and this is the only coverage of the notice itself.
+ */
+describe("backendUpdateAvailable", () => {
+ it("offers an upgrade when the release is ahead of the tracked version", () => {
+ expect(backendUpdateAvailable("1.0.16", "1.0.13")).toBe(true);
+ });
+
+ it("says nothing when the tracked version is current or ahead", () => {
+ expect(backendUpdateAvailable("1.0.16", "1.0.16")).toBe(false);
+ expect(backendUpdateAvailable("1.0.16", "1.0.17")).toBe(false);
+ });
+
+ it("says nothing when no release is known", () => {
+ // A failed or rate-limited fetch must not be read as "you are behind".
+ expect(backendUpdateAvailable(undefined, "1.0.13")).toBe(false);
+ expect(backendUpdateAvailable("", "1.0.13")).toBe(false);
+ });
+
+ it("offers the upgrade on a fresh install, where nothing is tracked", () => {
+ // getTrackedVersion returns 0.0.0 when the file is absent or empty.
+ expect(backendUpdateAvailable("1.0.16", "0.0.0")).toBe(true);
+ });
+});
+
+/**
+ * The gate on the stamp-failure warning, which is deliberately NOT the notice
+ * predicate above — and this is where the two are shown to differ, so the
+ * divergence is a decision on the record rather than an accident.
+ */
+describe("stampDisagreesWithPull", () => {
+ it("is quiet when the stamp records exactly what was pulled", () => {
+ expect(stampDisagreesWithPull("1.0.16", "1.0.16")).toBe(false);
+ });
+
+ it("fires when the stamp is behind", () => {
+ expect(stampDisagreesWithPull("1.0.13", "1.0.16")).toBe(true);
+ expect(backendUpdateAvailable("1.0.16", "1.0.13")).toBe(true); // both agree
+ });
+
+ it("fires when the stamp is AHEAD, where the notice predicate is silent", () => {
+ // The whole reason this is a separate predicate. An ahead stamp is wrong
+ // and, once the write has failed, uncorrectable — but there is no upgrade
+ // to offer, so backendUpdateAvailable says nothing.
+ expect(stampDisagreesWithPull("1.0.17", "1.0.16")).toBe(true);
+ expect(backendUpdateAvailable("1.0.16", "1.0.17")).toBe(false); // they differ
+ });
+
+ it("fires on a PRE-RELEASE stamp against the GA release of the same triple", () => {
+ // The divergence that is actually reachable, and the one a numeric-triple
+ // comparison would swallow: the notice fires here, so the warning that
+ // explains it has to as well.
+ expect(stampDisagreesWithPull("1.0.16-rc1", "1.0.16")).toBe(true);
+ expect(backendUpdateAvailable("1.0.16", "1.0.16-rc1")).toBe(true); // both agree
+ });
+
+ it("is quiet when the same release is spelled differently", () => {
+ // Compared by precedence, not as text: build metadata and leading zeros do
+ // not make a different release, and warning on them would fire on every
+ // cold start with nothing wrong.
+ expect(stampDisagreesWithPull("1.0.16+build77", "1.0.16")).toBe(false);
+ expect(stampDisagreesWithPull("1.0.16", "1.0.16+build77")).toBe(false);
+ expect(stampDisagreesWithPull("01.0.16", "1.0.16")).toBe(false);
+ });
+});
+
+/**
+ * `.backend-version` drives the "Backend update available" notice on every
+ * command. It is written at install time (install.sh, install.ps1) and by
+ * `ix upgrade` — but it was not written by `ix docker start`, which pulls
+ * `:latest` on every cold start, so a backend taken through that path left the
+ * file naming the release that was installed while running a later one, and
+ * nagged for ever.
+ *
+ * The stamp is now written wherever a pull happens, which puts the weight on
+ * this function: it runs attached to an operation the user actually asked for,
+ * against a directory that may not exist, with a version that may not be known.
+ */
+describe("writeVersionStamp", () => {
+ let home: string;
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), "ix-stamp-"));
+ });
+
+ afterEach(() => {
+ // maxRetries: this describe writes stamp files and a directory into `home`
+ // immediately before tearing it down, which is the shape that trips EBUSY
+ // on Windows.
+ rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
+ });
+
+ it("writes the version and reports that it did", () => {
+ const file = join(home, ".backend-version");
+ expect(writeVersionStamp(file, "1.0.16")).toBe(true);
+ expect(readFileSync(file, "utf-8")).toBe("1.0.16");
+ });
+
+ it("creates the directory when it does not exist yet", () => {
+ // The first install has no IX_HOME. Without the mkdir the write throws
+ // ENOENT into the catch, the tracked version stays at 0.0.0 for ever, and
+ // every command nags with nothing to say why.
+ const file = join(home, "does", "not", "exist", ".backend-version");
+ expect(existsSync(join(home, "does"))).toBe(false);
+ writeVersionStamp(file, "1.0.16");
+ expect(readFileSync(file, "utf-8")).toBe("1.0.16");
+ });
+
+ it("leaves an existing stamp alone when the version is not known", () => {
+ // Offline, rate-limited, or a release that could not be parsed. Not knowing
+ // which release we are on is not the same as being on none of them, and the
+ // only safe direction for this file is BEHIND: a stamp that reads new hides
+ // a stale backend and stops `ix upgrade` from ever fetching it.
+ const file = join(home, ".backend-version");
+ writeFileSync(file, "1.0.13");
+ for (const unknown of [null, undefined, ""]) {
+ // The return value is the contract ("whether it was written"), and the
+ // `ix upgrade` caller branches on it — so assert it, not just the file.
+ expect(writeVersionStamp(file, unknown)).toBe(false);
+ expect(readFileSync(file, "utf-8")).toBe("1.0.13");
+ }
+ });
+
+ it("writes nothing at all rather than an empty stamp on a fresh install", () => {
+ const file = join(home, ".backend-version");
+ writeVersionStamp(file, null);
+ expect(existsSync(file)).toBe(false);
+ });
+
+ it("reports a failed write instead of throwing", () => {
+ // It must not throw: the docker-start caller has already brought containers
+ // up by the time this runs. But it must not claim success either — the
+ // `ix upgrade` caller turns a false into the error the user sees, which is
+ // what stops it printing "Backend image updated" over a file that never
+ // moved on a read-only IX_HOME. A directory where the file should be is the
+ // portable way to make the write fail.
+ const file = join(home, "blocked");
+ mkdirSync(file, { recursive: true });
+ let result: boolean | undefined;
+ expect(() => {
+ result = writeVersionStamp(file, "1.0.16");
+ }).not.toThrow();
+ expect(result).toBe(false);
+ });
+});
+
+/**
+ * Stamping after a pull is only sound if the compose that was started actually
+ * tracks `:latest`. `ix docker start` falls back to ANY docker-compose.yml in
+ * the working directory, so this is what stops the stamp claiming a release for
+ * a container running a pinned tag, a digest, or a local build.
+ */
+describe("composeTracksLatestBackend", () => {
+ const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..");
+
+ it("accepts the compose file this project actually ships", () => {
+ // A drift guard. If the shipped compose ever pins a version instead of
+ // tracking :latest, stamping after a pull stops being true — and it would
+ // stop silently, since the stamp simply never gets written.
+ const shipped = readFileSync(join(REPO_ROOT, "docker-compose.standalone.yml"), "utf-8");
+ expect(composeTracksLatestBackend(shipped)).toBe(true);
+ });
+
+ it("accepts a quoted image reference", () => {
+ expect(
+ composeTracksLatestBackend(' image: "ghcr.io/ix-infrastructure/ix-memory-layer:latest"'),
+ ).toBe(true);
+ });
+
+ it("refuses a pinned version tag", () => {
+ expect(
+ composeTracksLatestBackend(" image: ghcr.io/ix-infrastructure/ix-memory-layer:1.0.13"),
+ ).toBe(false);
+ });
+
+ it("refuses a pinned digest", () => {
+ expect(
+ composeTracksLatestBackend(
+ " image: ghcr.io/ix-infrastructure/ix-memory-layer@sha256:944f76887832",
+ ),
+ ).toBe(false);
+ });
+
+ it("refuses a locally built or third-party image", () => {
+ expect(composeTracksLatestBackend(" image: ix-memory-layer:dev")).toBe(false);
+ expect(composeTracksLatestBackend(" image: arangodb:3.12")).toBe(false);
+ });
+
+ it("refuses a near-miss registry name", () => {
+ // The dots in the image name are not wildcards: this is compared, not
+ // matched. A pattern would accept this.
+ expect(
+ composeTracksLatestBackend(" image: ghcrXio/ix-infrastructure/ix-memory-layer:latest"),
+ ).toBe(false);
+ });
+
+ it("refuses a tag that merely starts with latest", () => {
+ // `:latest-debug` is a different image that a substring test would accept.
+ expect(
+ composeTracksLatestBackend(
+ " image: ghcr.io/ix-infrastructure/ix-memory-layer:latest-debug",
+ ),
+ ).toBe(false);
+ });
+
+ it("refuses the image republished under another registry", () => {
+ // Contains the wanted reference in full, so only comparing the WHOLE value
+ // rejects it — and it is a different image, pulled from somewhere we have
+ // made no claim about.
+ expect(
+ composeTracksLatestBackend(
+ " image: mirror.internal/ghcr.io/ix-infrastructure/ix-memory-layer:latest",
+ ),
+ ).toBe(false);
+ });
+
+ it("refuses a compose that names no image at all", () => {
+ expect(composeTracksLatestBackend("services:\n memory-layer:\n build: .")).toBe(false);
+ });
+});
+
+/**
+ * `stampBackendVersionAfterPull` against a real, isolated IX_HOME.
+ *
+ * The module resolves BACKEND_VERSION_FILE and VERSION_CACHE from IX_HOME at
+ * load, so IX_HOME is set and the module re-imported — without that, a
+ * regression in the early return would have this reaching api.github.com and
+ * overwriting the developer's own ~/.ix/.backend-version.
+ */
+describe("stampBackendVersionAfterPull, isolated", () => {
+ let home: string;
+ let priorHome: string | undefined;
+
+ beforeEach(() => {
+ priorHome = process.env.IX_HOME;
+ home = mkdtempSync(join(tmpdir(), "ix-stamp-home-"));
+ process.env.IX_HOME = home;
+ vi.resetModules();
+ });
+
+ afterEach(() => {
+ // Unstub and reset BEFORE the rmSync: on Windows a just-written temp tree
+ // can throw EBUSY/EPERM even with force, and anything after the throw never
+ // runs — which would leave a fake global fetch installed for the rest of
+ // the file. resetModules is here as well as in beforeEach because
+ // beforeEach is describe-scoped: without it the NEXT behavioural describe
+ // added to this file inherits this one's module instance, still bound to
+ // the IX_HOME about to be deleted, and writes into a resurrected directory.
+ // restoreAllMocks because vi.spyOn on an ALREADY-spied method hands back
+ // the existing mock, so without it a later test's `warn` still carries the
+ // earlier test's calls.
+ vi.unstubAllGlobals();
+ vi.resetModules();
+ vi.restoreAllMocks();
+ if (priorHome === undefined) delete process.env.IX_HOME;
+ else process.env.IX_HOME = priorHome;
+ // maxRetries for the same Windows EBUSY the ordering above works around:
+ // moving the unstub earlier stops it leaking, but a throw here still fails
+ // a test that passed.
+ rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
+ });
+
+ /** Re-imported so IX_HOME above is the one the module reads. */
+ const load = () => import("../commands/upgrade.js");
+
+ /** A compose the guard accepts, so the fetch-and-write path is reached. */
+ const tracksLatest = () => {
+ const compose = join(home, "docker-compose.yml");
+ writeFileSync(
+ compose,
+ "services:\n memory-layer:\n image: ghcr.io/ix-infrastructure/ix-memory-layer:latest\n",
+ );
+ return compose;
+ };
+
+ /**
+ * The release feed, stubbed — no test in here reaches the network. Each
+ * returns the mock so a test can assert the request was (or was not) made.
+ */
+ const feedReturns = (tag: string) => {
+ const fetchMock = vi.fn(async () => ({ ok: true, json: async () => ({ tag_name: tag }) }));
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+ };
+
+ /** The feed answering with an error status. */
+ const feedRefuses = () => {
+ const fetchMock = vi.fn(async () => ({ ok: false, json: async () => ({}) }));
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+ };
+
+ /** The feed unreachable — offline REJECTS, it does not answer !ok. */
+ const feedUnreachable = () => {
+ const fetchMock = vi.fn(async () => {
+ throw new Error("ENOTFOUND api.github.com");
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+ };
+
+ const stampPath = () => join(home, ".backend-version");
+
+ it("stamps nothing, and reaches no network, when the compose cannot be read", async () => {
+ // The compose read is the one call in here that can throw, and it must not
+ // escape into `ix docker start`, which has already brought containers up.
+ const fetchMock = feedReturns("v1.0.16");
+ const mod = await load();
+ await expect(
+ mod.stampBackendVersionAfterPull(join(home, "no-such-compose.yml")),
+ ).resolves.toBeUndefined();
+ expect(existsSync(stampPath())).toBe(false);
+ // The half the name claims and nothing used to check: hoisting the fetch
+ // above the compose guard passes every other assertion here.
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("stamps nothing when the compose does not track :latest", async () => {
+ // Stubbed so a regression in the guard is caught here rather than quietly
+ // reaching the network — which is what made this test pass offline with the
+ // guard deleted, and vacuous exactly where CI is sandboxed.
+ const fetchMock = feedReturns("v1.0.16");
+ const compose = join(home, "docker-compose.yml");
+ writeFileSync(compose, "services:\n memory-layer:\n image: ix-memory-layer:dev\n");
+ const mod = await load();
+ await mod.stampBackendVersionAfterPull(compose);
+ expect(existsSync(stampPath())).toBe(false);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("records a release carrying build metadata verbatim", async () => {
+ // The control for the wiring pin below. That test proves the call site
+ // stays QUIET for a build-metadata tag — which is also what happens if the
+ // tag never arrives at all, because `fetchLatestRelease` rejected it and
+ // `latest` came back null. Asserting VERSION_RE accepts the spelling is not
+ // enough: a `.replace(/\+.*$/, "")` added to the strip would keep that
+ // assertion green and still empty the pin. This is the one that fails,
+ // because it asserts the metadata reached the FILE.
+ const fetchMock = feedReturns("v1.0.16+build77");
+ const mod = await load();
+ await mod.stampBackendVersionAfterPull(tracksLatest());
+ expect(fetchMock).toHaveBeenCalled();
+ expect(readFileSync(stampPath(), "utf-8")).toBe("1.0.16+build77");
+ });
+
+ it("records the release it just pulled", async () => {
+ // The behaviour this whole change exists to add. Without it, gutting the
+ // write entirely leaves every other test in this file green.
+ const fetchMock = feedReturns("v1.0.16");
+ const mod = await load();
+ await mod.stampBackendVersionAfterPull(tracksLatest());
+ expect(fetchMock).toHaveBeenCalled();
+ expect(readFileSync(stampPath(), "utf-8")).toBe("1.0.16");
+ });
+
+ it("overwrites a stamp that had got ahead of the real release", async () => {
+ // Self-heal in the other direction. The GHCR tag and the release feed are
+ // published separately, so the file can legitimately read high; a
+ // never-go-backwards rule would pin it there and silence the notice for
+ // good.
+ writeFileSync(stampPath(), "1.0.17");
+ feedReturns("v1.0.16");
+ const mod = await load();
+ await mod.stampBackendVersionAfterPull(tracksLatest());
+ expect(readFileSync(stampPath(), "utf-8")).toBe("1.0.16");
+ });
+
+ it("leaves the stamp alone, and says nothing, when the feed refuses", async () => {
+ writeFileSync(stampPath(), "1.0.13");
+ const fetchMock = feedRefuses();
+ const warn = vi.spyOn(console, "error").mockImplementation(() => {});
+ const mod = await load();
+ await mod.stampBackendVersionAfterPull(tracksLatest());
+ expect(fetchMock).toHaveBeenCalled();
+ expect(readFileSync(stampPath(), "utf-8")).toBe("1.0.13");
+ // `latest &&` is the only thing stopping a warning here: the gate compares
+ // strings, and a tracked version never equals null.
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("leaves the stamp alone, and says nothing, when the feed is unreachable", async () => {
+ // Offline REJECTS; it does not answer with `ok: false`. Both converge on
+ // `latest === null` here — this covers the offline shape, it does NOT prove
+ // where the rejection is caught, since fetchLatestRelease's own catch and
+ // the outer catch are observationally identical from out here.
+ writeFileSync(stampPath(), "1.0.13");
+ const fetchMock = feedUnreachable();
+ const warn = vi.spyOn(console, "error").mockImplementation(() => {});
+ const mod = await load();
+ await expect(mod.stampBackendVersionAfterPull(tracksLatest())).resolves.toBeUndefined();
+ expect(fetchMock).toHaveBeenCalled();
+ expect(readFileSync(stampPath(), "utf-8")).toBe("1.0.13");
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("says why when the stamp cannot be written and the file is wrong", async () => {
+ // The user's backend notices are about to be wrong and this is the only
+ // thing that explains it. A directory where the file belongs makes the
+ // write fail portably, and makes getTrackedVersion read 0.0.0.
+ mkdirSync(stampPath(), { recursive: true });
+ const fetchMock = feedReturns("v1.0.16");
+ const warn = vi.spyOn(console, "error").mockImplementation(() => {});
+ const mod = await load();
+ await mod.stampBackendVersionAfterPull(tracksLatest());
+ expect(fetchMock).toHaveBeenCalled();
+ expectStampFailure(warn);
+ });
+
+ /**
+ * A stamp that is READABLE but not writable — the case the gate's comment
+ * actually describes ("a root-owned stamp already holding what we just
+ * pulled"). The directory trick cannot produce it: a directory always reads
+ * as 0.0.0, which forces the feed to return "0.0.0" to make the two agree,
+ * and no release is ever 0.0.0.
+ */
+ const unwritableStamp = (contents: string) => {
+ writeFileSync(stampPath(), contents);
+ chmodSync(stampPath(), 0o444);
+ };
+
+ /**
+ * The one message both failure paths print. Asserts the call COUNT too: only
+ * `calls[0]` is inspected, so without it a run where console.error fired twice
+ * — the real message plus an unrelated regression — would still pass.
+ */
+ const expectStampFailure = (warn: MockInstance) => {
+ expect(warn).toHaveBeenCalledTimes(1);
+ const said = String(warn.mock.calls[0]?.[0]);
+ expect(said).toContain(".backend-version"); // which file, the actionable half
+ expect(said).toContain("backend update notices will be wrong"); // and why it matters
+ };
+
+ it.skipIf(!modeBlocksWrite)(
+ "stays quiet when the stamp cannot be written but already records what we pulled",
+ async () => {
+ // Warning here would be noise on every cold start with nothing wrong.
+ unwritableStamp("1.0.16");
+ const fetchMock = feedReturns("v1.0.16");
+ const warn = vi.spyOn(console, "error").mockImplementation(() => {});
+ const mod = await load();
+ await mod.stampBackendVersionAfterPull(tracksLatest());
+ // Positive controls: a silent early return upstream satisfies
+ // `not.toHaveBeenCalled` just as well as the gate deciding to stay quiet.
+ // The mode, not the contents — the file reads "1.0.16" whether the write
+ // failed or succeeded, so asserting the contents proves nothing here.
+ expect(fetchMock).toHaveBeenCalled();
+ expect(statSync(stampPath()).mode & 0o200).toBe(0);
+ expect(warn).not.toHaveBeenCalled();
+ },
+ );
+
+ it.skipIf(!modeBlocksWrite)(
+ "stays quiet when the stamp spells the pulled release differently",
+ async () => {
+ // Build metadata does not participate in precedence, so these are the
+ // same release and nothing is wrong. Run in the direction that is
+ // directly reachable: the feed's tag_name is stamped with only a leading
+ // `v` stripped, so a release tagged `v1.0.16+build77` arrives spelled that
+ // way against a stamp holding the plain `1.0.16`. (The predicate is
+ // symmetric, so this exercises the same comparison either way round — but
+ // a fixture that does not follow from its own comment is how a correct
+ // test gets deleted in a later cleanup, which already happened to this one.)
+ //
+ // This is the wiring pin, not a duplicate of the unit test above: the unit
+ // test proves the predicate, this proves the CALL SITE still routes through
+ // it. A textual `!==` at the warn site passes every other test in this file.
+ // The fixture's whole discriminating power sits in this tag being
+ // ACCEPTED: if VERSION_RE ever stops admitting build metadata,
+ // fetchLatestRelease returns null, the call site is never reached, and
+ // every assertion below still passes while testing nothing. Verified:
+ // dropping that group from VERSION_RE leaves this file green without it.
+ expect(VERSION_RE.test("1.0.16+build77")).toBe(true);
+ unwritableStamp("1.0.16");
+ const fetchMock = feedReturns("v1.0.16+build77");
+ const warn = vi.spyOn(console, "error").mockImplementation(() => {});
+ const mod = await load();
+ await mod.stampBackendVersionAfterPull(tracksLatest());
+ // Positive controls: a silent early return upstream satisfies
+ // `not.toHaveBeenCalled` just as well as the gate deciding to stay quiet.
+ // The CONTENTS discriminate here, unlike in the sibling above where the
+ // stamp and the pulled release are the same string: if the write had
+ // landed this would read "1.0.16+build77".
+ expect(fetchMock).toHaveBeenCalled();
+ expect(readFileSync(stampPath(), "utf-8")).toBe("1.0.16");
+ expect(warn).not.toHaveBeenCalled();
+ },
+ );
+
+ it.skipIf(!modeBlocksWrite)(
+ "warns when the stamp is stuck AHEAD of the release, where an is-newer gate would not",
+ async () => {
+ unwritableStamp("1.0.17");
+ const fetchMock = feedReturns("v1.0.16");
+ const warn = vi.spyOn(console, "error").mockImplementation(() => {});
+ const mod = await load();
+ await mod.stampBackendVersionAfterPull(tracksLatest());
+ expect(fetchMock).toHaveBeenCalled();
+ expect(readFileSync(stampPath(), "utf-8")).toBe("1.0.17"); // still unwritten
+ // Which message, and how many: counting calls alone cannot tell this
+ // apart from any other console.error reached by a regression.
+ expectStampFailure(warn);
+ },
+ );
+});
+
+/**
+ * The gate tests above skip when a 0444 file does not refuse a write, and a skip
+ * is easy to miss. On CI — non-root host runners, filesystems that honour modes
+ * — the gate MUST be exercisable, so this fails there rather than letting the
+ * coverage evaporate quietly. Locally it does not: a dev box may legitimately be
+ * root in a container or on a mount that drops modes, and the describe above
+ * writes the reason to stderr for that case.
+ *
+ * Its own describe, deliberately: the isolated describe's beforeEach mkdtemps
+ * the very TMPDIR whose unusability `why` would be reporting, so it would throw
+ * first and the diagnostic would never be seen.
+ */
+describe("the mode gate is exercisable where it has to be", () => {
+ // `skipIf`, not an early return. A body that returns early reports a green
+ // PASS for a test named "can exercise the mode gate on CI" on every machine
+ // where it asserted nothing — strictly easier to miss than a skip, which is
+ // what this describe exists to avoid. The early-return version was justified
+ // as keeping the body from going stale; that benefit does not exist, because
+ // `modeProbe` is a module-scope const and any stale reference is a `tsc`
+ // error whether the line executes or not.
+ it.skipIf(!onCI)("can exercise the mode gate on CI", () => {
+ // BOTH, not just `why`. It is true today that `why === ""` exactly when
+ // `blocked` is true, but nothing enforces it: a future non-blocking branch
+ // that forgets to set a reason yields blocked=false with why="", and then
+ // all three gate tests skip while this one passes — green and silent on the
+ // one leg that is supposed to catch it. Demonstrated by mutation, which is
+ // why the `blocked` line is back after being removed as "a restatement".
+ expect(
+ modeProbe.why,
+ "the stamp gate could not be exercised on CI, so the AHEAD-stamp warning " +
+ "and the quiet-when-agreeing case are untested on this leg. If this leg " +
+ "now runs as root or in a container, run it unprivileged; if the mount " +
+ "does not honour chmod, move the gate to one that does.",
+ ).toBe("");
+ expect(modeProbe.blocked, "the probe reported no reason but did not block").toBe(true);
+ });
+});
+
+/**
+ * The two orderings that make the stamp safe cannot be exercised here — one
+ * sits behind `docker compose up`, the other behind a network fetch — so they
+ * are pinned as drift guards on the source. Both assert their landmarks exist
+ * before comparing positions, so neither can pass on a `-1`.
+ */
+describe("the stamp is wired where it is true", () => {
+ const dockerSource = readFileSync(new URL("../commands/docker.ts", import.meta.url), "utf-8");
+ const upgradeSource = readFileSync(new URL("../commands/upgrade.ts", import.meta.url), "utf-8");
+
+ /**
+ * Sliced to the `start` action's own body. Comparing offsets across the whole
+ * file would also accept the call sitting in `docker restart`, `docker logs`
+ * or the compose `up` FAILURE branch — all of which are defined after the
+ * pull, and none of which pulled anything.
+ */
+ const startFrom = dockerSource.indexOf('.command("start")');
+ const startTo = dockerSource.indexOf('.command("stop")', Math.max(startFrom, 0));
+ const startAction = dockerSource.slice(startFrom, startTo);
+
+ it("slices the start action, so the assertions below mean what they say", () => {
+ // Guards the two tests that follow: if these anchors ever stop matching,
+ // `slice(-1, -1)` is "" and every indexOf below would be -1.
+ expect(startFrom).toBeGreaterThan(-1);
+ expect(startTo).toBeGreaterThan(startFrom);
+ expect(startAction).toContain('"--pull", "always"');
+ });
+
+ it("stamps AFTER the pull, not before", () => {
+ const pull = startAction.indexOf('"--pull", "always"');
+ const stamp = startAction.indexOf("await stampBackendVersionAfterPull(composeFile)");
+ expect(pull).toBeGreaterThan(-1);
+ expect(stamp).toBeGreaterThan(-1);
+ expect(stamp).toBeGreaterThan(pull);
+ });
+
+ it("stamps between the pull and the health wait, on the path that always runs", () => {
+ // Three positions have to be excluded, and "after the pull" excludes none
+ // of them on its own:
+ // - inside the compose `up` catch, which exits 1 having started nothing;
+ // - after the health loop, which `return`s on the first healthy poll, so
+ // the stamp would run ONLY when the start timed out;
+ // - inside the loop's success branch, which is fine but not where it is.
+ // Bounding it above by the loop pins the one position that always runs
+ // after a successful pull.
+ const stamp = startAction.indexOf("await stampBackendVersionAfterPull(composeFile)");
+ const failureMessage = startAction.indexOf('"[error] Failed to start Docker containers."');
+ // Asserted BEFORE it is used as a fromIndex: indexOf(x, -1) searches from 0
+ // and silently finds the unrelated `!dockerAvailable()` exit higher up, so
+ // an inlined search would let the stamp sit inside the failure branch.
+ expect(failureMessage).toBeGreaterThan(-1);
+ const failureExit = startAction.indexOf("process.exit(1)", failureMessage);
+ const healthWait = startAction.indexOf("Waiting for services to become healthy");
+ expect(failureExit).toBeGreaterThan(-1);
+ expect(healthWait).toBeGreaterThan(-1);
+ expect(stamp).toBeGreaterThan(-1);
+ expect(stamp).toBeGreaterThan(failureExit);
+ expect(stamp).toBeLessThan(healthWait);
+ });
+
+ it("bounds the release fetch, which is now awaited on a command", () => {
+ // ix docker start awaits this. Undici's default headersTimeout is 300s, so
+ // an unbounded fetch behind a captive portal or a proxy that accepts the
+ // connection and never answers stalls the command for five minutes with
+ // nothing printed. Not observable without a hanging server, so it is pinned
+ // on the source.
+ const from = upgradeSource.indexOf("async function fetchLatestRelease");
+ expect(from).toBeGreaterThan(-1);
+ const fn = upgradeSource.slice(from, upgradeSource.indexOf("\n}", from));
+
+ // The signal must be INSIDE the fetch(...) argument list: building the
+ // options object and then calling `fetch(url)` without it leaves the fetch
+ // unbounded. The first argument is matched loosely so hoisting the URL to a
+ // const does not read as a missing timeout.
+ expect(fn).toMatch(
+ /await fetch\(\s*[^,]+,\s*\{\s*signal:\s*AbortSignal\.timeout\(\s*timeoutMs\s*\)\s*,?\s*\}\s*,?\s*\)/,
+ );
+ // ...and there is only the one fetch, so the matched call is the one made.
+ expect(fn.match(/\bfetch\(/g)).toHaveLength(1);
+
+ // Matching `timeout(timeoutMs)` says nothing about the value, so pin the
+ // default itself — 300_000 is undici's own, i.e. no bound at all.
+ const declared = /timeoutMs: number = ([0-9_]+)/.exec(fn);
+ expect(declared).not.toBeNull();
+ expect(Number(declared![1].replace(/_/g, ""))).toBeLessThanOrEqual(60_000);
+ });
+
+ it("gives the stamp path its own shorter bound", () => {
+ // The default is sized for `ix upgrade`, which the user chose to wait for.
+ // The stamp runs behind `ix docker start` with the containers already up,
+ // and an argument that is never passed is a bound that does not exist —
+ // which is exactly what happened when this parameter was first added.
+ const from = upgradeSource.indexOf("export async function stampBackendVersionAfterPull");
+ expect(from).toBeGreaterThan(-1);
+ const body = upgradeSource.slice(from, upgradeSource.indexOf("\n}", from));
+ const call = /fetchLatestRelease\(\s*MEMORY_LAYER_DIST_REPO\s*,\s*([0-9_]+)\s*\)/.exec(body);
+ expect(call).not.toBeNull();
+ expect(Number(call![1].replace(/_/g, ""))).toBeLessThanOrEqual(15_000);
+ });
+
+ it("stampBackendVersionAfterPull checks the compose before fetching or writing", () => {
+ const from = upgradeSource.indexOf("export async function stampBackendVersionAfterPull");
+ expect(from).toBeGreaterThan(-1);
+ const fn = upgradeSource.slice(from);
+ const body = fn.slice(0, fn.indexOf("\n}"));
+
+ const guard = body.indexOf("composeTracksLatestBackend(");
+ const fetched = body.indexOf("fetchLatestRelease(");
+ const written = body.indexOf("writeVersionStamp(");
+ expect(guard).toBeGreaterThan(-1);
+ expect(fetched).toBeGreaterThan(-1);
+ expect(written).toBeGreaterThan(-1);
+ expect(guard).toBeLessThan(fetched);
+ expect(guard).toBeLessThan(written);
+ // ...and it must return on the guard, not merely evaluate it.
+ expect(body).toMatch(/if \(!composeTracksLatestBackend\(.*\)\) return;/);
+ });
+});
diff --git a/ix-cli/src/cli/commands/docker.ts b/ix-cli/src/cli/commands/docker.ts
index eb9236d9..37b97ce6 100644
--- a/ix-cli/src/cli/commands/docker.ts
+++ b/ix-cli/src/cli/commands/docker.ts
@@ -4,6 +4,7 @@ import { createInterface } from "readline";
import { existsSync, mkdirSync } from "fs";
import { join } from "path";
import { homedir } from "os";
+import { stampBackendVersionAfterPull } from "./upgrade.js";
const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");
const COMPOSE_DIR = join(IX_HOME, "backend");
@@ -144,6 +145,18 @@ export function registerDockerCommand(program: Command): void {
process.exit(1);
}
+ // `--pull always` just fetched the images this compose names, so if it
+ // tracks `:latest` the container is now running the current backend
+ // release — record it. Without this the tracked version only ever moves
+ // when `ix upgrade` runs, so starting the backend any other way leaves a
+ // file naming an older release and the update notice fires on every
+ // command for ever. The compose file is passed because it decides whether
+ // that premise holds at all: this falls back to any docker-compose.yml in
+ // the working directory, which may pin a tag, a digest, or a local build.
+ // Awaited so the stamp is on disk before the command returns, and it
+ // cannot fail the start: the helper swallows its own errors.
+ await stampBackendVersionAfterPull(composeFile);
+
console.log("Waiting for services to become healthy...");
for (let i = 0; i < 30; i++) {
if (isHealthy()) {
diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.ts
index 939816fd..9ab0a8e9 100644
--- a/ix-cli/src/cli/commands/upgrade.ts
+++ b/ix-cli/src/cli/commands/upgrade.ts
@@ -51,10 +51,21 @@ function getCurrentVersion(): string {
// for updates" and exited 1 against a perfectly reachable GitHub.
export const VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
-async function fetchLatestRelease(repo: string): Promise<string | null> {
+async function fetchLatestRelease(
+ repo: string,
+ timeoutMs: number = 30_000,
+): Promise<string | null> {
try {
+ // Bounded: undici's default headersTimeout is 300s, so a proxy or captive
+ // portal that accepts the connection and never answers stalls whatever is
+ // waiting for five minutes with nothing printed. Every other fetch in this
+ // codebase bounds itself. The default stays generous because `ix upgrade`
+ // awaits three of these and the user chose to wait; the stamp path, which
+ // runs behind `ix docker start` after the containers are already up, passes
+ // a short one instead of making a slow link look like an unreachable GitHub.
const resp = await fetch(
- `https://api.github.com/repos/${GITHUB_ORG}/${repo}/releases/latest`
+ `https://api.github.com/repos/${GITHUB_ORG}/${repo}/releases/latest`,
+ { signal: AbortSignal.timeout(timeoutMs) }
);
if (!resp.ok) return null;
const data = (await resp.json()) as { tag_name?: string };
@@ -339,6 +350,208 @@ function getTrackedVersion(versionFile: string): string {
}
}
+/**
+ * Whether to tell the user their backend is behind.
+ *
+ * The two branches of `checkForUpdate` — cached and freshly fetched — each made
+ * this decision inline, so a change to one silently did not apply to the other.
+ * Pure, so the thing the user actually sees is testable without a clock, a
+ * cache file or a network.
+ *
+ * The tracked version is the whole input on purpose. It is written wherever the
+ * image is installed or pulled, so it is the record of what is running; nothing
+ * else available locally improves on it, and the one thing that looks like it
+ * would — comparing the container against `docker image inspect ...:latest` —
+ * is registry-blind and reports a months-old image as current.
+ */
+export function backendUpdateAvailable(
+ backendLatest: string | undefined,
+ trackedVersion: string,
+): boolean {
+ return !!backendLatest && isNewer(backendLatest, trackedVersion);
+}
+
+/**
+ * One wording for one condition, used by both callers that branch on
+ * `writeVersionStamp` returning false. Two literals for the same failure is how
+ * they drift.
+ *
+ * It does not promise a nag. A stamp stuck BEHIND makes the notice fire on every
+ * command; a stamp stuck AHEAD makes it stay silent through the next release
+ * the user should have been told about. Both are wrong and neither is fixable
+ * without the write, so the sentence has to cover both.
+ *
+ * Takes no file: both callers can only ever be about the backend stamp, and the
+ * sentence says "backend update notices". A parameter would make it look reusable
+ * for the compass stamp, which it is not.
+ */
+function stampFailureMessage(): string {
+ // States the consequence, not a cause: the write's errno is swallowed, so
+ // "until it is writable" would be a guess — and a wrong one for the case the
+ // tests actually reproduce, a directory sitting where the file belongs, which
+ // no permission change fixes.
+ return `[!!] Could not record the version in ${BACKEND_VERSION_FILE}; until it can be written, backend update notices will be wrong.`;
+}
+
+/**
+ * Whether the stamp disagrees with the release we just pulled.
+ *
+ * Deliberately NOT `backendUpdateAvailable`. That answers "is there an upgrade
+ * to offer", which is silent when the stamp is stuck AHEAD — a state this module
+ * documents as reachable, since the GHCR tag and the release feed are published
+ * separately — and an ahead stamp is equally wrong and equally uncorrectable
+ * once the write has failed.
+ *
+ * Compared by PRECEDENCE, not as text, and precedence is what the notice this
+ * warns about uses. The reachable divergence is a PRE-RELEASE: a stamp left at
+ * `1.0.16-rc1` by an earlier pull disagrees with a pulled `1.0.16`, and it must
+ * keep disagreeing — `backendUpdateAvailable` says an upgrade is available, so
+ * the notice really will fire. A comparison that only looked at the numeric
+ * triple would call those equal and swallow the one warning that explains it.
+ *
+ * Build metadata and leading zeros go the other way: `VERSION_RE` admits both
+ * and `splitVersion` ignores both, so `1.0.16+abc` and `1.0.16` are one release
+ * and must NOT warn. That one is reachable too, by the same route: all three
+ * writers stamp the feed's `tag_name` with only a leading `v` stripped, so a
+ * release tagged `v1.0.16+build77` lands in this file verbatim — and VERSION_RE
+ * admits it deliberately, after a tag carrying both a pre-release and build
+ * metadata once broke `ix upgrade` outright.
+ *
+ * Symmetric, so the argument order carries no meaning and a swapped call cannot
+ * change the answer; it reads (tracked, pulled) to match its name. Named and
+ * exported rather than inlined so it is testable and so its divergence from the
+ * notice predicate is visible rather than accidental.
+ */
+export function stampDisagreesWithPull(trackedVersion: string, pulled: string): boolean {
+ return isNewer(trackedVersion, pulled) || isNewer(pulled, trackedVersion);
+}
+
+/**
+ * Record the backend release in its stamp file. Returns whether it was written.
+ *
+ * `mkdirSync` because IX_HOME may not exist yet — a stamp that fails to write
+ * leaves the tracked version behind for ever, and the notice it drives says
+ * "update available" on every command with no way for the user to see why.
+ *
+ * A falsy version is refused rather than written: not knowing which release we
+ * are on is not the same as being on none of them. Being wrong *behind* costs a
+ * nag, while being wrong *ahead* hides a genuinely stale backend and stops
+ * `ix upgrade` from ever fetching it — so where there is a choice, this errs
+ * behind. (It is not always a choice: the GHCR `:latest` tag and the
+ * `ix-memory-layer-dist` release are separate publishing surfaces with nothing
+ * correlating them, so a release cut between the two can be recorded ahead of
+ * the image actually pulled. `ix upgrade` has always had that race; correcting
+ * it needs the backend to report its own version.)
+ *
+ * The write does not throw — callers differ on whether a failure should be
+ * fatal, so they decide from the return value rather than from an exception.
+ * Not a general component-stamp writer: the compass stamp is written with a
+ * trailing newline that `parseCompassStamp` depends on.
+ */
+export function writeVersionStamp(
+ versionFile: string,
+ version: string | null | undefined,
+): boolean {
+ if (!version) return false;
+ try {
+ mkdirSync(dirname(versionFile), { recursive: true });
+ writeFileSync(versionFile, version);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Whether this compose file runs the backend from the moving `:latest` tag.
+ *
+ * The premise of stamping after a pull is that `--pull always` fetched the
+ * current release — which holds only if the file being started actually tracks
+ * `:latest`. `ix docker start` falls back to any `docker-compose.yml` in the
+ * working directory, so it may well not: a compose that pins `:1.0.13`, pins a
+ * digest, or points at a locally-built image pulls something that is not the
+ * latest release, and stamping it would put a version in the file that the
+ * running container does not have.
+ *
+ * That is the one way this file must never be wrong, so the check is on the
+ * image reference itself rather than on which path the compose came from — a
+ * user is free to edit the copy under IX_HOME, and it is what the file *says*
+ * that decides what gets pulled.
+ */
+export function composeTracksLatestBackend(composeText: string): boolean {
+ // Compared as a whole string rather than matched as a pattern: BACKEND_IMAGE
+ // is interpolated, and its dots are regex wildcards, so a pattern here would
+ // also accept `ghcrXio/...` and anything else that happened to line up.
+ const wanted = `${BACKEND_IMAGE}:latest`;
+ return composeText.split(/\r?\n/).some((line) => {
+ const declared = /^\s*image:\s*(.+?)\s*$/.exec(line);
+ if (!declared) return false;
+ return declared[1].replace(/^["']|["']$/g, "") === wanted;
+ });
+}
+
+/**
+ * Record the backend release after something has pulled `:latest`.
+ *
+ * `.backend-version` is written at install time (install.sh, install.ps1) and by
+ * `ix upgrade` — but not by `ix docker start`, which pulls `:latest` on every
+ * cold start. So anyone who took a newer image that way kept a file naming the
+ * release they installed while running a later one, and was told to upgrade on
+ * every command for ever.
+ *
+ * The fix belongs at the write, not at the read. Having just pulled `:latest`,
+ * the running image IS the current release, so the release is simply what to
+ * record; nothing has to be inferred about it afterwards. Inferring it is what
+ * cannot be done safely here — `docker image inspect ...:latest` never contacts
+ * a registry, so a container matching the local `:latest` proves only that
+ * nothing has been pulled since, which is equally true of a months-old image.
+ *
+ * Always asks the release feed rather than reading the version cache, on a short
+ * bound. Preferring the cache looked like a free saving and was not: a cache up
+ * to an hour old can name an EARLIER release than the file already holds (an
+ * installer stamps the true latest without touching the cache), so it needed a
+ * "never go backwards" rule to be safe — and that rule then pinned a file that
+ * had got AHEAD, which is a state this very module documents as reachable, since
+ * the GHCR tag and the release feed are published separately. Fetching keeps the
+ * write self-healing in both directions, and only on a cold start.
+ *
+ * If the release cannot be established the stamp is left alone: the user keeps a
+ * notice they may not need, which is the failure worth having. A write that
+ * fails says so, because "update available" for ever with no explanation is the
+ * symptom this whole change is about.
+ */
+export async function stampBackendVersionAfterPull(composeFile: string): Promise<void> {
+ try {
+ if (!composeTracksLatestBackend(readFileSync(composeFile, "utf-8"))) return;
+ // Short bound: this is awaited behind `ix docker start`, whose containers
+ // are already up, so a proxy that accepts and never answers must not hold
+ // the command open for the generous default the upgrade path wants.
+ const latest = await fetchLatestRelease(MEMORY_LAYER_DIST_REPO, 10_000);
+ // `latest` first: it decides whether there is anything to write at all, so
+ // it reads in the order it applies and does not lean on the writer's own
+ // falsy check to make a null call a no-op.
+ if (latest && !writeVersionStamp(BACKEND_VERSION_FILE, latest)) {
+ // Must not fail the start, and only worth saying when the file really is
+ // wrong: a root-owned stamp already holding what we just pulled fails to
+ // write on every cold start with nothing actually out of date.
+ //
+ // "Differs from what we pulled" rather than "is behind the release we
+ // fetched": a stamp stuck AHEAD is also wrong and also cannot be
+ // corrected here, and the notice this warns about is computed from the
+ // CACHED release, which can be up to an hour out of step with `latest`.
+ if (stampDisagreesWithPull(getTrackedVersion(BACKEND_VERSION_FILE), latest)) {
+ console.error(chalk.yellow(stampFailureMessage()));
+ }
+ }
+ } catch {
+ // In practice only the compose read: fetchLatestRelease and
+ // writeVersionStamp swallow their own failures, so offline and rate-limited
+ // arrive as `latest === null` on the normal path above. Kept broad rather
+ // than narrowed to that one call, because nothing here is worth failing a
+ // start the user already got containers out of.
+ }
+}
+
/**
* Render a failed `execFileSync` as something a user can act on.
*
@@ -1023,9 +1236,10 @@ export async function checkForUpdate(): Promise<void> {
if (cache && Date.now() - cache.checkedAt < 3600_000) {
const hasCliUpdate = isNewer(cache.latest, current);
const hasCompassUpdate = shouldOfferCompassUpgrade(cache.compassLatest);
- const backendCurrent = getTrackedVersion(BACKEND_VERSION_FILE);
- const hasBackendUpdate =
- cache.backendLatest && isNewer(cache.backendLatest, backendCurrent);
+ const hasBackendUpdate = backendUpdateAvailable(
+ cache.backendLatest,
+ getTrackedVersion(BACKEND_VERSION_FILE),
+ );
if (hasCliUpdate || hasCompassUpdate || hasBackendUpdate) {
printUpdateNotice(current, cache.latest, !!hasCompassUpdate, !!hasBackendUpdate);
}
@@ -1041,9 +1255,10 @@ export async function checkForUpdate(): Promise<void> {
writeCache(latest, compassLatest ?? undefined, backendLatest ?? undefined);
const hasCliUpdate = isNewer(latest, current);
const hasCompassUpdate = shouldOfferCompassUpgrade(compassLatest ?? undefined);
- const backendCurrent = getTrackedVersion(BACKEND_VERSION_FILE);
- const hasBackendUpdate =
- backendLatest && isNewer(backendLatest, backendCurrent);
+ const hasBackendUpdate = backendUpdateAvailable(
+ backendLatest ?? undefined,
+ getTrackedVersion(BACKEND_VERSION_FILE),
+ );
if (hasCliUpdate || hasCompassUpdate || hasBackendUpdate) {
printUpdateNotice(current, latest, !!hasCompassUpdate, !!hasBackendUpdate);
}
@@ -1321,7 +1536,7 @@ export function registerUpgradeCommand(program: Command): void {
// ── Backend (memory-layer) upgrade ───────────────────────────────
const backendCurrent = getTrackedVersion(BACKEND_VERSION_FILE);
let backendImageChanged = false;
- if (backendLatest && isNewer(backendLatest, backendCurrent)) {
+ if (backendLatest && backendUpdateAvailable(backendLatest, backendCurrent)) {
console.log(
`Backend update available: ${backendCurrent === "0.0.0" ? "none" : backendCurrent} → ${chalk.green(backendLatest)}`
);
@@ -1334,10 +1549,22 @@ export function registerUpgradeCommand(program: Command): void {
["pull", "ghcr.io/ix-infrastructure/ix-memory-layer:latest"],
{ stdio: "inherit", timeout: 120000 }
);
- mkdirSync(IX_HOME, { recursive: true });
- writeFileSync(BACKEND_VERSION_FILE, backendLatest);
+ // The pull succeeded, so the image DID change: say so, and keep
+ // backendImageChanged true — it gates the Ix#271 re-map nudge, and
+ // suppressing that would leave a new engine reading a graph written
+ // by the old one, which fails by returning empty rather than by
+ // erroring.
+ //
+ // A failed stamp is reported on its own line rather than thrown.
+ // Throwing lands in the bare catch below, which says the PULL
+ // failed and to run `ix docker restart` — a false diagnosis for a
+ // read-only IX_HOME, and one that discards the only message naming
+ // the real cause.
backendImageChanged = true;
console.log(`[ok] Backend image updated to ${backendLatest}`);
+ if (!writeVersionStamp(BACKEND_VERSION_FILE, backendLatest)) {
+ console.error(chalk.yellow(stampFailureMessage()));
+ }
} catch {
console.error("[!!] Could not pull latest backend image. Run: ix docker restart");
}