Skip to content

feat(node): prevent same-host duplicate node start with agent-node.lock (Layer 1) - #3879

Merged
vansin merged 3 commits into
mainfrom
feat/agent-node-instance-lock
Nov 25, 2026
Merged

vansin merged 3 commits into
mainfrom
feat/agent-node-instance-lock

Conversation

@vansin

@vansin vansin commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements Layer 1 of duplicate-node start protection (approved by ANet负责人, Layer 2 cross-host / --takeover intentionally deferred):

  • Added agent-node/src/node-instance-lock.ts:
    • Atomically acquires <nodeDir>/agent-node.lock (O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW, 0o600), writes { version, pid, alias, node_id, hostname, started_at, token }, and holds the fd open for the lifetime of the process (zero extra child processes; works on Linux, macOS, and Windows).
    • If the lock already exists and the recorded PID is alive, refuses startup immediately with a plain-Chinese message:
      这个 AI 已经在这台机器上运行(PID <pid>),不用再启动;要重启请先 anet node stop <alias>
    • If the recorded PID is dead (crash / kill -9), verifies inode match, cleans up the stale lock, and atomically reclaims it.
    • Fails closed on symlinks; release() verifies exact token + pid match before unlinking so it never removes another owner's lock.
  • Wired into agent-node/src/cli.ts right after NODE_DIR is resolved (before Hub registration / SSE / runtime startup), with automatic cleanup in process.on("exit") and shutdown().
  • Added 7 unit tests in agent-node/src/node-instance-lock.test.ts.

Verification

  • bun test agent-node/src/node-instance-lock.test.ts (7/7 pass)

cc 通信欧 for review.

…ock (Layer 1)

- Add agent-node/src/node-instance-lock.ts: atomic O_CREAT|O_EXCL|O_NOFOLLOW per-node lock (<nodeDir>/agent-node.lock) storing {pid, alias, node_id, hostname, started_at, token} while holding the fd open for the lifetime of the process
- On EEXIST, inspect existing lock (refusing symlinks) and check holder PID liveness:
  - Alive -> exit cleanly with plain-Chinese message naming the running PID and pointing to `anet node stop`
  - Dead (stale lock after crash/SIGKILL) -> verify inode unchanged, unlink, and atomically reclaim
- Release lock safely on shutdown() and process exit (verifying token+pid match so another owner's lock is never unlinked)
- Add unit tests in agent-node/src/node-instance-lock.test.ts covering acquire/release, duplicate rejection, stale reclaim, symlink fail-closed, token-guarded release, and cli.ts wiring

Diff-Shape: +553/-1
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T03:54:40.423544Z f1d266e PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

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

Copy link
Copy Markdown

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: f1d266e413

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +325 to +326
if (check.dev === existing.dev && check.ino === existing.ino) {
unlinkSync(lockPath);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Serialize stale-lock reclamation across competing starters

On Linux/macOS, two processes starting concurrently after a crash can both successfully acquire this lock. Both can read and lstatSync the same stale inode; if one is descheduled before unlinkSync, the other can unlink the stale file and create its new live lock. The first then resumes, unlinks that new lock using its previously captured stat result, and successfully creates another lock. Keeping the descriptor open does not prevent unlinking on these platforms, so both nodes proceed into SSE/inbox processing—the duplicate startup this change is intended to prevent. Serialize reclamation with a separate atomic guard or use an OS-backed locking primitive; the inode check and unlink are not atomic.

Useful? React with 👍 / 👎.

Comment thread agent-node/src/cli.ts
Comment on lines +1173 to +1175
const lockRes = acquireNodeInstanceLock(NODE_DIR, {
alias: ALIAS,
nodeId: fileConfig.node_id ?? null,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Scope the lock to individual nodes in legacy config layouts

For nodes using the still-supported .anet/profiles/<alias>.json fallback (cli.ts:643–654), NODE_DIR is the shared .anet/profiles directory, so starting one node now prevents every other legacy-profile node in that project from starting, even when their aliases and identities differ. The same collision occurs with distinct --config files stored in one directory. The existing NODE_STATE_DIR resolution explicitly handles configs outside the canonical per-node layout; use an equivalent per-node lock location rather than assuming each config's parent directory belongs to a single node.

Useful? React with 👍 / 👎.

Comment thread agent-node/src/node-instance-lock.ts Outdated
Comment on lines +303 to +306
if (holderPid !== null && isPidAlive(holderPid)) {
return {
ok: false,
reason: "already_running",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Verify process identity before treating a stale PID as its owner

After an unclean exit, if the recorded PID is reused by another process—or by the replacement node after a reboot/container restart—process.kill(pid, 0) succeeds and this branch rejects startup even though the original lock owner is gone. In the self-PID case, every startup with that recycled PID rejects itself. This defeats automatic crash recovery and requires manually removing the lock or waiting for the unrelated process to exit. Persist and verify a process-incarnation identifier, such as boot identity plus process start time, rather than treating PID existence alone as proof that the original owner is still running.

Useful? React with 👍 / 👎.

通信欧 added 2 commits November 25, 2026 11:54
…n agent-node.lock

Addressing review feedback on #3879:
- Add explicit pre-open lstatSync() check before openSync so symlinks / non-regular files are refused on Windows where constants.O_NOFOLLOW === 0
- Record Linux boot_id and check /proc/<pid>/cmdline on Linux so rebooted hosts or unrelated reused PIDs are reclaimed cleanly instead of falsely refusing startup (conservative fallback to isPidAlive on macOS/Windows/unreadable /proc)
- Add 2 unit tests covering reboot boot_id mismatch and Linux PID reuse

Diff-Shape: +111/-2
…ink guard

- Pass lockPath into formatDuplicateNodeMessage so refusal prints the real
  absolute lock file path (;如果确认它没在运行,删除 <lockPath> 后再启动).
- Allow overriding O_NOFOLLOW flag (noFollowFlag: 0) and add a unit test
  proving symlinked and dangling-symlink agent-node.lock files still fail
  closed via lstatSync when constants.O_NOFOLLOW is unavailable (Windows).
- Update formatDuplicateNodeMessage (with/without alias & PID) and duplicate
  start assertions, and refresh scripts/test-inventory-baseline.json.

Diff-Shape: +69/-22
@vansin
vansin merged commit 982334e into main Nov 25, 2026
90 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant