Skip to content

fix(command): transfer pending commands during main upgrade - #1846

Merged
FlorentinDUBOIS merged 4 commits into
mainfrom
fix/upgrade-main-transfer-pending-commands
Oct 4, 2026
Merged

FlorentinDUBOIS merged 4 commits into
mainfrom
fix/upgrade-main-transfer-pending-commands

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

The main-process hot upgrade rebuilt an empty command Hub while worker work could still be in flight. The original command client then received EOF, and a later worker response reached the replacement as an unknown task even though its data-plane request could still finish.

This change transfers the complete control-plane ownership graph to the replacement main: connected clients, client and worker channel buffers, active and queued tasks, worker-response routes, subscribers, worker pending queues, stopped workers still referenced by a task or route, task deadlines, audit clocks, and future-ID counters. The replacement restores task state directly without replaying operator requests or re-scattering work.

The handoff uses an explicit V2 PREPARED / COMMIT / ACTIVATED protocol:

  • the replacement validates and registers inherited descriptors while paused, without command or worker data I/O;
  • pre-commit rejection closes and reaps the candidate, restores CLOEXEC, and lets the unchanged old Hub continue;
  • the first attempt to send COMMIT irreversibly fences the old Hub, so an ambiguous post-commit failure cannot execute work twice;
  • after a complete commit, the replacement activates the Hub, schedules restored sessions once, publishes PID and systemd readiness, preserves the initiating client's terminal response under backpressure, and acknowledges activation before the old main exits.

Compatibility fails closed before adoption. A running main from before this protocol cannot export the missing Hub state, so the first deployment requires a controlled service restart after pending commands are drained and state is saved. Subsequent V2-to-V2 hot upgrades transfer pending commands. A V2 sender rejects a legacy candidate before freezing live ownership; a legacy sender remains subject to its existing generation, audit, and child-reaping limitations when a V2 candidate refuses its old envelope.

SIGTERM observed before commit aborts and reaps the candidate, then the old event loop consumes the preserved stop intention. Operators should signal the service control group. A signal aimed only at the old PID after the final pre-commit observation remains outside this contract, and a failure after commit is fail-stop rather than crash recovery.

The branch is based on 9561b24e61c23511326ffeb547b0b7fe51ee7055, including the deadline and cancelled-route fixes from #1838 and the PROXY protocol corrections merged in #1844.

Channel snapshot validation accepts all five defined Ready bits in both serialized readiness and interest, preserves them exactly, and rejects the first unknown bit 0x20. This covers the Linux readiness word WRITABLE | HUP | WRITE_CLOSED (0x001a) without special-casing that observed value.

Descriptor-cleanup tests observe the original command-channel and SCM socket peers instead of probing released numeric descriptors or requiring immediate EOF. EOF is the only success outcome within a fixed one-second bound: data, other errors, and expiration fail. This tolerates transient descriptor copies across a concurrent fork-to-exec window while retaining a durable duplicate of either endpoint still fails the test. The exact transient holder in the original CI jobs was not instrumented, so that scheduler-level cause remains unverified.

Validation completed locally with Rust 1.93.1 and at most four build jobs:

  • cargo test -p sozu-command-lib --locked: 244 unit tests, 9 integration tests, and 2 doctests passed; 3 existing doctests were ignored.
  • cargo test -p sozu --locked --test upgrade_fd_inheritance_e2e -- --ignored: failed 0/1 on the earlier snapshot mask with invalid channel snapshot readiness bits: 0x001a, then passed 1/1 after accepting WRITE_CLOSED.
  • the snapshot regression exercises all 32 subsets of the five defined bits in both readiness and interest; it rejects 0x20 in each field. Removing WRITE_CLOSED makes the test fail on 0x10.
  • cargo test -p sozu --locked --no-default-features --features crypto-openssl,opentelemetry,splice,simd --verbose: 152/152 library tests passed and every integration and doctest target completed successfully.
  • cargo test -p sozu --locked --no-default-features --features fips,opentelemetry,splice,simd --verbose: 152/152 library tests passed and every integration and doctest target completed successfully.
  • retaining durable duplicates of both the command channel and SCM endpoint makes each corrected cleanup oracle fail with both EOF deadlines; restoring the candidate makes each targeted test pass 1/1.
  • the accepted-handoff, rejected-candidate, SIGTERM-during-PREPARE, and descriptor-inheritance process tests pass 1/1 on the rebased head.
  • the compatibility matrix passes 1/1 in both directions between the rebased candidate and the frozen pre-protocol d7b5f14d binary. This verifies those two transition paths rather than certifying every historical version pair; the legacy generation, audit, and child-reaping limitations described above remain observable.
  • cargo clippy --all-targets --locked --no-default-features --features crypto-openssl,opentelemetry,splice,simd -- -D warnings and the equivalent FIPS matrix passed.
  • cargo +nightly fmt --all --check passed.
  • .github/scripts/check_doc_citations.py --base 9561b24e61c23511326ffeb547b0b7fe51ee7055 passed all 37 citations, 1,078 test names, and 15 pinned excerpts.
  • env -u RUST_LOG ... cargo +1.93.1 test -p sozu --locked --features opentelemetry,splice,simd --test sigterm_soft_stop_e2e -- --ignored: 1/1 passed. The local 27/27 missing-access-log result was caused by ambient RUST_LOG=warn, which GitHub CI does not set; the test requires its configured info access records.

