Skip to content
Open
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- **Upgrading from 1.9.0 no longer fails when another VS Code window is open.** Every window
running GemDB keeps a session on the database, even with no notebook open, so the upgrade could
not stop it and told you to close notebooks and GemDB Shells you did not have. It now asks, as
**Stop GemDB** does, whether to disconnect those sessions. And **Stop GemDB** stops a database the
previous engine started with that engine's tools: with the new engine's, it failed with "The Gem
and Stone versions are incompatible", and the only way out was reinstalling 1.9.0.
- **`gemdb file.py` writes Python's `sys.stderr` to stderr.** Warnings, tracebacks printed from
Python, logging and `print(..., file=sys.stderr)` went to stdout, so `2>` and pipes saw them in
the wrong stream.
Expand Down
10 changes: 10 additions & 0 deletions docs/automation-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,16 @@ unanswered, and the upgrade stops the database for minutes. Python support
and the MCP server are then installed again without a second question: the
upgrade removed their compiled methods, and the question already said so.

Stopping the previous engine's stone for the upgrade is Stop's own path
(`runStop`), question included: a stone other sessions are logged in to is
force-stopped only after **Stop Anyway**, as it would be by Stop. Those
sessions are usually other VS Code windows, each of which keeps one even with
no notebook open, and a window not reloaded since the update is still the
previous GemDB, so nothing closed in this window can release them. The stop
uses the engine that started each process (`engineThatStarted` in
`processes.ts`), since the new engine's `stopstone` cannot log in to the old
stone (4044).

