Repository navigation
fix(shutdown): handle SIGTERM at tracker boundary - #2133
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #2133 +/- ##
===========================================
+ Coverage 84.04% 84.26% +0.21%
===========================================
Files 351 351
Lines 27988 28008 +20
Branches 27988 28008 +20
===========================================
+ Hits 23523 23601 +78
+ Misses 4070 4006 -64
- Partials 395 401 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
🟡 Changes recommended
src/main.rs currently ignores the Result from tokio::signal::ctrl_c() inside tokio::select!, which can cause an error to be treated as a SIGINT and trigger an unintended shutdown.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds Unix SIGTERM handling at the tracker executable boundary so the existing coordinated shutdown sequence runs for both SIGINT and SIGTERM, with distinct observable logs, and updates the related issue spec/evidence docs accordingly.
Changes:
File summaries
| File | Description |
|---|---|
| src/main.rs | Adds SIGTERM handling (Unix) and shutdown-source logging before running the existing JobManager cancellation/wait sequence. |
| docs/issues/open/2132-add-sigterm-to-main/verification.md | Records post-implementation manual verification evidence and checklist updates. |
| docs/issues/open/2132-add-sigterm-to-main/ISSUE.md | Promotes draft to open issue #2132 and updates acceptance criteria/status narrative. |
| docs/issues/open/1488-overhaul-tracker-shutdown/ISSUE.md | Updates the EPIC table link to reference the new SI-1 issue spec path. |
Review details
Suppressed comments (3)
docs/issues/open/2132-add-sigterm-to-main/ISSUE.md:10
- Frontmatter
last-updated-utcis date-only, but the repo template requires UTC timestamp precision (YYYY-MM-DD HH:MM). Update this field to include the time in UTC to match the documented convention.
docs/issues/open/2132-add-sigterm-to-main/verification.md:161 - The verification environment captures a personal machine hostname (
josecelano-desktop) in the OS line. To avoid leaking identifiable workstation details in repo docs, redact the hostname while keeping kernel/version info.
docs/issues/open/2132-add-sigterm-to-main/verification.md:156 - Verification notes say the SIGTERM fix was "uncommitted" and the commit hash line includes a "working tree contains" qualifier, which reduces reproducibility for anyone trying to re-run the evidence later. Prefer re-running verification on a clean working tree and recording the exact commit SHA that contains the change.
- Files reviewed: 4/4 changed files
- Comments generated: 1
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
There was a problem hiding this comment.
🟡 Changes recommended
src/main.rs currently treats sigterm.recv() returning None as a SIGTERM, which can misreport the shutdown source and trigger shutdown unexpectedly if the signal stream closes.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (2)
src/main.rs:59
- Same as the outer
select!:sigterm.recv()yieldsOption<()>. If it ever returnsNone, the current arm would still select and report SIGTERM. HandleNoneexplicitly to avoid misreporting the shutdown source.
_ = sigterm.recv() => "SIGTERM",
docs/issues/open/2132-add-sigterm-to-main/ISSUE.md:10
last-updated-utcshould include a UTC time (YYYY-MM-DD HH:MM) per the issue spec template; this entry is date-only, which makes updates harder to track consistently.
- Files reviewed: 12/13 changed files
- Comments generated: 1
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
The new tests/lifecycle/native_tracker.rs introduces const fn methods that mutate or use non-const operations and are likely to break compilation under the project MSRV.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (4)
Previously missed (1) — in code that hasn't changed since the last review.
docs/issues/open/AGENTS.md:114
- The summary table mixes the legacy standalone EPIC example (
1978-configuration-overhaul-epic.mdabove) with a folder-style EPIC example here, but the table labelEPIC specdoesn’t clarify which format it refers to. This can mislead readers into thinking EPIC specs are always folder-based even when documenting legacy single-file EPICs.
tests/lifecycle/native_tracker.rs:349
child_refis declared asconst fnbut calls runtime-only methods (as_ref()+expect(...)). This is very likely to be rejected by const-eval rules and can break compilation; use a normalfn.
const fn child_ref(&self) -> &Child {
tests/lifecycle/native_tracker.rs:353
child_mutis declared asconst fnbut usesOption::as_mut()+expect(...), which is unlikely to be const-evaluable and can break compilation. Use a normalfn.
const fn child_mut(&mut self) -> &mut Child {
tests/lifecycle/native_tracker.rs:357
output_refis declared asconst fnbut usesOption::as_ref()+expect(...), which is unlikely to be const-evaluable and can break compilation. Use a normalfn.
const fn output_ref(&self) -> &TrackerOutputCapture {
- Files reviewed: 29/30 changed files
- Comments generated: 1
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
There are a couple of concrete documentation/maintainability issues in changed files (notably a contradictory naming “Summary Table” and an unnecessary const fn) that should be corrected before merging.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (1)
tests/lifecycle/native_tracker.rs:257
take_drop_cleanup_observeris declared as aconst fn, but it performs normal runtime state mutation (Option::take()) and returns a non-const type. Marking itconstdoesn't provide a benefit here and can unnecessarily constrain future changes to this helper.
/// Returns an observer for the signal that terminated the reaped drop-path child.
pub const fn take_drop_cleanup_observer(&mut self) -> oneshot::Receiver<Result<i32, String>> {
self.drop_cleanup_observer
.take()
.expect("drop cleanup observer must be taken at most once")
}
- Files reviewed: 29/30 changed files
- Comments generated: 1
- Review effort level: Lite
4543c53 to
b0810e3
Compare
|
ACK b0810e3 |
da2ce7
left a comment
There was a problem hiding this comment.
This is a post-merge review of #2133 as it stands at e170b9620 on the default branch.
What still runs: the signal wait this change added to src/main.rs now lives in src/app.rs as wait_for_shutdown_signal (moved by 989edcc with its log target pinned, otherwise unchanged) and is called by run_until_shutdown_signal, which main enters once app::start_with_explicit_config_toml_path has returned. SIGINT and SIGTERM still select the logged shutdown source and run begin_shutdown and wait_for_all once. The executable-boundary tests in tests/lifecycle/signals.rs are live and extended, and the native fixture now lives under tests/common/native_tracker/. Two gaps in the change as merged were closed later and are history: the fixture's shutdown accepted any exit status, so the SIGINT test did not check a graceful exit, until ccc7a2b; and the success line and the exit code ignored the shutdown outcome until 191158c.
[Minor] The handlers are installed only after the whole startup has finished, so SIGTERM is still unhandled while the trackers are already serving. src/main.rs:30 calls run_until_shutdown_signal only after startup returns, and src/app.rs:198-205 registers SIGTERM and then SIGINT at that point; by then start_jobs_with_manager has bound and spawned the UDP and HTTP trackers (src/app.rs:326-327) and goes on to await the REST API and the health check API (src/app.rs:332-333). A SIGTERM from a supervisor in that span, for example a docker stop or a rolling restart that lands just after the start, takes the default action: the process is killed by signal 15 (reported as 143) instead of exiting with 0 or 1, no shutdown line is logged, in-flight HTTP requests are cut, and with persistent completed statistics enabled the events already published to their listener are lost. The same ordering means a failed registration panics (src/app.rs:201, src/app.rs:206) with every listener bound, skipping begin_shutdown. Smallest fix: on Unix, create both streams with tokio::signal::unix::signal(SignalKind::interrupt()) and signal(SignalKind::terminate()) in main before startup, report the io::Error as a startup failure, and pass the streams to run_until_shutdown_signal. Because signal() registers when it is called, the biased select! with its std::future::ready branch and the pinned ctrl_c future (src/app.rs:186-228) are then unnecessary, and the readiness marker can be logged straight after both registrations. A signal that arrives during startup is then held and acted on as soon as startup returns.
[Nit] A second SIGINT or SIGTERM during the drain is discarded without a trace. wait_for_shutdown_signal drops both listeners when it returns (src/app.rs:197-228), but the Tokio signal driver keeps its process-wide handlers for both signals installed for the rest of the process, so nothing restores the default action and nothing listens. With application.shutdown.deadline_in_secs at its maximum of 3600 and a component that does not stop, a second Ctrl-C in a terminal has no visible effect for up to an hour; only SIGQUIT, SIGKILL or the deadline end the process. Smallest fix: keep the streams in run_until_shutdown_signal and race jobs.wait_for_all(...) (src/app.rs:162) against a further signal, logging that shutdown is already in progress and how to force it; whether a second signal should also force an immediate incomplete exit is a separate choice.
[Nit] The fixture's drop path does not reap on the panic path it was written for. The comment at tests/common/native_tracker/mod.rs:403-404 says a panicking test's child is killed and reaped in the active runtime, but #[tokio::test] runs a current-thread runtime that is shut down as soon as the panic leaves block_on, so the cleanup task spawned at tests/common/native_tracker/mod.rs:405 is dropped before it is first polled: the child is killed only by kill_on_drop (tests/common/native_tracker/command.rs:275), the fixture does not wait for it, the drop observer never receives a result, and the temporary workspace can be removed before the child has exited. The test at tests/lifecycle/signals.rs:155 drops the fixture without panicking, so its runtime keeps running and the task completes; the panic path itself is not covered. Smallest fix: call child.start_kill() synchronously in drop before spawning the reaper, and say in the comment that reaping is best-effort while the runtime shuts down, as tests/common/native_tracker/command.rs:273-274 already says for the no-runtime case.
[Nit] The tokio features this change added for the fixture went into the shipped crate's normal dependencies. Cargo.toml:113 enables io-util and process for torrust-tracker, but nothing under src/ uses tokio::io or tokio::process; only tests/common/native_tracker/ does. Every build of the library and the release binary therefore compiles both modules, and so would any dependant of the library crate once it is published. Smallest fix: move io-util and process to the existing tokio entry under [dev-dependencies] at Cargo.toml:132.
Checked and found sound: the biased first poll registers SIGINT after SIGTERM and before the readiness marker is logged, so the fixture's wait on that marker does not race registration; the recv() future dropped between the two select!s loses no signal, because the stream keeps a delivered signal pending; a closed SIGTERM stream or a failed Ctrl-C registration fails loudly instead of being reported as a signal; the tests signal an unreaped child by its own PID, so the PID cannot have been reused; the SIGTERM test's expected job log still matches src/bootstrap/jobs/manager.rs:729; each child gets only a CLI-selected, port-zero configuration on 127.0.0.1 with the inherited configuration variables removed; and the nix dev-dependency is limited to its signal feature.
Summary
Add Unix
SIGTERMhandling at the tracker executable boundary. SIGINT and SIGTERM select the shutdown source, emit distinct observable logs, and execute the existing JobManager cancellation and waiting sequence once.Details
wait_for_shutdown_signal()so platform-specific signal registration and source selection are isolated from the executable lifecycle.ReadinessProbe.docs/issues/open/2132-add-sigterm-to-main/.Closes #2132
Validation
cargo build --releasecargo test --test lifecycle-signalscargo testlinter allKnown transitional behavior
Legacy periodic jobs retain their existing sequential per-job timeout behavior. The documented aggregate shutdown-result and deadline policy remain owned by SI-20. The native fixture's output assertions intentionally require message presence only; stdout and stderr are drained concurrently into one retained buffer and their cross-stream ordering is not asserted.