Repository navigation
refactor(bootstrap): [#2415] give each application component its own cancellation token - #2591
Conversation
…into the log The 2026-10-20 19:30 UTC entry recording that torrust#2414 merged was appended at the end of the sub-EPIC spec, after `## References`, instead of inside `### Progress Log`. Move it into the log in time order without changing its text, and add an entry recording the move. Co-authored-by: Copilot <[email protected]>
…issue each component its own token `JobManager::reserve(name)` issues a `Reservation` carrying a component id and the component's own cancellation token, which is not derived from the legacy root token or from any other component's token. `JobManager::spawn(reservation, future)` consumes the reservation, so it cannot be spawned twice, and returns `SpawnError::ForeignReservation` for a reservation issued by another manager. Dropping an unspawned reservation releases it. `cancel()` cancels the legacy root token and every reserved or spawned component token, and a reservation issued afterwards carries a cancelled token, so no stop request is lost and behavior is unchanged. Agreed at the T6a design review: the previous `spawn(name, future)` stays as the temporary adapter `spawn_unreserved` so this change compiles on its own; the next commit converts every caller and removes it. Co-authored-by: Copilot <[email protected]>
…dence The maintainer agreed to the reservation API and decided the details the Chosen Design left to T6: `spawn` returns `SpawnError`, which bootstrap propagates as a startup error; the root-token accessor becomes `legacy_cancellation_token()`; and the work lands as two code commits with a temporary adapter. Record this as Design Discussion Record entry 30 and update `adr-draft.md` section 3 in the same change (D14, D15). Add torrust#2415's `manual-verification-evidence.md` (V1: unit tests, doctests on stable and nightly, six mutations, the root-package suite, and the prose-first review), mark T6a done, and update both progress logs. The sub-EPIC's T6 step now counts six test-side `JobManager::new()` sites in `src/app.rs`. Co-authored-by: Copilot <[email protected]>
…its own reservation token Every component that application bootstrap registers in `JobManager` now reserves itself first, builds its runner with the reservation's own cancellation token, and is spawned with that reservation. The four server sites no longer take a child of the shared root token. The legacy `udp_ban_cleanup` job keeps the root token, now reached only through `JobManager::legacy_cancellation_token()`. Bootstrap propagates a registration failure as the new `app::Error::ComponentRegistration`, so `start_jobs` keeps its cancel-and-wait cleanup. The temporary `spawn_unreserved` adapter is removed, and the remaining direct `JobManager` users (the manager and profiling tests) use reservations. No existing test noticed a component built with a token other than its own: it was aborted at the shared deadline and every test still passed. A new application-level test starts every component, cancels the manager, and requires each one to stop cooperatively. `cancel()` still cancels every component at once, so shutdown behavior is unchanged. Co-authored-by: Copilot <[email protected]>
…n tokens The application jobs guide, the glossary, and the shutdown task inventory describe the current implementation. `JobManager` now issues each direct component its own cancellation token through a reservation and cancels them all at once; only the legacy `udp_ban_cleanup` job uses the root token. Update the token column, ownership tree, and diagram of the task inventory, which the ADR requires revisiting when lifecycle topology changes. The stop order stays marked as planned. Co-authored-by: Copilot <[email protected]>
…-complete review Record in torrust#2415's `manual-verification-evidence.md` the caller inventory, the AC1 gap that no existing test caught and the application-level test that now guards it with its 14 token mutations (V2), and the like-for-like shutdown comparison with `develop` for SIGTERM and SIGINT (V3, M1). Mark T6b, T6c, M1, and the design-review checkpoint done, point the acceptance table at the evidence without ticking the criteria, and update both progress logs. Co-authored-by: Copilot <[email protected]>
…ves other components uncancelled The release test only checked that the other component was cancelled after `cancel()`, which also holds if dropping a reservation had already cancelled it. Move the drop into the Act and assert that the other component's token is still uncancelled right after it. A mutation that cancels only the other components on drop passed the old test and fails this one. Found by the independent Task Reviewer. Also explain in `cancel_all` why cancelling tokens while holding the registry lock is safe. Co-authored-by: Copilot <[email protected]>
…low-up, and the retrospective Add torrust#2415's `agent-review-reports.md` with the independent Task Reviewer report (REVIEW PASSED, with findings) and what was done for each finding, and `implementation-retrospective.md`. Record in the evidence the removed duplicate manager test (S1), the strengthened release test and its mutations (S2, V4), and the final full suite and M1 recheck on the last code commit (S3, V4). Restamp sub-EPIC record entry 30 to 20:53, the minute the maintainer's answer arrived (N1), and update both progress logs. Co-authored-by: Copilot <[email protected]>
…nce-review decisions The maintainer approved pushing and opening the pull request without a rebase, and decided that reviewing and merging it is the acceptance review, as for torrust#2414, so the acceptance criteria are ticked after the merge. Co-authored-by: Copilot <[email protected]>
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Copilot review overview
3 open issues
What changed in this PR
Refactors JobManager registration to use per-component cancellation tokens issued via reservations, enabling future ordered shutdown while preserving current “cancel everything at once” behavior.
Changes:
- Introduces
JobManager::reserve()/ reservation-consumingspawn()with per-component tokens and aSpawnErrorfor foreign reservations. - Updates application bootstrap and profiling code to reserve first, build runners with the reservation token, then spawn.
- Adds reservation lifecycle tests and updates docs to describe the per-component token model.
| File | Description |
|---|---|
| src/bootstrap/jobs/manager.rs | Adds reservation registry, per-component tokens, foreign-reservation error, and new unit tests for lifecycle semantics. |
| src/app.rs | Converts all components to reserve+spawn using per-component tokens; adds bootstrap error propagation and an app-level cooperative-shutdown test. |
| src/console/profiling.rs | Updates profiling test to use reservation-issued token and spawn via reservation. |
| docs/issues/open/2415-2410-si-22-3-per-component-cancellation-tokens/manual-verification-evidence.md | Records testing/mutation evidence and M1 shutdown comparison for #2415. |
| docs/issues/open/2415-2410-si-22-3-per-component-cancellation-tokens/implementation-retrospective.md | Adds implementation retrospective and process learnings for #2415. |
| docs/issues/open/2415-2410-si-22-3-per-component-cancellation-tokens/agent-review-reports.md | Adds independent task reviewer report and follow-up outcomes. |
| docs/issues/open/2415-2410-si-22-3-per-component-cancellation-tokens/ISSUE.md | Updates issue status/progress and links to new evidence artifacts. |
| docs/issues/open/2410-1488-si-22-process-queued-events-before-listeners-stop/adr-draft.md | Updates ADR draft to reflect reservation semantics and error propagation. |
| docs/issues/open/2410-1488-si-22-process-queued-events-before-listeners-stop/EPIC.md | Updates epic status/progress log and records design-review decisions for T6. |
| docs/features/shutdown-process/task-inventory.md | Updates shutdown inventory to reflect per-component tokens and legacy root token usage. |
| docs/architecture/glossary.md | Updates glossary entries to reflect reservations and legacy root token semantics. |
| docs/architecture/application-jobs.md | Updates ownership/shutdown documentation for reservation-based components and legacy jobs. |
Review effort: Lite
…r instead of reusing ids `ComponentRegistry::reserve` incremented `next_id` with `+= 1`, which wraps silently in release builds (no overflow checks), so after 2^64 reservations an id would be reused and overwrite another component's registry entry. Use `checked_add` and fail loudly with a clear message. It cannot happen in practice (bootstrap reserves about 14 components), so `reserve` keeps returning a plain value. A new test reserves from a registry whose next id is `u64::MAX` and expects that panic; with the old increment it fails in both a dev build (overflow panic with another message) and a release build (no panic). Found by Copilot review of PR torrust#2591. Co-authored-by: Copilot <[email protected]>
… is registered `ComponentRegistry::mark_spawned` ignored a missing component id. It cannot be missing: `spawn` has already checked that the reservation belongs to this manager, and an entry is removed only by its own reservation's `Drop`, which runs after the call. State that invariant and check it with `debug_assert!`, so a future change that breaks it fails loudly in tests instead of leaving a token untracked. Found by Copilot review of PR torrust#2591. Co-authored-by: Copilot <[email protected]>
…udit Record Copilot review 5596471839: F1 (the component id counter could wrap in release builds) and F3 (`mark_spawned` ignored a missing id) are fixed in their own commits, and F2 repeats F1 on the increment line. Each row carries its verification, resolution reference, and reply URL. Co-authored-by: Copilot <[email protected]>
…ilot review round Set the spec's `related-pr` and add progress-log entries for the pull request and the review round, whose audit is in `docs/pr-reviews/pr-2591-review/PR-REVIEW.md`. Co-authored-by: Copilot <[email protected]>
…ust#2591 review threads All three threads were replied to, then resolved; a refreshed GraphQL fetch shows none unresolved. Co-authored-by: Copilot <[email protected]>
|
ACK 492d19a |
Issue #2415 is closed on GitHub, merged in PR #2591. Move its spec folder to `docs/issues/closed/`, set `status: done`, `spec-path`, and `last-updated-utc`, and repair the path references in its own artifacts and in the parent sub-EPIC, whose Subissues row and T6 plan row are now `DONE`. At the maintainer's instruction, his review and merge of the pull request count as the acceptance review, so AC1 to AC4 and the `linter all` criterion are ticked, with the qualifications recorded in the spec's progress log. Co-authored-by: Copilot <[email protected]>
…ssues/closed d7f32d4 chore(issues): archive closed issue #2415 spec to docs/issues/closed (Jose Celano) Pull request description: Archives the spec of issue #2415 from `docs/issues/open/` to `docs/issues/closed/`, after PR #2591 merged and the issue was closed on GitHub (verified: `CLOSED`, closed 2026-10-21 09:19 UTC). - Moves the spec folder (`ISSUE.md`, `manual-verification-evidence.md`, `agent-review-reports.md`, `implementation-retrospective.md`) and updates its frontmatter: `status: done`, `spec-path`, `last-updated-utc`. The path references in its own artifacts are repaired. - Ticks AC1 to AC4, the `linter all` criterion, and the last workflow checkpoint, because the maintainer chose to count his review and merge of PR #2591 as the acceptance review, as for #2414. The qualifications are in the spec's progress log: AC4 was read from source and not run, and AC1 is proven by the application-level test added in PR #2591. - Updates the parent sub-EPIC #2410: the Subissues row now links the archived spec and is `DONE`, the T6 plan row is `DONE`, and the progress log has an entry. - Searched the repository for the old folder name; the only remaining reference is the corrected sub-EPIC link. Documentation only: no source or test changes. Related to #2415. ACKs for top commit: josecelano: ACK d7f32d4 Tree-SHA512: 64e16a0e6610eed63323cc5813a15f75f67b41dbcecca38851af5f592e97d674f2c5a599686111d604ed81981c95d3e469aee4920f42a1438b90df2490fbe242
…its spec to docs/issues/closed c19fca7 chore(issues): [#2410] close sub-EPIC SI-22 and archive its spec to docs/issues/closed (Jose Celano) Pull request description: ## Summary Closes #2410 All four sub-issues of sub-EPIC #2410 (SI-22, process queued events before listeners stop) are merged and archived: #2413 in PR #2553, #2414 in PR #2578, #2415 in PR #2591, and #2416 in PR #2623. This PR closes the sub-EPIC itself, which was still open on GitHub with its acceptance criteria and workflow checkpoints unticked and its completion review unassessed. It follows the precedent of PR #2557 (EPIC #2243): the archive and the closing keyword travel together. ## What changed - Moved `docs/issues/open/2410-1488-si-22-process-queued-events-before-listeners-stop/` to `docs/issues/closed/` with `git mv`, set the EPIC to `status: done` with the new `spec-path`, and kept `reproduce-lost-completions.sh` in the folder (the maintainer decided to keep it at the #2416 checkpoint). - Filled the Acceptance Verification table (AC1 to AC13) with the artifact behind each criterion, ticked the criteria and workflow checkpoints, marked M2 and M3 done with their evidence, and filled the Implementation Completion Review. Qualifications are kept, not dropped: the 5 s drain default is a policy choice and not derived from the measurement, the race runs do not prove loss window (b), a shared-deadline abort leaves an in-progress outcome unknown, the UDP environment's red is by mutation, and bus retention through listener join is read from source and not run. - Added `agent-review-reports.md` with the independent Task Reviewer review of this close-out (verdict `REVIEW PASSED WITH FINDINGS`, 3 should-fix and 4 nits, all fixed in this commit). - Repaired every live link to the old folder (the four archived sub-issue specs and their retrospectives and evidence files, the #2412 and #2448 specs, the glossary, and the promoted ADR) and bumped `last-updated-utc` on each touched document that carries it. - Set row 15 of the EPIC #1488 roadmap to `Done` and updated the three SI-22 statements in that spec that still described it as pending. - Repointed the draft-ADR reference in the #2418 spec to the promoted ADR. ## Acceptance The criteria and checkpoints are ticked in advance of the merge, as in #2557, and the progress-log entry says so: the maintainer's review and merge of this PR are the acceptance review, as for #2414 to #2416. If the review changes any criterion, it should be unticked before the merge. ## Deliberately retained references The old folder path remains only in historical records: two recorded commands in the sub-EPIC and #2414 evidence files, the "moved to" checkpoint text in the EPIC, and the review audits under `docs/pr-reviews/` (`pr-2421-review`, `pr-2553-review`). ## Not part of this PR Follow-ups #2418 (batch persisted download writes) and #2411 (spam and abuse EPIC) stay open and do not block this close-out. #2406 and #2417 are already closed. No sub-EPIC-level implementation retrospective was written, and the completion review gives the reason. ## Validation - `linter all` exits 0, including the local link and fragment check, which skips `docs/issues/closed/`, so the archived files were also checked with lychee and an empty config: 100 links OK, 0 errors. - The signed commit passed the pre-commit hook, including the frontmatter validator and `cargo test --doc --workspace`. - `git merge-tree` against `torrust/develop` shows a clean merge. - Documentation only: no code changed. No tests were re-run beyond the hook's doc tests; the acceptance claims about tests cite the sub-issues' recorded runs and the test names found on the tree (read from source, not run). ACKs for top commit: josecelano: ACK c19fca7 Tree-SHA512: de784fead66e0eb1b6b9b7bf7e7aea9d29a2a3dbd297740752d23eca6fbaa700f20926e81033fdc06d31b72ff0f00302f522df7bce8354de87a3c9d48a0c7121
da2ce7
left a comment
There was a problem hiding this comment.
This is a post-merge review of the change from #2591 (merged as 321e83b) as it stands at a94c3ce on the default branch.
What still runs: JobManager::reserve issues each component its own CancellationToken through a Reservation, spawn consumes the reservation and rejects one issued by another manager, an unspawned reservation releases itself on drop, and a reservation issued after cancel() carries a cancelled token (src/bootstrap/jobs/manager.rs:201-269, :377-427, :603-635). In src/app.rs every component (fourteen kinds now that udp_ban_cleanup was migrated in 1c3daab) reserves first, builds its runner with its own reservation's token and spawns with that reservation, and a registration failure surfaces as Error::ComponentRegistration (src/app.rs:85) through start_jobs, which cancels and joins whatever already started (src/app.rs:294-306). The legacy root token, legacy_cancellation_token and register_legacy that this change kept are gone since 1c3daab, and the stop order added in a743450 and 6bb38ed now builds on the per-component tokens.
[Minor] Since 6bb38ed, spawn can fail in two cases that its documentation and the reservation contract set up by this change say it cannot, once a stop-last component has been reserved, which every manager built by start_jobs has (src/app.rs:320). spawn_with adds the implicit edge to the stop-last component on every spawn (src/bootstrap/jobs/manager.rs:660-666). First, after cancel(), add_stop_before rejects any non-empty edge list (manager.rs:444-446), so let last = m.reserve_stop_last("hc"); let r = m.reserve("c"); m.cancel(); m.spawn(r, runner) returns Err(SpawnError::ShutdownRequested) and drops the runner, while the same reserve, cancel, spawn sequence succeeds on a manager without a stop-last component, as it_should_cancel_a_reserved_component_that_is_spawned_after_the_manager_is_cancelled (manager.rs:1135) shows. Second, stop_last is set at manager.rs:595 and never cleared, so after drop(last) releases the stop-last reservation every later m.spawn(r, runner) returns Err(SpawnError::UnknownStopBeforeTarget) (manager.rs:437-438), contrary to "Dropping a reservation without spawning it releases it: the manager forgets its token and no other component is affected" (manager.rs:217-218); the test at manager.rs:2014 spawns its other component before the drop, so it does not reach this. spawn's # Errors section (manager.rs:625-629) lists only ForeignReservation. Application startup takes neither path today, because it never spawns after cancel() or after the stop-last reservation is dropped, so the effect is on callers of the public API, such as tests/common/workspace.rs:102-111, which adds components to a running application. Smallest fix: keep the stop-last id in the registry and clear it in release_if_reserved, and either skip the implicit edge once shutdown was requested (the late component's token is then already cancelled) or list ShutdownRequested and UnknownStopBeforeTarget under spawn's # Errors.
[Nit] Reservation::cancellation_token still says the token "is cancelled by JobManager::cancel" (src/bootstrap/jobs/manager.rs:257-258). Since a743450, cancel() cancels only the components that wait for nobody; a component with stop-before predecessors, including the health check API in every application manager, is cancelled later from wait_for_all (manager.rs:494-512). A caller that calls cancel() and then awaits such a component's token without driving wait_for_all waits indefinitely. Smallest fix: say the token is cancelled by cancel(), or by wait_for_all once the components it waits for have completed, as the module documentation at manager.rs:12-17 already does.
[Nit] src/AGENTS.md:79 still documents spawn(name, future), and the "Adding a New Service" checklist (src/AGENTS.md:103-106) says to pass the runner directly to job_manager.spawn and to listen for "the CancellationToken passed from JobManager" without saying where that token comes from. This change made spawn take a Reservation and requires the runner to be built with reservation.cancellation_token(). Following the checklist either does not compile or, if the runner is given a token of its own, leaves a component that cancel() never reaches: it is aborted at the shutdown deadline and the process exits 1 (the application-level test at src/app.rs:1242 does catch that case). Smallest fix: replace the bullet with reserve(name), spawn(reservation, future) and spawn_with(reservation, StopBefore(..), future), and make item 4 read "reserve, build the runner with the reservation's token, then spawn it (through spawn_listener or spawn_producer for components on an event bus)".
Checked and found sound: the description's claims against the diff (all 13 components reserve before their runners are built, the four .child_token() calls are removed, the registration order is kept, cancel() is idempotent, late reservations are issued cancelled, and a foreign reservation is rejected and released from the manager that issued it); that each component in src/app.rs at a94c3ce hands its own reservation's token to its own runner and to nothing else; that every startup error path drops the unspawned reservation without leaving a detached task holding its token, because the HTTP tracker, REST API, UDP tracker and health check runners own their server tasks through owners that abort on drop; the lock discipline, with no registry guard held across an await or while a Reservation is dropped, including the early return inside spawn_with; the poison-tolerant lock; the id-exhaustion panic, which cannot be reached in practice; the doctest import paths; and the application-level test at src/app.rs:1242, which still fails when any started component is built with a token that cancel() does not reach.

Summary
Gives every top-level component that
JobManagersupervises its own cancellation token, issued through a reservation, instead of a clone or child of one shared root token. This is T6 of sub-EPIC #2410 (SI-22.3, sub-issue 3 of 4), a behavior-preserving refactor that prepares the stop order of #2416:cancel()still cancels every component at once, so shutdown is unchanged.Closes #2415
Related to #2410 and #1488.
Changes
src/bootstrap/jobs/manager.rs:JobManager::reserve(name)returns aReservation(aComponentIdand the component's ownCancellationToken, not derived from any other token).spawn(reservation, future)consumes it, so it cannot be spawned twice (acompile_fail,E0382doctest checks this), and returnsSpawnError::ForeignReservationfor a reservation issued by another manager. Dropping an unspawned reservation releases it.cancel()cancels the legacy root token and every reserved or spawned component token, and a reservation issued aftercancel()carries a cancelled token. The root-token accessor is renamedlegacy_cancellation_token(); onlyregister_legacyjobs use it.src/app.rs: all 13 components reserve first, build their runner with the reservation's token, and spawn with it; the four.child_token()calls are gone; the legacyudp_ban_cleanupkeeps the root token. A registration failure is propagated as the newapp::Error::ComponentRegistration, sostart_jobskeeps its cancel-and-wait cleanup. Registration order (listeners before producers) is unchanged.reserveand betweenreserveandspawn, idempotentcancel(), a dropped reservation released without affecting others, a foreign reservation rejected, independence from the root token), the existing manager and profiling tests converted, and a new application-level test that starts every component, cancels, and requires each one to stop cooperatively. No test guarded that before: a component built with an unrelated token was aborted at the shared deadline and every existing test, includinglifecycle-signals, still passed.docs/architecture/application-jobs.md,docs/architecture/glossary.md, anddocs/features/shutdown-process/task-inventory.mddescribe the per-component tokens; the sub-EPIC records the T6a design-review decisions as Design Discussion Record entry 30, withadr-draft.mdsection 3 updated (D14, D15); the sub-EPIC's T6 step now counts six test-sideJobManager::new()sites insrc/app.rs; and a progress-log entry that had been appended after## Referencesis moved into the progress log.The commits follow the agreed split: the API with a temporary
spawn_unreservedadapter (refactor(bootstrap): [#2415] add JobManager reservations that issue each component its own token), then the caller conversion that removes it (refactor(bootstrap): [#2415] give every application component its own reservation token). Each commit compiles and passes its tests.Validation
Evidence is in
docs/issues/open/2415-2410-si-22-3-per-component-cancellation-tokens/manual-verification-evidence.md:developbuild. Exit code 0, the same 15 cooperative cancellations plus 1 legacy completion, 7 listener drain reports, no aborts, warnings or errors, and identical normalized logs. The completion order varies, as it does between runs ofdevelopitself.The pre-push hook passed (nightly fmt, check and docs, and the full stable test suite), as did
linter all,cargo test --test lifecycle-signals(13 passed), and every pre-commit run.Reviews
agent-review-reports.md.implementation-retrospective.mdis in the same folder. It proposes, without applying, twowrite-unit-testskill additions.The branch is not rebased onto the latest
develop: the commits that landed since it was cut touch none of its files, and it merges cleanly.