Skip to content

Commit 76f9b6d

Browse files
fix(gateway): surface systemd start-limit exhaustion (#98291)
* fix(gateway): surface systemd start-limit exhaustion * fix(gateway): avoid start-limit false positive for exit 78
1 parent a9945d1 commit 76f9b6d

8 files changed

Lines changed: 450 additions & 10 deletions

File tree

‎src/cli/daemon-cli/status.print.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -727,4 +727,65 @@ describe("printDaemonStatus", () => {
727727
expect(errors).not.toContain("systemd user services unavailable");
728728
expect(errors).not.toContain("run loginctl enable-linger");
729729
});
730+
731+
it("warns that systemd gave up restarting a crash-looped gateway", () => {
732+
const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux");
733+
try {
734+
printDaemonStatus(
735+
{
736+
service: {
737+
label: "systemd",
738+
loaded: true,
739+
loadedText: "loaded",
740+
notLoadedText: "not loaded",
741+
runtime: {
742+
status: "stopped",
743+
state: "failed",
744+
systemd: { result: "exit-code", nRestarts: 5, startLimitBurst: 5 },
745+
},
746+
},
747+
extraServices: [],
748+
},
749+
{ json: false },
750+
);
751+
} finally {
752+
platform.mockRestore();
753+
}
754+
755+
const errors = runtime.error.mock.calls.map(([line]) => line).join("\n");
756+
expect(errors).toContain("systemd stopped restarting the gateway after repeated crashes");
757+
expect(errors).not.toContain("likely exited immediately");
758+
});
759+
760+
it("keeps the generic stopped message after a config exit (78) despite a stale restart count", () => {
761+
// RestartPreventExitStatus=78 stopped systemd deliberately; a leftover
762+
// NRestarts must not surface start-limit recovery guidance here.
763+
const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux");
764+
try {
765+
printDaemonStatus(
766+
{
767+
service: {
768+
label: "systemd",
769+
loaded: true,
770+
loadedText: "loaded",
771+
notLoadedText: "not loaded",
772+
runtime: {
773+
status: "stopped",
774+
state: "failed",
775+
lastExitStatus: 78,
776+
systemd: { result: "exit-code", nRestarts: 5, startLimitBurst: 5 },
777+
},
778+
},
779+
extraServices: [],
780+
},
781+
{ json: false },
782+
);
783+
} finally {
784+
platform.mockRestore();
785+
}
786+
787+
const errors = runtime.error.mock.calls.map(([line]) => line).join("\n");
788+
expect(errors).toContain("Service is loaded but not running (likely exited immediately).");
789+
expect(errors).not.toContain("systemd stopped restarting the gateway");
790+
});
730791
});

