{"id":"XE-0041","kind":"bounty","visibility":"public","source":"github","source_repo":"xeprotocol/xe","source_ref":"60","source_url":"https://github.com/xeprotocol/xe/issues/60","reporter_id":17,"title":"node: SIGTERM during sync does not cancel in-flight sync; shutdown hangs, keeps the Badger lock, and the replacement process cannot start (Medium)","area":"p2p-sync","claimed_tier":"medium","assessed_tier":null,"verdict":null,"duplicate_of":null,"tracked":true,"internal_ref":"","internal_url":null,"status":"accepted","closed_reason":null,"github_state":"open","disclosed_at":null,"award_xe":null,"award_approved":false,"paid_ref":"","created_at":"2026-10-29T13:57:17.968848+00:00","updated_at":"2026-11-11T06:28:24.864113+00:00","source_created_at":"2026-10-26T07:33:51+00:00","told_at":"2026-11-10T00:15:31+00:00","status_changed_at":"2026-10-29T14:04:12.532832+00:00","url":"https://bounty.xe.network/XE-0041","body":"## Summary\n\n`requestSync` derives its context from `context.Background()` instead of the node's shutdown context, and the block-apply loop has no cancellation check. `Node.Stop` then waits on `spawnGate.wait()` for every in-flight sync to finish, while the API listener has already been shut down by the earlier deferred `apiSrv.Shutdown`. On a node that is syncing, SIGTERM therefore turns into a multi-minute outage with every listener closed, the process still alive, and the Badger directory lock held. A restart started in that window exits with `Cannot acquire directory lock`, so the operator's restart fails until the old process drains.\n\n## Affected component\n\n- `net/sync.go:531` builds the sync context from `context.Background()` with a 60 second timeout.\n- `net/sync.go:602-604` retries up to `maxRetries = 10` over the pending set; each round can carry `maxTotalBlocks = 10000` blocks.\n- `net/sync.go:410-415` `spawnGate.wait` closes the gate and then blocks on `wg.Wait()` with no deadline.\n- `node/node.go:1301-1308` `Stop` closes the p2p host at line 1306 and then calls `syncWait` at line 1307 before closing the store at line 1308.\n- `cmd/xe/main.go:1419` registers `defer n.Stop()` before the API server defer at line 1464, so on SIGTERM the API is shut down before `Stop` waits.\n\nCommit: `978785929bc17a2f4ab30c383e5fc9cf4d634512`, network `testnet-0005`.\n\n## Impact\n\nAny restart or deploy of a node that is actively syncing leaves the node unreachable for the whole drain while it still holds the data directory:\n\n- the HTTP API is closed first, so the node answers nothing (measured: HTTP 000 and zero listeners 5 seconds after SIGTERM);\n- the p2p host is closed at `node/node.go:1306` before the wait, so peers see the node disappear;\n- the process survives with every listener closed and still holds the Badger directory lock (measured: still alive after more than two minutes, with the main goroutine annotated as blocked in `sync.WaitGroup.Wait` for 2 minutes), so a supervisor that waits on the process, or has no stop timeout, sees a live process and does not restart it, while one that sends SIGKILL at its stop timeout restarts the node only after the timeout, skipping the graceful drain; a manual replacement in the window fails to start with `store: Cannot acquire directory lock ... Another process is using this Badger database`;\n- the drain is bounded only by the in-flight work: each sync round can carry up to 10,000 blocks, retried up to 10 times per block, and a new round can start every 10 seconds while the node is behind, so a node that is catching up almost always has work in flight.\n\nOn a node whose sync cannot converge (for example the lease-family blocks reported in #57), each round also re-processes blocks that will never apply, so the drain can last minutes; the measured clean run stayed in the wait for over two minutes at only 573 accounts. This is an operator-facing availability defect in restart and recovery; it is triggered by a normal SIGTERM, not by a crafted input. The testnet-0005 genesis names a representative account for the genesis supply, and finality needs 67 percent of delegated weight, so if that representative is the only delegated voter, a restart that spends minutes in this wait keeps finality idle for that period.\n\nScope and affected parties: the programme lists nodes (config, storage, restarts) and networking (peer discovery and sync) as in scope. The people affected are node operators who restart or deploy a node that is syncing, and, on a network with a single representative, anyone relying on finality during that restart window.\n\n## PoC\n\nFrom the repository root, with a fresh data directory, the published testnet-0005 genesis, and the documented bootstrap peers:\n\n```\nrm -rf /tmp/xes/data\n./xe node --genesis-dir ./genesis/testnet-0005 --data /tmp/xes/data \\\n  --api-port 28081 --api-bind 127.0.0.1 --metrics-addr 127.0.0.1:29095 \\\n  --port 29001 --disable-mdns --no-discovery \\\n  --dial /ip4/45.77.226.208/tcp/9000/p2p/12D3KooWJg4PQYGSfNCupBWZdEWbKj7pgdp5MmmUXbPdBcp6YDtT,/ip4/144.202.4.117/tcp/9000/p2p/12D3KooWEqv1BRZkSntgcgbrJh7bobFRSkBdRupubvNZLEx8hZLA &\n```\n\nWait until the node is syncing and has a few hundred accounts, then resolve the node's PID from its API listener:\n\n```\ncurl -s http://127.0.0.1:28081/node | jq '{accounts,peer_count}'\n# {\"accounts\":573,\"peer_count\":6}\nNODE_PID=$(ss -ltnp | sed -n 's/.*:28081.*pid=\\([0-9]*\\).*/\\1/p' | head -1)\n```\n\nThe PID matters: if the node is started under a wrapper such as `setsid`, `$!` can be the wrapper and the signal never reaches the node.\n\nSend SIGTERM to the node and try to restart on the same data directory while the old process is still up:\n\n```\nkill -TERM \"$NODE_PID\"\nsleep 5\ncurl -s -o /dev/null -w '%{http_code}\\n' http://127.0.0.1:28081/node   # 000\nss -ltn | grep -cE ':(28081|29001|29095)\\b'                            # 0\n./xe node --genesis-dir ./genesis/testnet-0005 --data /tmp/xes/data \\\n  --api-port 28082 --api-bind 127.0.0.1 --metrics-addr 127.0.0.1:29097 \\\n  --port 29002 --no-discovery --disable-mdns\n# failed to start node: store: Cannot acquire directory lock on \"/tmp/xes/data/ledger\".\n#   Another process is using this Badger database. err: resource temporarily unavailable\n```\n\nThe old process is still alive with every listener closed. A SIGQUIT dump taken more than two minutes after SIGTERM shows the main goroutine still inside `Node.Stop` on the sync gate, and the runtime annotates the wait:\n\n```\ngoroutine 1 gp=0x19c9d064e1e0 [sync.WaitGroup.Wait, 2 minutes]:\nsync.(*WaitGroup).Wait(...)\ngithub.com/xeprotocol/xe/net.(*spawnGate).wait(...)  net/sync.go:414\ngithub.com/xeprotocol/xe/node.(*Node).Stop(...)      node/node.go:1307\nmain.cmdNode.deferwrap1()                            cmd/xe/main.go:1419\n```\n\nIn this clean run (573 accounts and peer_count 6 as reported by `/node`) the process was still alive after more than two minutes, the API answered nothing by the 5 second mark, all three listeners were gone, and the replacement failed on the lock. It had not exited on its own and was ended with SIGQUIT; the dump contained 37 goroutines, 3 of them inside `requestSync`. A longer run that had synced for about seven minutes produced a 430 goroutine dump with 188 goroutines inside `requestSync`, 163 waiting in `Ledger.acquireAccountLock` (`core/ledger.go:430`) from `Ledger.addBlock` (`core/ledger.go:785`), 209 goroutines inside Badger's `Iterator.fill`, and goroutine IDs near 91.2 million. An idle node with no peers, by contrast, exits in well under a second after SIGTERM, so the wait is specific to in-flight sync work.\n\n## Suggested severity\n\nMedium. Restart and recovery are explicitly in scope, and the measured wait is minutes on a node that is syncing, but the trigger is a local SIGTERM rather than a client action, and an orchestrator or supervisor that sends SIGKILL at its stop timeout recovers the node. The defect is not a targeted DoS under the published High tier; it is a restart and recovery failure that stays hidden until an operator restarts a syncing node.\n\n## Suggested fix\n\n- Give `requestSync` the node's context (or a context derived from it) and check `ctx.Err()` in the apply and retry loops.\n- Make `spawnGate.wait` bounded: cancel the gate's context and wait with a deadline, or track sync work in the node's `WaitGroup` that `Stop` can cancel.\n- Close the store only after the drain or after a hard deadline, and fail the process with a clear message instead of waiting indefinitely while holding the directory lock.\n- Consider not shutting down the API until `Node.Stop` is ready to complete, so an operator can still observe the node during the drain.\n\nXE payout address: will be provided in a follow-up comment.\n","patch_refs":[{"id":148,"repo":"xeprotocol/xe","kind":"pr","ref":"126","title":"fix(net): cancel in-flight sync on shutdown and bound spawnGate wait (#60)","url":"https://github.com/xeprotocol/xe/pull/126","note":"","state":"open","author":"arturbarszcz78","added_by":"desk","created_at":"2026-10-29T13:57:30.091343+00:00"}],"thread":[{"id":16,"source":"github","source_ref":"6410749366","author":"senastor","team":false,"body":"XE payout address: 3af6fd8452352903a845a4b99a0f852a9f944bbab4afd6cfaab93cfb11510a9a","created_at":"2026-10-26T07:37:58+00:00"},{"id":1561,"source":"github","source_ref":"6755089374","author":"XE desk","team":true,"body":"Read and accepted. It is tracked internally and the fix will land in a public PR; this issue is\nupdated when it does, and the tier and award follow the fix. The desk entry is https://bounty.xe.network/XE-0041.","created_at":"2026-11-10T00:15:31+00:00"}]}