fix(dsh): adopt a same-origin leftover service record instead of orphaning it

A record left by an older version under a path prefix of the same origin
(`/reme`) describes the service the endpoint on screen talks to: the launch
configures only host and port. The record was nevertheless judged foreign,
because the ownership check compares the full endpoint key while the
same-origin replacement compares the origin.

The Host now re-keys such a record to the endpoint on screen, so the tab can
stop it and a start can replace it. The conflict branch falls back to the
same guard when the record could not be re-keyed. The adoption compares and
writes the record without yielding, so a launch that records its own pid
while the ownership probe runs is never overwritten.
This commit is contained in:
LiangshouX 2026-11-03 10:17:51 +08:00
parent ca4a06339a
commit 80cd5041bf
2 changed files with 296 additions and 23 deletions

View file

@ -23,8 +23,9 @@ import {
serviceStatus,
startService,
stopService,
writeServiceState,
} from "./service.js";
import type { ServiceIO } from "./service.js";
import type { PersistedService, ServiceIO } from "./service.js";
import {
envSummary,
mergeEnvFile,
@ -208,6 +209,11 @@ export class ReMeEnvManager {
/** Current service phase (running / conflict / stopped) and ownership. */
async serviceStatus(endpoint: string, authToken = ""): Promise<ServiceState> {
const endpointValue = this.endpoint(endpoint);
// A record left under a path prefix of the same origin describes the
// service this endpoint talks to. It is re-keyed to the endpoint on screen
// first, so the tab can manage (stop) it and the start path can replace
// it instead of treating our own service as a foreign process.
await this.adoptLeftover(endpointValue);
const persisted = readServiceState(this.serviceStatePath);
// A malformed record must not turn the log path into a relative one.
let logDir = resolveWorkspaceDir("", homedir());
@ -406,6 +412,11 @@ export class ReMeEnvManager {
}
private async stopLocked(endpointValue: string): Promise<ServiceStopResult> {
// A leftover record under a path prefix of the same origin is this
// service: it is re-keyed first, so a stop that arrives before any
// status read still acts on the right record instead of refusing it as
// foreign.
await this.adoptLeftover(endpointValue);
const result = await stopService(this.serviceIO, {
statePath: this.serviceStatePath,
endpoint: endpointValue,
@ -429,6 +440,79 @@ export class ReMeEnvManager {
}
}
/**
* A leftover record that names the same local service as the endpoint on
* screen.
*
* The launch configures only host and port, so two endpoints on the same
* origin name the same local process even when their paths differ. A record
* left by a version that still launched prefixed endpoints (for example
* `/reme`) therefore describes the service the endpoint on screen talks to.
* It is returned only when it is provably ours: the same origin, a live
* pid, a Python image and a command line that carries the recorded
* `workspace_dir` and `service.port`.
*
* A request that cannot launch anything never gets one: a prefixed request
* is refused by `buildStartCommand`, so stopping a healthy same-origin
* service first would leave nothing running (autoStart would do that on
* every DSH start).
*/
private async leftoverService(
endpointValue: string,
): Promise<PersistedService | undefined> {
if (!this.launchable(endpointValue)) return undefined;
const recorded = readServiceState(this.serviceStatePath);
if (!recorded || recorded.pid === undefined) return undefined;
// A record filed under the endpoint on screen is not a leftover.
if (
serviceEndpointKey(recorded.endpoint) ===
serviceEndpointKey(endpointValue)
)
return undefined;
if (serviceOriginKey(recorded.endpoint) !== serviceOriginKey(endpointValue))
return undefined;
if (!processAlive(this.serviceIO, recorded.pid)) return undefined;
const ownership = await serviceOwnership(
this.serviceIO,
recorded,
recorded.endpoint,
);
return ownership === "owned" ? recorded : undefined;
}
/**
* Re-key a leftover same-origin record to the endpoint on screen.
*
* Only the endpoint the record is filed under changes: it stays the record
* of the same process, so the tab can stop it and the start path can replace
* it. A failed write is not fatal — the start path can still replace the
* record by its own endpoint.
*
* The record is compared and written without yielding in between: the
* ownership probe above takes long enough for a launch to record a new pid,
* and overwriting that record would orphan the fresh service. The compare
* and the write are synchronous, so nothing can slip in between them.
*/
private async adoptLeftover(endpointValue: string): Promise<void> {
const leftover = await this.leftoverService(endpointValue);
if (!leftover) return;
const current = readServiceState(this.serviceStatePath);
if (
!current ||
current.pid !== leftover.pid ||
current.endpoint !== leftover.endpoint
)
return;
try {
writeServiceState(this.serviceStatePath, {
...current,
endpoint: endpointValue,
});
} catch {
// The record keeps its old endpoint; the start path replaces it anyway.
}
}
private async startLocked(
endpoint: string,
pythonPath: string,
@ -476,28 +560,52 @@ export class ReMeEnvManager {
// The port is answered by something that is not a healthy service. A
// provable launch of ours (still booting or rejecting our token) is
// stopped and replaced; anything else is left alone.
if (!current.managed)
return this.refused(
logPath,
now,
"conflict",
"Another process is already listening on this endpoint",
);
const previous = await stopService(this.serviceIO, {
statePath: this.serviceStatePath,
endpoint: endpointValue,
ownership: "owned",
});
if (!previous.stopped)
return this.refused(
logPath,
now,
"previous-not-stopped",
`A previous launch could not be stopped: ${
previous.reason ?? "unknown reason"
}`,
{ record: previous.record },
);
if (!current.managed) {
// The port may be held by a leftover record of ours that is filed
// under a path prefix of the same origin. The endpoint on screen
// cannot stop that record (it names another endpoint) and the
// conflict card offers no way out, so it is replaced here instead of
// leaving the user with a process to kill by hand.
const leftover = await this.leftoverService(endpointValue);
if (!leftover)
return this.refused(
logPath,
now,
"conflict",
"Another process is already listening on this endpoint",
);
const replaced = await stopService(this.serviceIO, {
statePath: this.serviceStatePath,
endpoint: leftover.endpoint,
ownership: "owned",
});
if (!replaced.stopped)
return this.refused(
logPath,
now,
"previous-not-stopped",
`A previous launch could not be stopped: ${
replaced.reason ?? "unknown reason"
}`,
{ record: replaced.record },
);
} else {
const previous = await stopService(this.serviceIO, {
statePath: this.serviceStatePath,
endpoint: endpointValue,
ownership: "owned",
});
if (!previous.stopped)
return this.refused(
logPath,
now,
"previous-not-stopped",
`A previous launch could not be stopped: ${
previous.reason ?? "unknown reason"
}`,
{ record: previous.record },
);
}
}
// A record for a *different* endpoint that is still alive would be
// overwritten by the new launch, leaving that endpoint unable to stop it.

View file

@ -433,6 +433,171 @@ test("replaces a leftover launch recorded under a same-origin path prefix", asyn
assert.equal(readServiceState(statePath)?.pid, 5001);
});
test("adopts a leftover record under a same-origin path prefix", async (t) => {
// The leftover record was filed under `…/reme`, but the launch configures
// only host and port, so it is the service the endpoint on screen talks to.
// It must be re-keyed to that endpoint: otherwise it looks foreign, the tab
// offers no Stop, and the record lingers until the process exits.
const { manager, calls, directory, io } = managerIn(t);
// The real status read: the leftover is only adopted by the Host itself.
manager.serviceStatus = ReMeEnvManager.prototype.serviceStatus;
const statePath = join(directory, "reme-memory", "service.json");
writeServiceState(statePath, {
pid: 6000,
endpoint: "http://127.0.0.1:2334/reme",
workspaceDir: directory,
pythonPath: "D:\\env\\python.exe",
command: "reme start",
startedAt: "2026-10-27T00:00:00.000Z",
});
let running = true;
io.probePid = () => {
if (!running) throw new Error("ESRCH");
};
io.killTree = (pid) => {
calls.killTree.push(pid);
running = false;
};
io.processCommandLine = async () =>
`reme start workspace_dir=${directory} service.port=2334`;
io.fetchHealth = async () => ({ ok: true, version: "0.4.2.1", error: "" });
const status = await manager.serviceStatus("http://127.0.0.1:2334");
assert.equal(status.phase, "running");
assert.equal(status.managed, true, "the leftover is ours to manage");
assert.equal(status.pid, 6000);
assert.equal(
readServiceState(statePath)?.endpoint,
"http://127.0.0.1:2334",
"the record is filed under the endpoint on screen",
);
// The adopted record is stoppable: the endpoint on screen can act on it.
const stopped = await manager.serviceStop("http://127.0.0.1:2334");
assert.equal(stopped.stopped, true);
assert.deepEqual(calls.killTree, [6000]);
assert.equal(readServiceState(statePath), undefined);
});
test("replaces a leftover launch that holds the port without being healthy", async (t) => {
// The leftover record was filed under `…/reme` and its process occupies the
// port without answering the health check. The endpoint on screen cannot
// stop that record (it names another endpoint) and the conflict card offers
// no way out, so the start must replace it instead of refusing.
const { manager, calls, directory, io } = managerIn(t);
manager.serviceStatus = ReMeEnvManager.prototype.serviceStatus;
const statePath = join(directory, "reme-memory", "service.json");
writeServiceState(statePath, {
pid: 6000,
endpoint: "http://127.0.0.1:2334/reme",
workspaceDir: directory,
pythonPath: "D:\\env\\python.exe",
command: "reme start",
startedAt: "2026-10-27T00:00:00.000Z",
});
let running = true;
io.probePid = () => {
if (!running) throw new Error("ESRCH");
};
io.killTree = (pid) => {
calls.killTree.push(pid);
running = false;
};
io.processCommandLine = async () =>
`reme start workspace_dir=${directory} service.port=2334`;
// The port answers, but the service behind it is not healthy.
io.fetchHealth = async () => ({ ok: false, version: "", error: "boom" });
io.portOpen = async () => true;
const status = await manager.serviceStatus("http://127.0.0.1:2334");
assert.equal(status.phase, "conflict");
assert.equal(status.managed, true, "the leftover is ours to manage");
assert.equal(status.pid, 6000);
const result = await manager.serviceStart(
"http://127.0.0.1:2334",
"D:\\env\\python.exe",
join(directory, "workspace"),
);
assert.equal(result.started, true);
assert.deepEqual(calls.killTree, [6000], "the leftover is stopped first");
assert.equal(calls.spawn.length, 1);
assert.equal(readServiceState(statePath)?.pid, 5001);
});
test("adopting a leftover never overwrites a record that changed meanwhile", async (t) => {
// The ownership probe reads the process command line, which takes long
// enough for another launch to record its own service. The adoption must
// not write the record it read before the probe: that would orphan the
// fresh service, or re-key a record that belongs to another endpoint.
const { manager, directory, io } = managerIn(t);
manager.serviceStatus = ReMeEnvManager.prototype.serviceStatus;
const statePath = join(directory, "reme-memory", "service.json");
writeServiceState(statePath, {
pid: 6000,
endpoint: "http://127.0.0.1:2334/reme",
workspaceDir: directory,
pythonPath: "D:\\env\\python.exe",
command: "reme start",
startedAt: "2026-10-27T00:00:00.000Z",
});
// Another launch records its own service while the ownership probe runs.
io.processCommandLine = async () => {
writeServiceState(statePath, {
pid: 7000,
endpoint: "http://127.0.0.1:2335",
workspaceDir: directory,
pythonPath: "D:\\env\\python.exe",
command: "reme start",
startedAt: "2026-10-27T00:01:00.000Z",
});
return `reme start workspace_dir=${directory} service.port=2334`;
};
await manager.serviceStatus("http://127.0.0.1:2334");
assert.equal(
readServiceState(statePath)?.pid,
7000,
"the newer record survives the adoption",
);
assert.equal(
readServiceState(statePath)?.endpoint,
"http://127.0.0.1:2335",
"and it is not re-keyed to another endpoint",
);
});
test("a stop acts on a leftover record without a prior status read", async (t) => {
// The Host must not depend on the client having read the status first: the
// stop itself re-keys the leftover, so it stops the right process instead of
// refusing the record as foreign.
const { manager, calls, directory, io } = managerIn(t);
const statePath = join(directory, "reme-memory", "service.json");
writeServiceState(statePath, {
pid: 6000,
endpoint: "http://127.0.0.1:2334/reme",
workspaceDir: directory,
pythonPath: "D:\\env\\python.exe",
command: "reme start",
startedAt: "2026-10-27T00:00:00.000Z",
});
let running = true;
io.probePid = () => {
if (!running) throw new Error("ESRCH");
};
io.killTree = (pid) => {
calls.killTree.push(pid);
running = false;
};
io.processCommandLine = async () =>
`reme start workspace_dir=${directory} service.port=2334`;
const stopped = await manager.serviceStop("http://127.0.0.1:2334");
assert.equal(stopped.stopped, true);
assert.deepEqual(calls.killTree, [6000]);
assert.equal(readServiceState(statePath), undefined);
});
test("a prefixed request never stops the healthy service it cannot replace", async (t) => {
// A prefixed endpoint can never be launched: the launch sets only host and
// port, so the request is refused later anyway. Replacing the same-origin