Skip to content
Source
Sign inSign up
pingdotgg/t3code

[Bug]: Upgrading is brittle on large database #17937

Closedmorgaesis(GitHub profile, opens in a new tab) opened this issue 3 comments

Area

apps/server Why T3 errors: at 21:22 UTC your desktop (updated to nightly 20261010) asked the server to update itself. While the service launcher was file-copying the 5.5 GB state database as its backup, the desktop's SSH launcher started a second t3 serve on port 3773. The updated server then died with EADDRINUSE, and the launcher "rolled back" by copying that backup over the live database while the second server had it open. statev2.sqlite has been malformed since, so every thread-list read fails.

Impact

Major degradation or frequent failure

Version or commit

nightly 20261010

Workaround

Claude Opus 5.5: I fixed everything fixable. Two findings have no fix:

  • Restart race: while the unit starts, your desktop can launch a second server for an instant. T3 has no lock both launch paths honour, so every restart of t3code.service already has this window; the script narrows it.
  • The lost rows above: worst case, one message that was rejected during the failed update gets accepted if the client retries it.
  1. morgaesis(GitHub profile, opens in a new tab) added labelsneeds-triage

  2. Same failure here, with a worse outcome: the database came back empty, not malformed. All threads, projects and scheduled tasks were gone. Adding our timeline and the code paths involved, since it pins down the exact race.

    Setup: Linux VM, t3code.service (service launcher from 0.0.46-nightly.20261010.2908), desktop on macOS connected over SSH. Update 0.0.46-nightly.20261011.2955 → 0.0.46-nightly.20261013.3042, statev2.sqlite several hundred MB, slow disk (IO pressure "full" 36–64 %).

    Timeline (local time):

    • 09:39:46: the active server hands off to the launcher. The launcher stops it, and backupDatabaseOnce starts copying the DB file. This took ~5 minutes on the slow disk, and port 3773 was down the whole time.
    • 09:40–09:45: the desktop's SSH route found nothing on 3773 and started its own t3 serve --port 3773 --base-dir ~/.t3 against the same DB. We run a watchdog that kills foreign t3 serve processes on that base dir, so this repeated 5 times (one new server per minute). The first ones served the old, intact DB (their logs show the old threads).
    • 09:44:54: backup done, the trial child starts and fails: listen EADDRINUSE 127.0.0.1:3773 (a desktop-launched server holds the port).
    • 09:44:5x: #handleExit → #returnToPrevious → restoreDatabaseBackup runs copyFile(backup, statev2.sqlite) over the live file (same inode, truncate + write).
    • 09:44:59: the next desktop-launched server opened the DB mid-restore, saw an empty file, and ran all 61 migrations from scratch. Every row in effect_sql_migrations is stamped with that second.
    • Right after: discardDatabaseBackup deleted the backup, so nothing was left to recover. 2955 then started on the fresh DB (Database migration history diverges … 61:PullRequestReviewGuides (unknown to this build)).
    • 09:46:40: the user retried and the update succeeded, only because the DB was now 4 MB and the backup took seconds.

    What we think needs fixing (from reading the launcher in 2908/3042):

    1. restoreDatabaseBackup overwrites the live DB with copyFile without checking for other open handles. Restoring under an open SQLite connection gives an empty or corrupt DB.
    2. #returnToPrevious discards the backup immediately after restoring, even if the restore or the rollback start fails. Keep it until the previous version is confirmed healthy (ideally keep the last N).
    3. backupDatabaseOnce is a raw file copy of a live DB (plus -wal/-shm). The SQLite online backup API or VACUUM INTO would be consistent and is usually faster than copy + fsync of a large file.
    4. t3 serve takes no exclusive lock on --base-dir, so two servers can own one DB (same root cause as #6097 and #11084; the unmerged #9652 tried to address it).
    5. The desktop SSH route starts a replacement server while a service-managed server (serviceManaged) is mid-update. It should wait for the service (it can see runtime/service-state.json with update.status = pending).
    6. Backup duration, rollback and backup deletion are not logged, which made this hard to reconstruct.

    Mitigations we are putting in place: connect the desktop over HTTPS (pairing link) instead of SSH launch, so it never spawns a server on the host; take our own SQLite online backups outside ~/.t3/runtime; and run updates through a script that pauses the watchdog, backs up first and verifies thread counts afterwards.

    A 1-minute explainer of the failure sequence:

    https://github.com/user-attachments/assets/6d301d8a-92df-47a6-92ae-454e9f17d3b6

  3. Note

    🤖 Claude Opus 5.5 responding on behalf of Theo

    Closing as fixed by #16102 and #19311, shipped in 0.0.46-nightly.20261014.3105.

    • Second server during the update: a server must take an exclusive lock on the T3 home before it opens the database (#16102). The SSH-launched server and the updated trial can no longer both own it.
    • Rollback over a live database: if another server owns the home, the trial exits with code 78, and the launcher waits for the owner to leave (#idleWhileStateDirOwned, apps/server/src/serviceLauncher.ts:823). It no longer copies the backup over a database that another process has open.
    • Large databases: #19311 checks that the backup fits before the server stops, and raises the prepare window from 120 s to 30 minutes, so a slow first start on a big database no longer forces a rollback.

    One mixed-version case is not covered: a server from before the lock whose runtime record another old server already removed. If you hit this again with both sides on a build that has the lock, please reopen with the launcher log.

  4. This still happens on lock-aware builds, through two rollback paths outside the exit-78 protection described in the closing comment. Reproduced on main @ 9826dbb990; could this be reopened?

    #16102 covers a trial that finds another owner and exits 78: the launcher idles and discards the backup (apps/server/src/serviceLauncher.ts:775). The launcher itself never takes or checks the server-owner.sqlite lock, and two paths still restore without it:

    • A trial that ends any other way. A crash or non-78 exit (#handleExit, :752-763) or the prepared timeout (:738) goes to #returnToPrevious, which calls restoreDatabaseBackup (:806).
    • A launcher restart with a .restore-pending marker. #recover (:543-544) finishes the restore before anything else.

    Between the trial's exit and the previous version reacquiring the lock, nobody holds it, and that gap covers the whole restore copy. A desktop SSH launch (#24225), the desktop's local server, or an offline t3 project add can take the lock in that window. A candidate can also fail before reaching the lock (server.ts:783) while another server already holds it, and the launcher then restores instead of idling.

    Repro. A launcher test with fake runtimes, in the style of serviceLauncher.test.ts (below). The test process plays the other server: it takes the same lock as acquireServerOwnership (BEGIN EXCLUSIVE on userdata/server-owner.sqlite) and commits a row to statev2.sqlite.

    1. Crashed trial. 1.0.0 requests an update to 1.1.0; the launcher backs up and starts the trial. The other owner takes the lock and commits written-by-other-owner. The trial exits 1, standing in for a candidate that fails before reaching the lock (I can't deterministically schedule the other owner to win the lock mid-restore).
    2. Interrupted rollback. State is pending with a backup and a .restore-pending marker; the other owner holds the lock and has committed a row; the launcher starts.

    To run: in a checkout of main @ 9826dbb990, run vp i, save the file as apps/server/src/serviceLauncher.ownershipRepro.test.ts, then cd apps/server && vp test run src/serviceLauncher.ownershipRepro.test.ts.

    Result. Both cases restore the backup while the other owner holds the lock. New connections then see only before-update; the other owner's committed row is gone (integrity_check ok). On the tested macOS/APFS path, cp -c replaces the files, so the other owner's existing connection still reads its row from the replaced files. Linux (cp --reflink=auto, copying into the existing file) is untested.

    [repro] {
      update: { fromVersion: '1.0.0', targetVersion: '1.1.0', status: 'rolled-back', reason: 'candidate-exited:1', ... },
      newConnectionWhileOwned: { rows: [ 'before-update' ], integrity: 'ok' },
      otherOwnersConnection: [ 'before-update', 'written-by-other-owner' ],
      afterOwnerCloses: { rows: [ 'before-update' ], integrity: 'ok' }
    }
    [service-launcher] Another T3 Code server owns this T3 home. Stop it, then restart this service.
    [repro] rows after launcher recovery while the other owner holds the lock: { rows: [ 'before-update' ], integrity: 'ok' }
    
     × a crashed trial's rollback restores the backup over another owner's database
     × a restarted launcher finishes an interrupted restore over another owner's database
    AssertionError: expected [ 'before-update' ] to deeply equal [ 'before-update', 'written-by-other-owner' ]
    apps/server/src/serviceLauncher.ownershipRepro.test.ts
    import * as NodeFS from "node:fs";
    import * as NodeOS from "node:os";
    import * as NodePath from "node:path";
    import * as NodeSqlite from "node:sqlite";
    
    import { SERVER_EXIT_CODE_STATE_DIR_OWNED } from "@t3tools/contracts";
    import { afterEach, expect, it, vi } from "vite-plus/test";
    
    import { Launcher, readServiceState, writeServiceState } from "./serviceLauncher.ts";
    import { SERVICE_LAUNCHER_PROTOCOL } from "./cloud/serviceProtocol.ts";
    
    const writeFakeRuntime = (versionDir: string, childSource: string) => {
      NodeFS.mkdirSync(versionDir, { recursive: true });
      const entryPath = NodePath.join(versionDir, "t3");
      NodeFS.writeFileSync(entryPath, `#!${process.execPath}\n${childSource}`);
      NodeFS.chmodSync(entryPath, 0o755);
      NodeFS.writeFileSync(NodePath.join(versionDir, ".install-complete"), `${NodePath.basename(versionDir)}\n`);
    };
    
    // Same mechanism as acquireServerOwnership (serverOwnership.ts:195-197).
    const takeOwnerLock = (stateDir: string) => {
      const lock = new NodeSqlite.DatabaseSync(NodePath.join(stateDir, "server-owner.sqlite"));
      lock.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;");
      return lock;
    };
    
    // The previous version exits 78 when another process holds the lock, like a real server.
    const previousRuntime = (dbPath: string, stateDir: string) => `
    import { DatabaseSync } from "node:sqlite";
    const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
    if (context.update === undefined) {
      process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${JSON.stringify(dbPath)} });
      setInterval(() => {}, 1_000);
    } else {
      const lock = new DatabaseSync(${JSON.stringify(NodePath.join(stateDir, "server-owner.sqlite"))});
      try { lock.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;"); }
      catch { process.exit(${SERVER_EXIT_CODE_STATE_DIR_OWNED}); }
      setInterval(() => {}, 1_000);
    }
    `;
    
    const rows = (dbPath: string) => {
      const db = new NodeSqlite.DatabaseSync(dbPath, { readOnly: true });
      try {
        return {
          rows: db.prepare("SELECT v FROM t ORDER BY rowid").all().map((row) => row.v),
          integrity: db.prepare("PRAGMA integrity_check").get()?.integrity_check,
        };
      } finally {
        db.close();
      }
    };
    
    const cleanups: Array<() => void> = [];
    afterEach(() => {
      for (const cleanup of cleanups.splice(0)) cleanup();
      vi.restoreAllMocks();
    });
    
    const setup = () => {
      const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-i4-repro-"));
      cleanups.push(() => NodeFS.rmSync(root, { recursive: true, force: true }));
      const stateDir = NodePath.join(root, "userdata");
      const dbPath = NodePath.join(stateDir, "statev2.sqlite");
      NodeFS.mkdirSync(stateDir, { recursive: true });
      const seed = new NodeSqlite.DatabaseSync(dbPath);
      seed.exec("PRAGMA journal_mode = WAL; CREATE TABLE t (v TEXT); INSERT INTO t VALUES ('before-update');");
      seed.close();
      const ownedMessage = Promise.withResolvers<void>();
      const write = process.stderr.write.bind(process.stderr);
      vi.spyOn(process.stderr, "write").mockImplementation((chunk, ...rest) => {
        if (String(chunk).includes("owns this T3 home")) ownedMessage.resolve();
        return write(chunk as string, ...(rest as []));
      });
      return { root, stateDir, dbPath, ownedMessage: ownedMessage.promise };
    };
    
    const waitForFile = async (filePath: string) => {
      for (let i = 0; i < 400 && !NodeFS.existsSync(filePath); i++) {
        await new Promise((resolve) => setTimeout(resolve, 25));
      }
      expect(NodeFS.existsSync(filePath)).toBe(true);
    };
    
    it("a crashed trial's rollback restores the backup over another owner's database", async () => {
      const { root, stateDir, dbPath, ownedMessage } = setup();
      const statePath = NodePath.join(root, "runtime", "service-state.json");
      const trialStarted = NodePath.join(root, "trial-started");
      const crashTrial = NodePath.join(root, "crash-trial");
      writeFakeRuntime(NodePath.join(root, "runtime", "versions", "1.0.0"), previousRuntime(dbPath, stateDir));
      // Stands in for a candidate that fails before it reaches the ownership lock.
      writeFakeRuntime(
        NodePath.join(root, "runtime", "versions", "1.1.0"),
        `
    import { existsSync, writeFileSync } from "node:fs";
    writeFileSync(${JSON.stringify(trialStarted)}, "");
    setInterval(() => { if (existsSync(${JSON.stringify(crashTrial)})) process.exit(1); }, 20);
    `,
      );
      await writeServiceState(statePath, { protocol: SERVICE_LAUNCHER_PROTOCOL, activeVersion: "1.0.0" });
    
      const launcher = new Launcher(root, await readServiceState(statePath));
      const running = launcher.run().catch(() => undefined);
      await waitForFile(trialStarted); // backup taken, old server stopped
    
      // Another server takes the T3 home and commits a write.
      const lock = takeOwnerLock(stateDir);
      const owner = new NodeSqlite.DatabaseSync(dbPath);
      owner.exec("PRAGMA busy_timeout = 5000; INSERT INTO t VALUES ('written-by-other-owner');");
      expect(rows(dbPath).rows).toEqual(["before-update", "written-by-other-owner"]);
    
      NodeFS.writeFileSync(crashTrial, "");
      await ownedMessage; // restored, then the previous version exited 78
    
      const after = rows(dbPath);
      const state = await readServiceState(statePath);
      const ownerView = owner.prepare("SELECT v FROM t ORDER BY rowid").all().map((row) => row.v);
      owner.close();
      lock.close();
      console.log("[repro]", {
        update: state.update,
        newConnectionWhileOwned: after,
        otherOwnersConnection: ownerView,
        afterOwnerCloses: rows(dbPath),
      });
      await launcher.stop("SIGTERM");
      await running;
      expect(after.rows).toEqual(["before-update", "written-by-other-owner"]);
    }, 30_000);
    
    it("a restarted launcher finishes an interrupted restore over another owner's database", async () => {
      const { root, stateDir, dbPath, ownedMessage } = setup();
      const statePath = NodePath.join(root, "runtime", "service-state.json");
      writeFakeRuntime(NodePath.join(root, "runtime", "versions", "1.0.0"), previousRuntime(dbPath, stateDir));
      writeFakeRuntime(NodePath.join(root, "runtime", "versions", "1.1.0"), "process.exit(1);\n");
      // Left by a launcher that stopped mid-rollback: pending update, backup, restore marker.
      const updateId = "11111111-1111-4111-8111-111111111111";
      const backupDir = NodePath.join(root, "runtime", "db-backup", updateId);
      NodeFS.mkdirSync(backupDir, { recursive: true });
      NodeFS.copyFileSync(dbPath, NodePath.join(backupDir, "database"));
      NodeFS.writeFileSync(NodePath.join(backupDir, ".restore-pending"), "");
      await writeServiceState(statePath, {
        protocol: SERVICE_LAUNCHER_PROTOCOL,
        activeVersion: "1.0.0",
        update: { id: updateId, fromVersion: "1.0.0", targetVersion: "1.1.0", dbPath, status: "pending" },
      });
    
      // Meanwhile another server (desktop app, SSH launch) owns the home and has written.
      const lock = takeOwnerLock(stateDir);
      const owner = new NodeSqlite.DatabaseSync(dbPath);
      owner.exec("PRAGMA busy_timeout = 5000; INSERT INTO t VALUES ('written-by-other-owner');");
      cleanups.push(() => {
        owner.close();
        lock.close();
      });
    
      const launcher = new Launcher(root, await readServiceState(statePath));
      const running = launcher.run().catch(() => undefined);
      await ownedMessage;
      const after = rows(dbPath);
      console.log("[repro] rows after launcher recovery while the other owner holds the lock:", after);
      await launcher.stop("SIGTERM");
      await running;
      expect(after.rows).toEqual(["before-update", "written-by-other-owner"]);
    }, 30_000);

    None of the open ownership PRs cover this: #24230/#25237 restart once ownership clears, #18633 reports and cancels backups, #21886 detects a replaced lock file, #24963 makes t3 doctor take the lock. #24230's lock probe could be reused for a fix.

    — Opus 5.5 with Claude Code, reviewed by GPT 6.1 Sol

Sign in to join this conversation.