GitHub CI checks are pending on the rebased commit a8bdd54b8833060576674a8c2aff0374f6e8083b.

Fixes #1832

Released descriptor numbers can be reused by parallel tests, while inherited CLOEXEC copies can transiently delay EOF. Observe the original channel and SCM peers under a fixed bound so cleanup tests reject durable leaks without mistaking number reuse for retained ownership.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/upgrade-main-transfer-pending-commands branch from 0e9e651 to a8bdd54 Compare October 4, 2026 01:09
@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator Author

Review of a8bdd54. Fix requested before merge. The transfer design checks out: descriptor ownership, rollback before COMMIT, deadlines carried as remaining time, no replay of partial load_state / UpgradeWorker work, and the #1838 interplay. Emptying the task map in generate_upgrade_data makes upgrade_keeps_draining_worker_e2e fail, so that test pins the transfer.

P1 — a pid-file write failure after COMMIT takes the whole proxy down.

  • begin_new_main_process (bin/src/upgrade.rs) now runs handle_sigterm, enable_cloexec_after_upgrade and write_pid_file after paused_hub.activate(), i.e. after COMMIT. On main they ran before the child confirmed, and a failure rolled back.
  • If any ? fails there, or complete_main_upgrade returns Fatal:
    • the child exits;
    • the old main is already fenced, so it stops too;
    • workers return when their command channel closes (lib/src/server.rs:1664-1667);
    • the old main exits 0, so Restart=on-failure does not restart the service.
  • Repro: run with pid_file_path, then rm sozu.pid && mkdir sozu.pid, then sozu upgrade.
    • This PR: the client gets ReadBlocking(NoByteToRead), every process exits and the front port refuses connections.
    • main: "Upgrade of main process failed: no feedback from the new main"; the old main and its worker keep serving.
  • Suggested fix: validate or pre-open the pid file and create the SIGTERM self-pipe before PREPARED, so only the publish step stays after COMMIT. The LIFECYCLE.md / CHANGELOG sentence "never resumes the old event loop" should also say that a post-commit failure means a full stop.

P2 — upgrade-main always fails when max_command_buffer_size < 4096.

P3:

  • bin/tests/main_upgrade_compatibility_matrix_e2e.rs:314 panics when SOZU_MATRIX_LEGACY is unset, so a plain cargo test -p sozu --all-features -- --ignored exits 101 and stops before the later test binaries. It should skip with a message instead. With the variables set (legacy binary built from 66fbce8), both directions pass.
  • Stale symbol names, which the citation gate does not catch:
    • CommandHub::from_upgrade_data in doc/configure_admin_ops.md and in bin/src/command/server.rs comments around lines 136 and 180;
    • SerializedWorkerSession::try_from in doc/protocol.md:40 and bin/src/worker.rs:389.

Verification:

  • cargo test -p sozu -p sozu-command-lib --all-features: ok.
  • clippy -D warnings: ok.
  • The --ignored process tests pass apart from the matrix panic: upgrade_keeps_draining_worker_e2e, main_upgrade_transfer_rejection_e2e, upgrade_fd_inheritance and sigterm_soft_stop.
  • sozu-e2e upgrade / command_channel: 18 passed.
  • Doc citations: ok.
  • git merge-tree against main: clean.

After COMMIT the old main is irreversibly fenced and exits whatever the
replacement does, and every worker returns from its event loop once its
command channel closes. `begin_new_main_process` restored close-on-exec,
installed its SIGTERM handler and wrote the pid file only after COMMIT, so
an unwritable pid file (or a failed handler install) stopped every process
while the old main exited 0 and `Restart=on-failure` did not restart it.

The replacement now restores close-on-exec on its paused Hub, installs its
SIGTERM handler and opens its pid file without truncating it before
PREPARED, where a failure still rolls back. After COMMIT only activation can
fail, since restoring a worker's SCM socket changes a file description the
old main shares; a pid-file write, terminal-response or ACTIVATED failure is
logged and the new main keeps running. Pinned by the process-level
`unwritable_pid_file_rolls_back_main_upgrade_and_keeps_serving`, added to the
CI process-level e2e step.

