Skip to content

fix: make daemon stop() async with SIGTERM→wait→SIGKILL escalation (closes #22676) - #46357

Closed
Br1an67 wants to merge 1 commit into
openclaw:mainfrom
Br1an67:fix/22676
Closed

Br1an67 wants to merge 1 commit into
openclaw:mainfrom
Br1an67:fix/22676

Conversation

@Br1an67

@Br1an67 Br1an67 commented Mar 14, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Problem: Signal/iMessage/Gmail daemon stop() sends SIGTERM but doesn't wait, causing orphaned processes on restart
  • Why it matters: Orphaned processes block ports/locks, causing send failures after restart
  • What changed: stop()/shutdown() now async: SIGTERM → 5s wait → SIGKILL if needed
  • What did NOT change: Start logic, normal operation, process spawning

Change Type

  • Bug fix

Scope

  • Signal extension
  • iMessage extension
  • Gmail hooks

Linked Issue/PR

Security Impact

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Evidence

  • pnpm build + pnpm check + pnpm test all passing

Human Verification

  • Verified: build/check/test passing
  • NOT verified: runtime with actual SIGUSR1 restart

Compatibility / Migration

  • Backward compatible? Yes — callers that don't await still work (fire-and-forget)

Failure Recovery

  • How to revert: revert this commit

This PR was AI-assisted (fully tested with pnpm build/check/test).

@openclaw-barnacle openclaw-barnacle Bot added channel: imessage Channel integration: imessage channel: signal Channel integration: signal size: S labels Mar 14, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2d6f324f1e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread extensions/signal/src/daemon.ts Outdated
Comment on lines +142 to +143
if (child.killed || exited) {
return;

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.

P1 Badge Return in-flight stop promise when already signaled

After stop() became async, this early return means a second caller does not wait for shutdown if another caller already sent SIGTERM. In monitor.ts, abort triggers a fire-and-forget daemonLifecycle.stop(), then finally does await daemonLifecycle.stop(); with this guard, that awaited call can return immediately while the first stop is still waiting, so the monitor can exit before the daemon is actually gone (the exact orphan/restart race this change is trying to prevent). Make stop() idempotent by reusing/returning an in-flight stop promise instead of returning early on child.killed.

Useful? React with 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Mar 14, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR converts stop() / shutdown() across the Signal daemon, iMessage RPC client, and Gmail hook service from fire-and-forget SIGTERM to an async SIGTERM → 5 s wait → SIGKILL escalation, fixing orphaned-process issues on restart (#22676). The approach is sound and the iMessage implementation is cleanly done. Two issues are worth addressing before merging:

  • monitor.ts double-stop race (logic): opts.abortSignal's abort handler calls void daemonLifecycle.stop() (fire-and-forget), which sends SIGTERM and sets child.killed = true. The finally block's await daemonLifecycle.stop() then returns immediately because the child.killed guard short-circuits it. Consequently, monitorSignalProvider can return while the child is still alive for up to 5 s — exactly the race this PR intends to fix. The remedy is to relax the guard so that an already-signalled-but-not-yet-exited process is still awaited on the second call.
  • gmail-ops.ts mutable closure (style): shutdown() references the let child variable inside a 5 s async callback rather than capturing a local const snapshot at invocation time, which differs from the defensive pattern used in client.ts. Correct in practice due to the shuttingDown guard, but fragile.

Confidence Score: 3/5

  • The abort-signal path in monitor.ts can still return while the child process is alive, leaving the original port/lock race unsolved for that code path.
  • The core logic in daemon.ts and client.ts is correct for the normal stop path, and the iMessage implementation is particularly clean. However, monitor.ts has a meaningful logic gap: when opts.abortSignal triggers shutdown, the finally block's await stop() returns immediately because the abort handler's concurrent stop already set child.killed = true, so monitorSignalProvider can exit before the subprocess is dead — directly undermining the fix's goal. This affects real restart scenarios that go through the abort path.
  • extensions/signal/src/monitor.ts — the double-stop interaction between the abort handler and the finally block needs to be resolved to ensure the child process has truly exited before monitorSignalProvider returns.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/signal/src/monitor.ts
Line: 407-409

Comment:
**`await` in `finally` bypassed when abort fires first**

When `opts.abortSignal` is aborted, `onAbort` calls `void daemonLifecycle.stop()` (fire-and-forget), which immediately invokes `child.kill("SIGTERM")` and sets `child.killed = true`. When the `finally` block later runs `await daemonLifecycle.stop()`, the inner guard `if (child.killed || exited) { return; }` causes it to return instantly — without waiting for the process to actually exit. As a result, `monitorSignalProvider` can return while the child is still alive for up to 5 s (until the background SIGKILL fires), defeating the fix for port/lock contention on restart.

One way to resolve this is to change the early-exit guard in `spawnSignalDaemon`'s `stop()` so that an already-signalled-but-not-yet-exited process is still awaited:

```ts
// daemon.ts
stop: async () => {
  if (!exited && !child.killed) {
    child.kill("SIGTERM");
  }
  if (exited) return;           // already gone, nothing to await
  await new Promise<void>((resolve) => {
    const t = setTimeout(() => {
      try { child.kill("SIGKILL"); } catch {}
      resolve();
    }, 5000);
    child.once("exit", () => { clearTimeout(t); resolve(); });
    if (child.exitCode !== null) { clearTimeout(t); resolve(); }
  });
},
```

With this change, the second call from `finally` still awaits the exit even when SIGTERM was already sent by the abort handler, so `monitorSignalProvider` only returns once the subprocess has truly stopped.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/hooks/gmail-ops.ts
Line: 329-345

Comment:
**Mutable `child` captured by closure inside SIGKILL timeout**

`shutdown()` closes over the `let child` variable. Inside the 5 s `setTimeout` callback, `child.kill("SIGKILL")` resolves the variable at callback-fire time, not at the time `shutdown()` was invoked. While the `shuttingDown` guard prevents reassignment in the happy path, this differs from the pattern used in `client.ts` (which correctly snapshots `const child = this.child` before any async work).

A safer approach is to capture a local constant at the start of `shutdown()`:

```suggestion
  const currentChild = child;
  currentChild.kill("SIGTERM");
    await new Promise<void>((resolve) => {
      const t = setTimeout(() => {
        try {
          currentChild.kill("SIGKILL");
        } catch {}
        resolve();
      }, 5000);
      currentChild.once("exit", () => {
        clearTimeout(t);
        resolve();
      });
      if (currentChild.exitCode !== null) {
        clearTimeout(t);
        resolve();
      }
    });
```

This matches the explicit snapshot pattern in `client.ts` (`const child = this.child; this.child = null;`) and removes the implicit dependency on `shuttingDown` to keep the closure variable stable.

How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: 2d6f324

Comment on lines 407 to 409
const onAbort = () => {
daemonLifecycle.stop();
void daemonLifecycle.stop();
};

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.

await in finally bypassed when abort fires first

When opts.abortSignal is aborted, onAbort calls void daemonLifecycle.stop() (fire-and-forget), which immediately invokes child.kill("SIGTERM") and sets child.killed = true. When the finally block later runs await daemonLifecycle.stop(), the inner guard if (child.killed || exited) { return; } causes it to return instantly — without waiting for the process to actually exit. As a result, monitorSignalProvider can return while the child is still alive for up to 5 s (until the background SIGKILL fires), defeating the fix for port/lock contention on restart.

One way to resolve this is to change the early-exit guard in spawnSignalDaemon's stop() so that an already-signalled-but-not-yet-exited process is still awaited:

// daemon.ts
stop: async () => {
  if (!exited && !child.killed) {
    child.kill("SIGTERM");
  }
  if (exited) return;           // already gone, nothing to await
  await new Promise<void>((resolve) => {
    const t = setTimeout(() => {
      try { child.kill("SIGKILL"); } catch {}
      resolve();
    }, 5000);
    child.once("exit", () => { clearTimeout(t); resolve(); });
    if (child.exitCode !== null) { clearTimeout(t); resolve(); }
  });
},

With this change, the second call from finally still awaits the exit even when SIGTERM was already sent by the abort handler, so monitorSignalProvider only returns once the subprocess has truly stopped.

Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/signal/src/monitor.ts
Line: 407-409

Comment:
**`await` in `finally` bypassed when abort fires first**

When `opts.abortSignal` is aborted, `onAbort` calls `void daemonLifecycle.stop()` (fire-and-forget), which immediately invokes `child.kill("SIGTERM")` and sets `child.killed = true`. When the `finally` block later runs `await daemonLifecycle.stop()`, the inner guard `if (child.killed || exited) { return; }` causes it to return instantly — without waiting for the process to actually exit. As a result, `monitorSignalProvider` can return while the child is still alive for up to 5 s (until the background SIGKILL fires), defeating the fix for port/lock contention on restart.

One way to resolve this is to change the early-exit guard in `spawnSignalDaemon`'s `stop()` so that an already-signalled-but-not-yet-exited process is still awaited:

```ts
// daemon.ts
stop: async () => {
  if (!exited && !child.killed) {
    child.kill("SIGTERM");
  }
  if (exited) return;           // already gone, nothing to await
  await new Promise<void>((resolve) => {
    const t = setTimeout(() => {
      try { child.kill("SIGKILL"); } catch {}
      resolve();
    }, 5000);
    child.once("exit", () => { clearTimeout(t); resolve(); });
    if (child.exitCode !== null) { clearTimeout(t); resolve(); }
  });
},
```

With this change, the second call from `finally` still awaits the exit even when SIGTERM was already sent by the abort handler, so `monitorSignalProvider` only returns once the subprocess has truly stopped.

How can I resolve this? If you propose a fix, please make it concise.

Comment thread src/hooks/gmail-ops.ts
Comment on lines 329 to +345
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
const t = setTimeout(() => {
try {
child.kill("SIGKILL");
} catch {}
resolve();
}, 5000);
child.once("exit", () => {
clearTimeout(t);
resolve();
});
if (child.exitCode !== null) {
clearTimeout(t);
resolve();
}
});

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.

Mutable child captured by closure inside SIGKILL timeout

shutdown() closes over the let child variable. Inside the 5 s setTimeout callback, child.kill("SIGKILL") resolves the variable at callback-fire time, not at the time shutdown() was invoked. While the shuttingDown guard prevents reassignment in the happy path, this differs from the pattern used in client.ts (which correctly snapshots const child = this.child before any async work).

A safer approach is to capture a local constant at the start of shutdown():

Suggested change
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
const t = setTimeout(() => {
try {
child.kill("SIGKILL");
} catch {}
resolve();
}, 5000);
child.once("exit", () => {
clearTimeout(t);
resolve();
});
if (child.exitCode !== null) {
clearTimeout(t);
resolve();
}
});
const currentChild = child;
currentChild.kill("SIGTERM");
await new Promise<void>((resolve) => {
const t = setTimeout(() => {
try {
currentChild.kill("SIGKILL");
} catch {}
resolve();
}, 5000);
currentChild.once("exit", () => {
clearTimeout(t);
resolve();
});
if (currentChild.exitCode !== null) {
clearTimeout(t);
resolve();
}
});