**Choosing another root path when the default is on NFS — asked, once setup
has refused.** The stone will not open a repository on an NFS mount, and on
many shared Linux machines `~` is one (#69). Setup checks before downloading
Expand Down
139 changes: 135 additions & 4 deletions src/__integration__/engineUpgrade.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { execFileSync } from 'child_process';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { PINNED_ENGINE_VERSION, STONE_NAME } from '../config';
import { ChildProcess, execFileSync, spawn } from 'child_process';
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import * as vscode from 'vscode';
import { NETLDI_NAME, PINNED_ENGINE_VERSION, STONE_NAME } from '../config';
import { REPOSITORY_LIMIT_MB, createDatabase, repositoryVersion } from '../database';
import { EngineUpgradeError, upgradeBackupPath, upgradeEngine } from '../engineUpgrade';
import { engineUpgradeWorld } from '../lifecycle';
import { databaseConfPath, extentPath, grailStampPath, mcpStampPath } from '../paths';
import {
databaseConfPath,
databaseLogPath,
expectedEnginePath,
extentPath,
grailStampPath,
mcpStampPath,
} from '../paths';
import { listProcesses } from '../processes';
import { Fixture, makeFixture } from './fixture';

Expand Down Expand Up @@ -106,10 +114,96 @@ function makeOldDatabase(): void {
previousEngine('stopstone', [PREGROW_STONE, 'DataCurator', 'swordfish']);
}

/**
* Start GemDB's own stone and listener on the old database with the previous
* engine, as the previous GemDB left them running: they outlive the editor, so
* this is what an extension update finds.
*/
function startPreviousDatabase(): void {
const running = listProcesses();
if (!running.some((p) => p.type === 'stone' && p.name === STONE_NAME)) {
const conf = databaseConfPath();
previousEngine('startstone', [
'-z',
path.join(conf, 'system.conf'),
'-e',
path.join(conf, `${STONE_NAME}.conf`),
'-l',
path.join(databaseLogPath(), `${STONE_NAME}.log`),
STONE_NAME,
]);
}
if (!running.some((p) => p.type === 'netldi' && p.name === NETLDI_NAME)) {
previousEngine('startnetldi', [
'-a',
os.userInfo().username,
'-g',
'-l',
path.join(databaseLogPath(), `${NETLDI_NAME}.log`),
NETLDI_NAME,
]);
}
}

/**
* A session the previous engine's listener forked, standing for another window
* still running the previous GemDB: nothing this window logs out can end it,
* so a plain stopstone refuses while it is there. An RPC login, as a window's
* is, and not a linked topaz: a linked one holds the extent open itself until
* the process exits, which no window's session does. Settles once it is
* logged in.
*/
function holdPreviousSession(): Promise<ChildProcess> {
const gs = previous as string;
const port = listProcesses().find((p) => p.type === 'netldi' && p.name === NETLDI_NAME)?.port;
const topaz = spawn(path.join(gs, 'bin', 'topaz'), ['-q'], {
env: {
...process.env,
GEMSTONE: gs,
GEMSTONE_GLOBAL_DIR: (fixture as Fixture).root,
PATH: `${path.join(gs, 'bin')}:/usr/bin:/bin`,
},
});
held.push(topaz);
return new Promise((resolve, reject) => {
let output = '';
const timer = setTimeout(() => reject(new Error(`no login:\n${output}`)), 60_000);
const collect = (data: Buffer): void => {
output += data.toString();
if (/successful login/i.test(output)) {
clearTimeout(timer);
resolve(topaz);
}
};
topaz.stdout.on('data', collect);
topaz.stderr.on('data', collect);
topaz.on('exit', () => reject(new Error(`topaz exited:\n${output}`)));
topaz.stdin.write(
[
'set user DataCurator pass swordfish',
`set gemstone ${STONE_NAME}`,
`set gemnetid !tcp@localhost#netldi:${port}#task!gemnetobject`,
'login',
'',
].join('\n'),
);
});
}

const held: ChildProcess[] = [];

afterEach(() => {
vi.restoreAllMocks();
for (const topaz of held.splice(0)) topaz.kill('SIGKILL');
});

beforeAll(() => {
if (!ready) return;
fixture = makeFixture();
if (!fixture) return;
// Where the previous GemDB installed it, beside the pinned one: what lets a
// stone it started be stopped with its own stopstone.
fs.symlinkSync(previous as string, expectedEnginePath(from));
// What `upgradeScriptPath` looks for: <extension>/grail/scripts/upgrade_engine.sh.
extension = fs.mkdtempSync(path.join(os.tmpdir(), 'gemdb-it-ext-'));
fs.symlinkSync(path.resolve(grail), path.join(extension, 'grail'));
Expand Down Expand Up @@ -181,8 +275,40 @@ describe.skipIf(!ready)('upgrading a database an earlier GemDB made', () => {
fs.rmSync(backup, { force: true });
}, 600_000);

it('changes nothing when told not to disconnect a session the previous engine holds', async () => {
if (!fixture) return;
startPreviousDatabase();
await holdPreviousSession();
const before = fs.statSync(extentPath()).mtimeMs;
const warning = vi.spyOn(vscode.window, 'showWarningMessage');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: The "declined" answer here comes from the vscode mock's default showWarningMessage (which resolves undefined), so a reader can't see from the test itself that the user said no. Would .mockResolvedValue(undefined) be clearer? It would match the explicit 'Stop Anyway' in the next test and keep this test correct if the mock's default ever changes.

const { world: w } = world(true, from);

const run = upgradeEngine({ from, to: PINNED_ENGINE_VERSION, extent: extentPath() }, w);

await expect(run).rejects.toThrow(/nothing was changed.*Every VS Code window/);
expect(warning).toHaveBeenCalledWith(
expect.stringContaining('GemDB did not stop'),
{ modal: true },
'Stop Anyway',
);
expect(listProcesses().find((p) => p.type === 'stone')?.version).toBe(from);
// Left to the windows still using it, listener included: this engine's
// cannot serve that stone.
expect(listProcesses().find((p) => p.type === 'netldi')).toBeUndefined();
expect(fs.statSync(extentPath()).mtimeMs).toBe(before);
expect(fs.existsSync(upgradeBackupPath(extentPath(), from))).toBe(false);
}, 600_000);

it('upgrades it in place, keeps the original, and leaves nothing running', async () => {
if (!fixture) return;
// The stone the previous GemDB left running, with another window's
// session in it: stopped with the previous engine's own stopstone, once
// the user says Stop Anyway.
startPreviousDatabase();
await holdPreviousSession();
const warning = vi
.spyOn(vscode.window, 'showWarningMessage')
.mockResolvedValue('Stop Anyway' as unknown as vscode.MessageItem);
fs.mkdirSync(path.dirname(grailStampPath()), { recursive: true });
fs.writeFileSync(grailStampPath(), 'grail=old\n');
fs.mkdirSync(path.dirname(mcpStampPath()), { recursive: true });
Expand All @@ -194,6 +320,11 @@ describe.skipIf(!ready)('upgrading a database an earlier GemDB made', () => {
).resolves.toBe('upgraded');

expect(questions).toHaveLength(1);
expect(warning).toHaveBeenCalledWith(
expect.stringContaining('Every VS Code window running GemDB'),
{ modal: true },
'Stop Anyway',
);
expect(repositoryVersion((fixture as Fixture).engine)).toBe(PINNED_ENGINE_VERSION);
expect(fs.statSync(upgradeBackupPath(extentPath(), from)).size).toBe(CAP_BYTES);
expect(listProcesses()).toEqual([]);
Expand Down
77 changes: 77 additions & 0 deletions src/__tests__/engineThatStarted.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { __resetSettings, __setSetting } from '../__mocks__/vscode';
import { EngineProcess } from '../gslist';
import { engineDirName } from '../paths';
import { engineThatStarted, startedByAnotherEngine } from '../processes';

/**
* Which engine's tools stop a stone that is already running.
*
* Stones outlive the editor, so after an update moves the pin the stone still
* up is the previous engine's, and the new engine's stopstone cannot log in to
* it (4044). Stopping it with the wrong engine is what left a user unable to
* stop or upgrade their database without reinstalling the old GemDB.
*/

const PIN = '4.0.0.a8';
const PREVIOUS = '4.0.0.a5';

function stone(version: string): EngineProcess {
return { type: 'stone', name: 'gemdb', version, pid: 101, status: 'OK', responding: true };
}

let root: string;

beforeEach(() => {
__resetSettings();
root = fs.mkdtempSync(path.join(os.tmpdir(), 'gemdb-engine-'));
__setSetting('gemdb.rootPath', root);
__setSetting('gemdb.engineVersion', PIN);
});

afterEach(() => {
fs.rmSync(root, { recursive: true, force: true });
});

function install(version: string): string {
const dir = path.join(root, engineDirName(version));
fs.mkdirSync(dir);
return dir;
}

describe('the engine that stops a running database', () => {
it('is the pinned one for a stone the pinned engine started', () => {
install(PIN);

expect(startedByAnotherEngine(stone(PIN))).toBe(false);
expect(engineThatStarted(stone(PIN))).toBeUndefined();
});

it('is the previous one for a stone the previous engine started', () => {
install(PIN);
const previous = install(PREVIOUS);

expect(startedByAnotherEngine(stone(PREVIOUS))).toBe(true);
expect(engineThatStarted(stone(PREVIOUS))).toBe(previous);
});

it('falls back to the pinned one when the previous engine is gone', () => {
install(PIN);

expect(engineThatStarted(stone(PREVIOUS))).toBeUndefined();
});

it('takes a version the process list cut short for the pinned one', () => {
__setSetting('gemdb.engineVersion', '4.0.0.Alpha1');

expect(startedByAnotherEngine(stone('4.0.0.Alpha'))).toBe(false);
});

it('is the pinned one when nothing is running', () => {
expect(startedByAnotherEngine(undefined)).toBe(false);
expect(engineThatStarted(undefined)).toBeUndefined();
});
});
48 changes: 29 additions & 19 deletions src/__tests__/engineUpgrade.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,15 @@ function makeWorld(options: {
confirm?: boolean;
noRoom?: boolean;
stoneUp?: boolean;
listenerUp?: boolean;
/** The stop fails outright, as a login refused by the stone does. */
stoneWillNotStop?: boolean;
/** The stop settles with the stone still up, as a declined Stop Anyway does. */
stopDeclined?: boolean;
scriptFails?: string;
/** What copydbf reads after the script, success or failure. */
versionAfter?: string | undefined;
}): { calls: string[]; reports: string[]; world: UpgradeWorld } {
let stoneUp = options.stoneUp ?? false;
let listenerUp = options.listenerUp ?? false;
const calls: string[] = [];
const reports: string[] = [];
const world: UpgradeWorld = {
Expand All @@ -65,18 +66,11 @@ function makeWorld(options: {
calls.push('unlock');
}
},
logout: () => calls.push('logout'),
stoneUp: () => stoneUp,
listenerUp: () => listenerUp,
stopStone: () => {
calls.push('stopStone');
stopDatabase: () => {
calls.push('stopDatabase');
if (options.stoneWillNotStop) return Promise.reject(new Error('login failed'));
stoneUp = false;
return Promise.resolve();
},
stopNetldi: () => {
calls.push('stopNetldi');
listenerUp = false;
if (!options.stopDeclined) stoneUp = false;
return Promise.resolve();
},
runScript: (report) => {
Expand Down Expand Up @@ -126,29 +120,27 @@ describe('the backup and the progress lines', () => {

describe('upgrading the database', () => {
it('asks first, and touches nothing when the answer is no', async () => {
const { calls, world } = makeWorld({ confirm: false, stoneUp: true, listenerUp: true });
const { calls, world } = makeWorld({ confirm: false, stoneUp: true });
await expect(upgradeEngine(PLAN, world)).resolves.toBe('declined');
expect(calls).toEqual([`confirm(4.0.0.a5,4.0.0.a8,${BACKUP})`]);
});

it('refuses before stopping anything when the disk cannot hold the backup', async () => {
const { calls, world } = makeWorld({ noRoom: true, stoneUp: true });
await expect(upgradeEngine(PLAN, world)).rejects.toThrow(DiskSpaceError);
expect(calls).not.toContain('stopStone');
expect(calls).not.toContain('stopDatabase');
expect(calls).not.toContain('script');
});

it('stops the previous engine’s processes, under the lock, before the script runs', async () => {
const { calls, reports, world } = makeWorld({ stoneUp: true, listenerUp: true });
it('stops the database, under the lock, before the script runs', async () => {
const { calls, reports, world } = makeWorld({ stoneUp: true });
await expect(upgradeEngine(PLAN, world)).resolves.toBe('upgraded');
expect(calls).toEqual([
`confirm(4.0.0.a5,4.0.0.a8,${BACKUP})`,
'room',
'progress',
'lock',
'logout',
'stopStone',
'stopNetldi',
'stopDatabase',
'script',
'copydbf',
'unlock',
Expand All @@ -174,6 +166,24 @@ describe('upgrading the database', () => {
expect(calls.at(-1)).toBe('unlock');
});

it('changes nothing when the user will not disconnect the sessions in the way', async () => {
const { calls, world } = makeWorld({ stoneUp: true, stopDeclined: true });

const result = upgradeEngine(PLAN, world);

await expect(result).rejects.toThrow(/nothing was changed/);
expect(calls).not.toContain('script');
expect(calls).not.toContain('forgetInstalls');
});

it('names other editor windows as what may be holding the database open', async () => {
const { world } = makeWorld({ stoneUp: true, stopDeclined: true });

const result = upgradeEngine(PLAN, world);

await expect(result).rejects.toThrow(/Every VS Code window running GemDB/);
});

it('says the database is back as it was when the script restored it', async () => {
const { calls, world } = makeWorld({ scriptFails: 'upgradeImage failed; extent restored' });
const result = upgradeEngine(PLAN, world);
Expand Down
2 changes: 2 additions & 0 deletions src/__tests__/engineUpgradeStart.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ vi.mock('../processes', () => ({
findStone: () => true,
findNetldi: () => true,
engineEnvironment: () => ({}),
engineThatStarted: () => undefined,
startedByAnotherEngine: () => false,
ensureProcesses: () => ensureProcesses(),
isListening: () => true,
isRunning: () => true,
Expand Down
Loading
Loading