`prepare_from_upgrade_data` also expected every client channel to start at
`CLIENT_CHANNEL_INITIAL_BUFFER_SIZE`, while `Channel::new` clamps it to
`max_command_buffer_size` (#1416), so a ceiling below 4096 bytes made every
main upgrade fail; it now expects the clamped value, pinned by
`prepare_from_upgrade_data_accepts_clamped_client_channel_capacity`.

The compatibility matrix skips with a message when its frozen binaries are
not configured instead of panicking the whole `--ignored` run, and stale
`CommandHub::from_upgrade_data` / `SerializedWorkerSession::try_from`
references name the current symbols.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 7e2ebc0 into main Oct 4, 2026
28 checks passed
FlorentinDUBOIS added a commit that referenced this pull request Oct 4, 2026
…1848)

Follow-up to #1846 (merged as 7e2ebc0).

## Problem

1. A SIGTERM delivered to the whole cgroup while the replacement main waits for COMMIT makes it exit with `waiting for commit` while the old main is already fenced: the proxy stops abruptly instead of softly. The `PausedCommandHub::handle_sigterm` doc comment claimed such a signal is honoured by the new Hub's event loop.
2. A rolled-back main upgrade can leave a 0-byte pid file where none existed before.
3. The compatibility-matrix e2e reports `ok` when skipped, and its skip message is captured by libtest.

## Cause

1. `Channel::read_message_blocking_timeout` (`command/src/channel.rs`) reads with `SO_RCVTIMEO`. signal(7): such a socket read is never restarted after a handled signal, even under `SA_RESTART`, so it fails with `EINTR`. The loop retried only `WouldBlock` and returned `ChannelError::Read(Interrupted)`.
2. `util::open_pid_file` (`bin/src/util.rs`) opened with `create(true)` before PREPARED. Child-side cleanup cannot fix this: the old main SIGKILLs the child on PREPARED timeout, unexpected message, or pending SIGTERM.
3. `println!` is captured by libtest, and libtest has no skipped outcome.

## Fix

1. `ErrorKind::Interrupted => continue`. The deadline is still checked against the `Instant` captured at entry at the top of every iteration, so the wait is neither aborted nor extended. Callers:
   - fixed by this change: the child's COMMIT wait (`bin/src/upgrade.rs`), plus the old main's PREPARED and ACTIVATED waits (`bin/src/command/upgrade.rs`). All three run with the SA_RESTART SIGTERM handler installed.
   - `sozu ctl` (`bin/src/ctl/command.rs`, including the unbounded `None` wait): installs no handler, so it never sees EINTR.
   - `sozu top`: installs a `ctrlc` handler, but each of its reads is bounded at 5 s.
2. A missing pid file is no longer created before COMMIT. Only its parent is checked with `access(W_OK | X_OK)`, which fails on a missing parent, a non-directory, EROFS or EACCES, and `publish_pid_file` creates the file after COMMIT. An existing file is still opened before PREPARED without truncation, so the directory-at-path rollback in `upgrade_pid_file_failure_e2e` still fails before PREPARED.
3. The skip message goes to `std::io::stderr()` directly, which bypasses libtest capture.

The `handle_sigterm` doc comment now describes the retry. CHANGELOG `[Unreleased]` Fixed is updated.

## Tests

- `read_message_blocking_with_timeout_survives_interrupting_signals` and `read_message_blocking_with_timeout_keeps_its_deadline_under_signals` install an `SA_RESTART` `SIGUSR1` handler and `pthread_kill` the reader thread every 5 ms. Without the fix, both fail with `Read(Os { code: 4, kind: Interrupted, ... })`. With the fix, they pass in three consecutive runs.
- `open_pid_file_defers_creating_a_missing_file_until_publish` fails when the old `create(true)` is restored and passes with the fix. Also added: `open_pid_file_keeps_an_existing_file_until_publish` and `open_pid_file_rejects_a_missing_parent_directory`.
- Commands run, all passing:
  - `cargo test -p sozu -p sozu-command-lib --all-features --locked`
  - `cargo test -p sozu --all-features -- --ignored`, including `unwritable_pid_file_rolls_back_main_upgrade_and_keeps_serving` and `sigterm_during_prepare_aborts_upgrade_then_stops_the_old_main`
  - `cargo clippy --all-features --all-targets -p sozu -p sozu-command-lib -- -D warnings`
  - `cargo +nightly fmt --all --check`
  - `check_doc_citations.py --base origin/main`

Refs #1846



Signed-off-by: Florentin Dubois <[email protected]>
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.

Define pending control-command behavior across upgrade-main

1 participant