This matches the explicit snapshot pattern in client.ts (const child = this.child; this.child = null;) and removes the implicit dependency on shuttingDown to keep the closure variable stable.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/hooks/gmail-ops.ts
Line: 329-345

Comment:
**Mutable `child` captured by closure inside SIGKILL timeout**

`shutdown()` closes over the `let child` variable. Inside the 5 s `setTimeout` callback, `child.kill("SIGKILL")` resolves the variable at callback-fire time, not at the time `shutdown()` was invoked. While the `shuttingDown` guard prevents reassignment in the happy path, this differs from the pattern used in `client.ts` (which correctly snapshots `const child = this.child` before any async work).

A safer approach is to capture a local constant at the start of `shutdown()`:

```suggestion
  const currentChild = child;
  currentChild.kill("SIGTERM");
    await new Promise<void>((resolve) => {
      const t = setTimeout(() => {
        try {
          currentChild.kill("SIGKILL");
        } catch {}
        resolve();
      }, 5000);
      currentChild.once("exit", () => {
        clearTimeout(t);
        resolve();
      });
      if (currentChild.exitCode !== null) {
        clearTimeout(t);
        resolve();
      }
    });
```

This matches the explicit snapshot pattern in `client.ts` (`const child = this.child; this.child = null;`) and removes the implicit dependency on `shuttingDown` to keep the closure variable stable.

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e06d0a9a02

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +132 to +133
const closedOrTimeout = await Promise.race([
this.closed.then(() => "closed" as const),

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.

P2 Badge Recreate close promise on each iMessage child start

stop() now decides whether to escalate based on this.closed, but this.closed is a single promise created in the constructor and never reset per spawned child. After one start() → stop() cycle, that promise stays resolved, so a later stop() on the same IMessageRpcClient instance will take the "closed" branch immediately and skip SIGTERM/SIGKILL, which can leave the new imsg process alive when stdin EOF is insufficient to terminate it. Because this class exposes reusable start()/stop() methods, this is a real restart-path orphan risk.

Useful? React with 👍 / 👎.

…loses openclaw#22676)

Signal daemon stop() was fire-and-forget: it sent SIGTERM but did not wait
for the process to exit. On SIGUSR1 restart the new signal-cli spawned
before the old one released its port/lock, causing orphaned processes and
send failures. The same pattern existed in the iMessage RPC client and
Gmail ops shutdown.

Apply the SIGTERM → wait (5 s) → SIGKILL escalation pattern already used
in src/infra/ssh-tunnel.ts to all three call sites:

- extensions/signal/src/daemon.ts  (SignalDaemonHandle.stop)
- extensions/imessage/src/client.ts (IMessageRpcClient.stop)
- src/hooks/gmail-ops.ts           (shutdown in runGmailService)

Co-authored-by: Copilot <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Mar 15, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3cc1c300b1

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +71 to +73
id === defaultSlotIdForKey("contextEngine") &&
normalizedOwner !== CORE_CONTEXT_ENGINE_OWNER
) {

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.

P1 Badge Permit built-in registration of the default context engine

This guard blocks registration of the default slot id (legacy) for any non-core owner, but built-in startup still registers legacy via registerContextEngine("legacy", ...) (the public path) and ignores the { ok: false } return, so default initialization no longer installs a factory for legacy. In the default configuration, resolveContextEngine() will then throw that legacy is not registered, which breaks normal agent/context-engine resolution paths.

Useful? React with 👍 / 👎.

@Br1an67

Br1an67 commented Mar 17, 2026

Copy link
Copy Markdown
Contributor Author

Closing to manage active PR count. Will reopen when slot is available.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: imessage Channel integration: imessage channel: signal Channel integration: signal docs Improvements or additions to documentation size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Signal daemon stop() race condition on SIGUSR1 restart — orphaned processes and send failures

1 participant