‎src/cli/daemon-cli/status.print.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
resolveGatewayRestartLogPath,
1111
resolveGatewaySupervisorLogPaths,
1212
} from "../../daemon/restart-logs.js";
13+
import { isSystemdStartLimitHit } from "../../daemon/service-runtime.js";
1314
import {
1415
isSystemdUnavailableDetail,
1516
renderSystemdUnavailableHints,
@@ -366,8 +367,17 @@ export function printDaemonStatus(status: DaemonStatus, opts: { json: boolean; d
366367
defaultRuntime.error(errorText(hint));
367368
}
368369
} else if (service.loaded && service.runtime?.status === "stopped") {
370+
const startLimitHit = process.platform === "linux" && isSystemdStartLimitHit(service.runtime);
369371
defaultRuntime.error(
370-
errorText("Service is loaded but not running (likely exited immediately)."),
372+
errorText(
373+
startLimitHit
374+
? // systemd gave up restarting after repeated crashes; sending the operator
375+
// to restart (which now clears the failed latch) beats "exited immediately".
376+
`systemd stopped restarting the gateway after repeated crashes; run ${formatCliCommand(
377+
"openclaw gateway restart",
378+
)} or inspect logs.`
379+
: "Service is loaded but not running (likely exited immediately).",
380+
),
371381
);
372382
for (const hint of renderRuntimeHints(
373383
service.runtime,

‎src/commands/doctor-format.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,64 @@ describe("buildGatewayRuntimeHints", () => {
5858
expect(hints.join("\n")).not.toContain("systemd user services are unavailable");
5959
});
6060

61+
it("guides recovery when systemd hit its restart start limit (crash loop)", () => {
62+
// Real give-up shape: process kept failing (Result=exit-code) until NRestarts
63+
// reached StartLimitBurst and systemd stopped restarting.
64+
const text = buildGatewayRuntimeHints(
65+
{
66+
status: "stopped",
67+
state: "failed",
68+
systemd: { result: "exit-code", nRestarts: 5, startLimitBurst: 5 },
69+
},
70+
{ platform: "linux", env: {} },
71+
).join("\n");
72+
73+
expect(text).toContain("systemd stopped restarting the gateway after repeated crashes");
74+
expect(text).toContain("openclaw gateway restart");
75+
expect(text).not.toContain("likely exited immediately");
76+
});
77+
78+
it("keeps the generic stopped hint for a single failed exit below the start limit", () => {
79+
const text = buildGatewayRuntimeHints(
80+
{
81+
status: "stopped",
82+
state: "failed",
83+
systemd: { result: "exit-code", nRestarts: 1, startLimitBurst: 5 },
84+
},
85+
{ platform: "linux", env: {} },
86+
).join("\n");
87+
88+
expect(text).toContain("likely exited immediately");
89+
expect(text).not.toContain("systemd stopped restarting the gateway");
90+
});
91+
92+
it("keeps the generic stopped hint after a config exit (78) despite a stale restart count", () => {
93+
// RestartPreventExitStatus=78 stopped systemd on purpose; the leftover
94+
// NRestarts must not flip the hint to start-limit recovery guidance.
95+
const text = buildGatewayRuntimeHints(
96+
{
97+
status: "stopped",
98+
state: "failed",
99+
lastExitStatus: 78,
100+
systemd: { result: "exit-code", nRestarts: 5, startLimitBurst: 5 },
101+
},
102+
{ platform: "linux", env: {} },
103+
).join("\n");
104+
105+
expect(text).toContain("likely exited immediately");
106+
expect(text).not.toContain("systemd stopped restarting the gateway");
107+
});
108+
109+
it("keeps the generic stopped hint for an ordinary cleanly-stopped service", () => {
110+
const text = buildGatewayRuntimeHints(
111+
{ status: "stopped", state: "inactive" },
112+
{ platform: "linux", env: {} },
113+
).join("\n");
114+
115+
expect(text).toContain("likely exited immediately");
116+
expect(text).not.toContain("systemd stopped restarting the gateway");
117+
});
118+
61119
it("does not warn for normal systemd cgroup metrics", () => {
62120
expect(
63121
buildGatewayRuntimeHints(

‎src/commands/doctor-format.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { buildPlatformRuntimeLogHints } from "../daemon/runtime-hints.js";
1111
import {
1212
getSystemdCgroupHygieneSummary,
1313
isSystemdCgroupHygieneRisk,
14+
isSystemdStartLimitHit,
1415
type GatewayServiceRuntime,
1516
} from "../daemon/service-runtime.js";
1617
import {
@@ -104,7 +105,16 @@ export function buildGatewayRuntimeHints(
104105
return hints;
105106
}
106107
if (runtime.status === "stopped") {
107-
hints.push("Service is loaded but not running (likely exited immediately).");
108+
if (platform === "linux" && isSystemdStartLimitHit(runtime)) {
109+
// start-limit-hit means systemd gave up restarting after repeated crashes;
110+
// a plain "exited immediately" hint would hide that recovery needs a restart.
111+
hints.push(
112+
"systemd stopped restarting the gateway after repeated crashes.",
113+
`Recover with: ${formatCliCommand("openclaw gateway restart", env)}, then inspect logs if it keeps crashing.`,
114+
);
115+
} else {
116+
hints.push("Service is loaded but not running (likely exited immediately).");
117+
}
108118
if (fileLog) {
109119
hints.push(`File logs: ${fileLog}`);
110120
}

‎src/daemon/service-runtime.test.ts‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
// Tests for systemd supervision-state classification helpers.
2+
import { describe, expect, it } from "vitest";
3+
import { isSystemdStartLimitHit } from "./service-runtime.js";
4+
5+
describe("isSystemdStartLimitHit", () => {
6+
it("detects a crash loop where the restart counter reached StartLimitBurst", () => {
7+
// Real systemd 249 give-up: process kept exiting non-zero so Result stays
8+
// exit-code; NRestarts hitting StartLimitBurst is the give-up signal.
9+
expect(
10+
isSystemdStartLimitHit({
11+
status: "stopped",
12+
state: "failed",
13+
systemd: { result: "exit-code", nRestarts: 5, startLimitBurst: 5 },
14+
}),
15+
).toBe(true);
16+
});
17+
18+
it("detects a crash loop when the last exit was a non-config code", () => {
19+
// exit 1 is a normal crash, not the RestartPreventExitStatus=78 no-restart
20+
// path, so a counter that reached StartLimitBurst is real start-limit exhaustion.
21+
expect(
22+
isSystemdStartLimitHit({
23+
status: "stopped",
24+
state: "failed",
25+
lastExitStatus: 1,
26+
systemd: { result: "exit-code", nRestarts: 3, startLimitBurst: 3 },
27+
}),
28+
).toBe(true);
29+
});
30+
31+
it("detects Result=start-limit-hit even when restart counters are absent", () => {
32+
expect(
33+
isSystemdStartLimitHit({
34+
status: "stopped",
35+
state: "failed",
36+
systemd: { result: "start-limit-hit" },
37+
}),
38+
).toBe(true);
39+
});
40+
41+
it("does not counter-detect the deliberate EX_CONFIG (78) no-restart exit", () => {
42+
// RestartPreventExitStatus=78 stops systemd on purpose; the NRestarts left
43+
// over from earlier crashes is stale and must not read as start-limit exhaustion.
44+
expect(
45+
isSystemdStartLimitHit({
46+
status: "stopped",
47+
state: "failed",
48+
lastExitStatus: 78,
49+
systemd: { result: "exit-code", nRestarts: 5, startLimitBurst: 5 },
50+
}),
51+
).toBe(false);
52+
});
53+
54+
it("keeps Result=start-limit-hit authoritative even after a config (78) exit", () => {
55+
// The explicit systemd give-up signal wins regardless of the last exit code.
56+
expect(
57+
isSystemdStartLimitHit({
58+
status: "stopped",
59+
state: "failed",
60+
lastExitStatus: 78,
61+
systemd: { result: "start-limit-hit", nRestarts: 5, startLimitBurst: 5 },
62+
}),
63+
).toBe(true);
64+
});
65+
66+
it("does not flag a single failed exit below the start limit", () => {
67+
expect(
68+
isSystemdStartLimitHit({
69+
status: "stopped",
70+
state: "failed",
71+
systemd: { result: "exit-code", nRestarts: 1, startLimitBurst: 5 },
72+
}),
73+
).toBe(false);
74+
});
75+
76+
it("does not flag a running unit even if its lifetime restart count is high", () => {
77+
expect(
78+
isSystemdStartLimitHit({
79+
status: "running",
80+
state: "active",
81+
systemd: { result: "success", nRestarts: 9, startLimitBurst: 5 },
82+
}),
83+
).toBe(false);
84+
});
85+
86+
it("does not flag when rate limiting is disabled (StartLimitBurst=0)", () => {
87+
expect(
88+
isSystemdStartLimitHit({
89+
status: "stopped",
90+
state: "failed",
91+
systemd: { result: "exit-code", nRestarts: 9, startLimitBurst: 0 },
92+
}),
93+
).toBe(false);
94+
});
95+
96+
it("does not counter-detect when StartLimitBurst is missing from the probe", () => {
97+
expect(
98+
isSystemdStartLimitHit({
99+
status: "stopped",
100+
state: "failed",
101+
systemd: { result: "exit-code", nRestarts: 9 },
102+
}),
103+
).toBe(false);
104+
});
105+
106+
it("returns false without systemd supervision data or runtime", () => {
107+
expect(isSystemdStartLimitHit({ status: "stopped", state: "failed" })).toBe(false);
108+
expect(isSystemdStartLimitHit(undefined)).toBe(false);
109+
});
110+
});

‎src/daemon/service-runtime.ts‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
11
/** Shared daemon runtime status types and systemd cgroup hygiene helpers. */
22
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
33

4-
/** systemd cgroup fields used to spot unhealthy gateway service supervision. */
4+
/** systemd supervision fields used to spot unhealthy or given-up gateway service state. */
55
export type GatewayServiceSystemdRuntime = {
66
unit?: string;
77
killMode?: string;
88
tasksCurrent?: number;
99
memoryCurrent?: number;
10+
// systemd `Result` (e.g. success, exit-code, start-limit-hit) plus the restart
11+
// counter and configured StartLimitBurst. Together they detect a crash-loop
12+
// give-up that the collapsed `status` string and `Result` alone cannot.
13+
result?: string;
14+
nRestarts?: number;
15+
startLimitBurst?: number;
1016
};
1117

1218
export type GatewayServiceRuntime = {
@@ -29,6 +35,14 @@ export type GatewayServiceRuntime = {
2935
export const SYSTEMD_TASKS_CURRENT_WARNING_THRESHOLD = 200;
3036
export const SYSTEMD_MEMORY_CURRENT_WARNING_BYTES = 2 * 1024 * 1024 * 1024;
3137

38+
// EX_CONFIG (78) from sysexits.h. The generated systemd unit pins
39+
// RestartPreventExitStatus=78 (see systemd-unit.ts) so the gateway's
40+
// config-error / duplicate-lock exit (gateway-cli run) deliberately stops
41+
// without a restart. A last exit of 78 therefore means systemd gave up on
42+
// purpose, not that it exhausted StartLimitBurst, so any accumulated NRestarts
43+
// is stale from earlier crashes and must not drive start-limit detection.
44+
const SYSTEMD_NO_RESTART_EXIT_STATUS = 78;
45+
3246
export function isRiskySystemdKillMode(value: string | undefined): boolean {
3347
const normalized = normalizeLowercaseStringOrEmpty(value);
3448
return normalized === "process" || normalized === "none";
@@ -83,3 +97,45 @@ export function getSystemdCgroupHygieneSummary(
8397
export function isSystemdCgroupHygieneRisk(runtime?: GatewayServiceSystemdRuntime): boolean {
8498
return getSystemdCgroupHygieneSummary(runtime) !== null;
8599
}
100+
101+
/**
102+
* True when systemd has stopped auto-restarting the gateway because it crashed
103+
* faster than StartLimitBurst/StartLimitIntervalSec allows. Unlike an ordinary
104+
* stopped/exited unit, this terminal latch needs an explicit `reset-failed` +
105+
* restart to recover, so status/doctor must surface it instead of the generic
106+
* "exited immediately" message.
107+
*
108+
* Detection: the unit is `failed` and either systemd reported the give-up
109+
* directly (Result=start-limit-hit, the start-was-refused-before-exec case) or
110+
* the restart counter reached the configured burst. The counter path is the
111+
* common one: once the gateway process has actually run and exited non-zero,
112+
* systemd keeps Result=exit-code and never overwrites it with start-limit-hit
113+
* (verified against systemd 249), so Result alone misses real crash loops.
114+
*
115+
* The counter path is guarded against the deliberate no-restart exit: a last
116+
* exit of 78 (EX_CONFIG, held back by RestartPreventExitStatus=78) means
117+
* systemd stopped on purpose, so a stale NRestarts left over from earlier
118+
* crashes must not be mistaken for start-limit exhaustion. The explicit
119+
* Result=start-limit-hit signal stays authoritative regardless of exit status.
120+
*/
121+
export function isSystemdStartLimitHit(runtime?: GatewayServiceRuntime): boolean {
122+
if (!runtime || normalizeLowercaseStringOrEmpty(runtime.state) !== "failed") {
123+
return false;
124+
}
125+
const systemd = runtime.systemd;
126+
if (!systemd) {
127+
return false;
128+
}
129+
if (normalizeLowercaseStringOrEmpty(systemd.result) === "start-limit-hit") {
130+
return true;
131+
}
132+
if (runtime.lastExitStatus === SYSTEMD_NO_RESTART_EXIT_STATUS) {
133+
return false;
134+
}
135+
return (
136+
typeof systemd.startLimitBurst === "number" &&
137+
systemd.startLimitBurst > 0 &&
138+
typeof systemd.nRestarts === "number" &&
139+
systemd.nRestarts >= systemd.startLimitBurst
140+
);
141+
}

0 commit comments

Comments
 (0)