GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Merge pull request #4164 from lidge-jun/lane-a/3-4141 · lidge-jun/opencodex@95a3f6a

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • src
    • service.ts
  • tests/service
    • service.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎src/service.ts‎

Copy file name to clipboardExpand all lines: src/service.ts
+47-7Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2338,7 +2338,23 @@ export function readWindowsSchedulerXmlState(
23382338
}
23392339

23402340
// ── macOS (launchd) ──
2341-
function installLaunchd(): void {
2341+
/**
2342+
* Deps follow {@link startLaunchd}: `launchctl` replaces the LAYER, returning a
2343+
* {@link runLaunchctl} result, not a spawnSync result. It is optional so this stays
2344+
* assignable to `ServiceOps.install` and `RepairServiceDeps.repairLaunchd`
2345+
* (`() => void`), and so `platformOps` wires the same function the tests exercise.
2346+
*
2347+
* The seam is what makes the eviction below testable at all. The live-service-manager
2348+
* guard refuses every mutating verb from an armed test process and `bootout` is not on
2349+
* its read-only list, so a test reaching the real runner would fail closed on the guard
2350+
* instead of exercising the sequence.
2351+
*
2352+
* No `matches` dep: unlike `startLaunchd`, this function never consults
2353+
* {@link launchdJobMatchesPlist}. It has just rewritten the plist, so a live job is stale
2354+
* by construction and there is nothing to compare against.
2355+
*/
2356+
export function installLaunchd(deps: { launchctl?: typeof runLaunchctl } = {}): void {
2357+
const run = deps.launchctl ?? runLaunchctl;
23422358
const dir = join(homedir(), "Library", "LaunchAgents");
23432359
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
23442360
recordOwnedConfigPath(getConfigDir(), serviceStatePath());
@@ -2352,17 +2368,41 @@ function installLaunchd(): void {
23522368
// so the staleness diagnostic judges exactly what launchd runs.
23532369
const launcher = stableLauncherEntry();
23542370
writeServiceDefinitionFile(p, buildPlist(resolvedProxyEnv(), { launcher }), "utf8");
2355-
// Best-effort: an absent job is fine here, and a failed unload is caught by the
2356-
// load verification below with a better message than a raw unload error.
2357-
runLaunchctl(["unload", p]);
2358-
const loaded = runLaunchctl(["load", "-w", p]);
2371+
// `unload` is the legacy verb and it does not evict a job bootstrapped into the GUI
2372+
// domain — which is precisely the state that could not repair itself. Modern launchd
2373+
// answers `load -w` for an already-bootstrapped job with "Load failed: 5:
2374+
// Input/output error" AND exits 0, so `ocx update` replaced the binary, ran repair,
2375+
// and left launchd running the PREVIOUS job while the fresh plist sat unused (#4141).
2376+
//
2377+
// This EVICTS the running job. That is the repair being asked for, and it is why it
2378+
// lives here and nowhere else: `installLaunchd` has already rewritten the plist, so
2379+
// whatever is loaded is stale by construction. `ocx service start` must never do
2380+
// this, and `startLaunchd` accordingly still refuses to.
2381+
//
2382+
// Absence is fine: booting out a job that is not there is a no-op, and a real failure
2383+
// is reported by the load verification below with a better message than a raw
2384+
// eviction error would carry.
2385+
const bootoutTarget = `${launchdGuiDomain()}/${LABEL}`;
2386+
run(["bootout", bootoutTarget]);
2387+
let loaded = run(["load", "-w", p]);
2388+
if (launchctlLoadFailed(loaded.stderr)) {
2389+
// Still bootstrapped after an eviction: the job re-registered between the two calls,
2390+
// or the first `bootout` raced a job that had not finished exiting. Evict and load
2391+
// once more — ONCE. A bounded retry recovers the race; a loop would turn a genuinely
2392+
// wedged domain into a hang instead of the diagnosable throw below.
2393+
run(["bootout", bootoutTarget]);
2394+
loaded = run(["load", "-w", p]);
2395+
}
23592396
if (!loaded.ok || launchctlLoadFailed(loaded.stderr)) {
23602397
// Do NOT write install state for a load that did not take: state describing an
23612398
// unused plist is what made this failure invisible.
23622399
throw new Error(
23632400
`launchctl could not load ${p}: ${loaded.stderr || "load reported failure"}\n`
2364-
+ "A previous job may still be bootstrapped. Try:\n"
2365-
+ ` launchctl bootout ${launchdGuiDomain()}/${LABEL}\n`
2401+
// The hint used to tell the operator to run `bootout` by hand. It now runs twice
2402+
// above, so naming it as an untried remedy would send someone to repeat what just
2403+
// failed. Report what was attempted instead.
2404+
+ `A previous job is still bootstrapped after two attempts to boot it out of ${launchdGuiDomain()}.\n`
2405+
+ `Inspect it with:\n launchctl print ${bootoutTarget}\n`
23662406
// macOS `service repair` delegates straight to installLaunchd, so this fires for
23672407
// an already-installed service too; repair reloads it without re-registering.
23682408
+ `then re-run '${wasInstalled ? "ocx service repair" : "ocx service install"}'.`,
Collapse file

‎tests/service/service.test.ts‎

Copy file name to clipboardExpand all lines: tests/service/service.test.ts
+138-1Lines changed: 138 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { saveConfig } from "../../src/config";
99
import { windowsEnvIndirectBatchValue } from "../../src/lib/win-paths";
1010
import { assertServiceAuthEnvironment, assertServiceEnvironmentMatchesInstall, bakedServicePathsDiagnostic, confirmServiceServing, launchdListenPort, systemdListenPort, buildPlist, buildUnit, buildWindowsLauncherVbs, buildWindowsSchtasksCreateArgs, buildWindowsSchtasksCreateArgsForXml, buildWindowsServiceScript, buildWindowsTaskXml as buildWindowsTaskXmlProduction, buildWindowsTaskXmlDocument, deriveWindowsServiceDiagnostic, deriveWindowsServiceDiagnosticForCurrentUser, expectedLaunchdCommand, installFreshWindowsSchedulerSafely, installServiceSafely, launchctlLoadFailed, launchdJobMatchesPlist, normalizeServiceSubcommand, parseServiceArgs, parseServiceInstallState, planServiceCommand, prepareServiceInstall, probeServiceInstallation, readWindowsSchedulerXmlState, registerFreshWindowsSchedulerTask, removeNativeWindowsServiceForScheduler, repairService, reportServiceServing, resolveServiceListenPort, runLaunchctl, selectServiceSubcommand, SERVICE_INSTALL_HEALTH_MS, SERVICE_INSTALL_HEALTH_WINDOWS_MS, serviceInstallHealthMs, serviceLogPath, serviceStartableFromTray, serviceStatusReport, serviceRetryCommand, serviceStatusSummary, stableLauncherEntry, systemdNeedsDaemonReload, systemdServiceInstallCleanupOps, uninstallSystemd, windowsListenPort, winswListenPort, startLaunchd, windowsTaskRegistrationHealthy as windowsTaskRegistrationHealthyProduction } from "../../src/service";
1111
import type { ServiceDiagnostic } from "../../src/service";
12-
import { definitionCarriesCredential, resolvedProxyEnv, writeServiceDefinitionFile } from "../../src/service";
12+
import { definitionCarriesCredential, installLaunchd, resolvedProxyEnv, writeServiceDefinitionFile } from "../../src/service";
1313
import { buildWinswXml } from "../../src/lib/winsw";
1414
import { CONFIG_OWNER_FILE, CONFIG_UNINSTALL_MANIFEST, recordOwnedConfigPath, removeOwnedConfigState } from "../../src/lib/config-ownership";
1515
import { serviceApiTokenFilePath } from "../../src/lib/service-secrets";
@@ -3326,6 +3326,143 @@ describe("launchctl load verification", () => {
33263326
})).toThrow(/service repair/);
33273327
});
33283328
});
3329+
3330+
/**
3331+
* #4141: after `ocx update` the job never came back. Repair on darwin is
3332+
* `installLaunchd`, which best-effort `unload`ed the plist and then threw on any
3333+
* `Load failed`. But `unload` does not evict a job bootstrapped into the GUI domain,
3334+
* and that is exactly the state modern launchd reports with "Load failed: 5:
3335+
* Input/output error" while exiting 0 — so a live-but-stale job was precisely the case
3336+
* that could not repair itself, and the thrown text carried the `bootout` recipe as a
3337+
* hint that nothing ever ran.
3338+
*
3339+
* These drive the injected seam. They never reach launchd: the live-service-manager
3340+
* guard refuses `bootout` from an armed test process, so a test on the real runner
3341+
* would fail closed on the guard rather than exercise anything.
3342+
*/
3343+
describe("installLaunchd", () => {
3344+
// A runLaunchctl RESULT, not a spawnSync result.
3345+
function recordingLaunchctl(loadResults: Array<{ ok: boolean; stderr: string }>) {
3346+
const argv: string[][] = [];
3347+
let loads = 0;
3348+
const launchctl = ((args: string[]) => {
3349+
argv.push([...args]);
3350+
if (args[0] !== "load") return { ok: true, stdout: "", stderr: "", status: 0 };
3351+
// Exhausting the queue is a fixture bug, not a passing case. Defaulting a missing
3352+
// entry to success once hid a retry that never got the failure it was meant to
3353+
// assert, so make the fixture state its own call count or fail loudly.
3354+
const next = loadResults[loads++];
3355+
if (!next) throw new Error(`unexpected load #${loads}: the fixture queued ${loadResults.length}`);
3356+
return { ok: next.ok, stdout: "", stderr: next.stderr, status: next.ok ? 0 : 1 };
3357+
}) as typeof runLaunchctl;
3358+
return { argv, launchctl };
3359+
}
3360+
3361+
const BOOTSTRAPPED = "Load failed: 5: Input/output error";
3362+
3363+
/**
3364+
* installLaunchd writes the plist under `homedir()/Library/LaunchAgents`. The preload
3365+
* already sandboxes HOME; pinning a fresh one per case keeps these from writing into
3366+
* whatever another test left there.
3367+
*/
3368+
function withLaunchAgentHome(run: () => void): void {
3369+
const previousHome = process.env.HOME;
3370+
const previousUserProfile = process.env.USERPROFILE;
3371+
const dir = mkdtempSync(join(tmpdir(), "ocx-launchd-install-"));
3372+
process.env.HOME = dir;
3373+
process.env.USERPROFILE = dir;
3374+
try {
3375+
run();
3376+
} finally {
3377+
if (previousHome === undefined) delete process.env.HOME;
3378+
else process.env.HOME = previousHome;
3379+
if (previousUserProfile === undefined) delete process.env.USERPROFILE;
3380+
else process.env.USERPROFILE = previousUserProfile;
3381+
}
3382+
}
3383+
3384+
const verbs = (argv: string[][]): string[] => argv.map(args => args[0] ?? "");
3385+
3386+
test("evicts a stale job, and recovers on the retried load", () => {
3387+
const { argv, launchctl } = recordingLaunchctl([
3388+
{ ok: true, stderr: BOOTSTRAPPED },
3389+
{ ok: true, stderr: "" },
3390+
]);
3391+
3392+
withLaunchAgentHome(() => {
3393+
expect(() => installLaunchd({ launchctl })).not.toThrow();
3394+
});
3395+
3396+
// The whole repair, in order. Red before the fix: it threw on the first
3397+
// `Load failed` without ever running `bootout`.
3398+
expect(verbs(argv)).toEqual(["bootout", "load", "bootout", "load"]);
3399+
// The legacy verb is gone: it is what failed to evict the job in the first place.
3400+
expect(verbs(argv)).not.toContain("unload");
3401+
expect(argv[0]?.[1]).toMatch(/^gui\/\d+\/com\.opencodex\.proxy$/);
3402+
expect(argv[2]?.[1]).toBe(argv[0]?.[1]);
3403+
expect(argv[1]?.slice(0, 2)).toEqual(["load", "-w"]);
3404+
expect(argv[3]?.slice(0, 2)).toEqual(["load", "-w"]);
3405+
});
3406+
3407+
test("a clean load is never retried, so a healthy job is evicted once and reloaded", () => {
3408+
const { argv, launchctl } = recordingLaunchctl([{ ok: true, stderr: "" }]);
3409+
3410+
withLaunchAgentHome(() => {
3411+
expect(() => installLaunchd({ launchctl })).not.toThrow();
3412+
});
3413+
3414+
expect(verbs(argv)).toEqual(["bootout", "load"]);
3415+
});
3416+
3417+
test("still throws when the job survives both evictions", () => {
3418+
const { argv, launchctl } = recordingLaunchctl([
3419+
{ ok: true, stderr: BOOTSTRAPPED },
3420+
{ ok: true, stderr: BOOTSTRAPPED },
3421+
]);
3422+
3423+
withLaunchAgentHome(() => {
3424+
expect(() => installLaunchd({ launchctl })).toThrow(/could not load/);
3425+
});
3426+
3427+
// Bounded: two evictions and two loads, then the diagnosable throw. A loop here
3428+
// would turn a wedged domain into a hang.
3429+
expect(verbs(argv)).toEqual(["bootout", "load", "bootout", "load"]);
3430+
});
3431+
3432+
/**
3433+
* `launchctlLoadFailed` matches "Bootstrap failed" as well as "Load failed", and both
3434+
* mean the same thing here: something is still bootstrapped in the domain. So this
3435+
* retries, and the regex itself is left alone — it is the 2026-08-02 silent-success
3436+
* guard, and the fix is to recover from the condition rather than stop detecting it.
3437+
*/
3438+
test("a Bootstrap failed load takes the same eviction and retry", () => {
3439+
const bootstrapFailed = { ok: false, stderr: "Bootstrap failed: 37: Operation already in progress" };
3440+
const { argv, launchctl } = recordingLaunchctl([bootstrapFailed, bootstrapFailed]);
3441+
3442+
withLaunchAgentHome(() => {
3443+
expect(() => installLaunchd({ launchctl })).toThrow(/could not load/);
3444+
});
3445+
3446+
expect(verbs(argv)).toEqual(["bootout", "load", "bootout", "load"]);
3447+
});
3448+
3449+
/**
3450+
* The retry is scoped to that signal on purpose. A load that fails for another
3451+
* reason — a malformed plist, say — is not fixed by evicting a job, so retrying
3452+
* would only delay the real stderr reaching the operator.
3453+
*/
3454+
test("a plain non-zero load with unrelated stderr throws without a second eviction", () => {
3455+
const { argv, launchctl } = recordingLaunchctl([
3456+
{ ok: false, stderr: "Could not read plist: invalid XML" },
3457+
]);
3458+
3459+
withLaunchAgentHome(() => {
3460+
expect(() => installLaunchd({ launchctl })).toThrow(/invalid XML/);
3461+
});
3462+
3463+
expect(verbs(argv)).toEqual(["bootout", "load"]);
3464+
});
3465+
});
33293466
});
33303467

33313468
/**

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.