Skip to content

perf(node): coarse clock for the voucher-accept path's under-lock clock reads (#1792 item 4) - #1870

Merged
alpergundogdu merged 3 commits into
mainfrom
claude/issue-1792-bnzq86
Aug 30, 2026
Merged

alpergundogdu merged 3 commits into
mainfrom
claude/issue-1792-bnzq86

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

What

Addresses item 4 of #1792 (Group E of the serve-path hot-path audit): "SystemTime::now() syscalls under the lane lock."

The voucher/preimage accept path reads the wall clock twice while holding the per-lane tokio::Mutex — the capability-expiry gate (voucher.rs) and the last_voucher_at liveness stamp (both the voucher and preimage paths). So every accepted proof pays two SystemTime::now() syscalls inside the most contended critical section on the paid delivery path. Both reads tolerate ~second resolution: one is an on-chain grant deadline, the other a best-effort admin diagnostic ("seconds since last voucher").

Change

  • New crate::coarse_clock::CoarseClock — an AtomicU64 of Unix milliseconds. A background task refreshes it every 500 ms, so the two under-lock reads become one relaxed atomic load instead of a syscall.
  • The refresher (CoarseClock::spawn_refresher) holds only a Weak, so it is self-terminating: once the handler (the clock's last owner) drops at shutdown, the next upgrade() fails and the loop exits. It owns no queue and awaits no sender, so it needs no StopHandle wiring.
  • Wired as an optional ClientHandlerDeps.coarse_clock; the runtime creates one, spawns the refresher, and passes it in. voucher.rs reads self.coarse_clock.unix_seconds() / unix_millis().

Behavior is unchanged everywhere a refresher isn't running

Until a refresher runs, the cell holds a 0 sentinel and every read falls back to a live SystemTime::now(). So a handler built without one — every unit and loopback test, which construct handlers via ClientHandlerDeps::new (defaulting the field to None) — reports the exact wall clock and behaves precisely as before. Only the runtime attaches a refresher, so the coarsening is a production-only optimization, not a semantic change. 0 is a safe sentinel because a real Unix-ms reading is never zero.

Scope is strictly the two under-lock reads. The unix_millis() admin readouts outside the lane lock (region-stats age reporting) keep reading the live clock, where accuracy matters and there's no contention to relieve.

Correctness notes

  • unix_seconds() = unix_millis()/1000 = floor(ms/1000), identical to the prior payment_settlement::unix_now() (Duration::as_secs()) for the same instant — a drop-in for the expiry comparison.
  • In production the clock lags real time by at most the 500 ms refresh interval: expiry is enforced ≤0.5 s late (well within "~second resolution"), and a slightly-behind last_voucher_at only makes a lane look marginally staler — the safe direction the field already documents.

Testing

  • cargo build -p decdn-node — clean
  • cargo clippy -p decdn-node --all-targets — clean (no anti-panic policy violations)
  • cargo test -p decdn-node --lib — 771 passed (incl. 3 new coarse_clock tests: live fallback, stamped read-back, refresher-stamps-then-self-terminates)
  • cargo test -p decdn-node --test client_loopback -- capabilit region activity voucher expir — 13 passed (capability-expiry gate + lane-activity readouts exercised)
  • cargo fmt --check and cargo doc -D warnings — clean

Closes #1792 item 4.

🤖 Generated with Claude Code

https://claude.ai/code/session_013MSiZrVoUQzy4J5Ci8RGEu


Generated by Claude Code

…ck reads

Group E item 4 of the serve-path hot-path audit (#1792): the
voucher/preimage accept path reads the wall clock twice while holding the
per-lane mutex — the capability-expiry gate and the `last_voucher_at`
liveness stamp — so every accepted proof pays two `SystemTime::now()`
syscalls inside the most contended critical section on the paid path.
Both reads tolerate ~second resolution (an on-chain grant deadline and a
best-effort admin diagnostic).

Add `CoarseClock`: an `AtomicU64` of Unix milliseconds that a background
task refreshes every 500 ms, so those two reads become one relaxed atomic
load. The refresher holds only a `Weak`, so it self-terminates when the
handler (the clock's last owner) drops at shutdown and needs no
`StopHandle` wiring.

Until a refresher runs the cell holds a `0` sentinel and every read falls
back to a live `SystemTime::now()`, so a handler built without one — every
unit and loopback test — reports the exact wall clock and behaves exactly
as before. Only the runtime attaches a refresher, so the coarsening is a
production-only optimization, not a semantic change. The admin readouts
outside the lane lock keep reading the live clock.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_013MSiZrVoUQzy4J5Ci8RGEu
Copilot AI lite review requested due to automatic review settings August 29, 2026 22:19

Copilot AI 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.

Pull request overview

This PR implements issue #1792 item 4 by removing SystemTime::now() syscalls from the most contended per-lane tokio::Mutex critical section in the paid delivery voucher/preimage accept path. It introduces a background-refreshed coarse wall clock (atomic Unix milliseconds) and wires it into the runtime so the under-lock timestamp reads become relaxed atomic loads in production, while tests continue to use live wall-clock reads via the None fallback.

Changes:

  • Add CoarseClock (AtomicU64 unix-millis) with an optional background refresher task.
  • Wire CoarseClock through ClientHandlerDeps and initialize/spawn the refresher in the node runtime.
  • Replace under-lock clock reads in voucher.rs (capability expiry gate + last_voucher_at stamps) to use the coarse clock.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
crates/node/src/runtime/mod.rs Creates a shared CoarseClock, spawns the refresher, and injects it into ClientHandlerDeps.
crates/node/src/lib.rs Exposes the new coarse_clock module.
crates/node/src/handlers/client/voucher.rs Switches expiry/liveness under-lock clock reads to use self.coarse_clock.
crates/node/src/handlers/client/mod.rs Adds optional coarse_clock to deps and stores an Arc<CoarseClock> on the handler (fallback to live clock in tests).
crates/node/src/coarse_clock.rs New coarse clock implementation + unit tests for fallback/tick/refresher behavior.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread crates/node/src/coarse_clock.rs Resolved
Comment thread crates/node/src/handlers/client/mod.rs Resolved
claude added 2 commits August 29, 2026 22:22
The `cargo doc` CI job runs `--document-private-items` with `-D warnings`,
which resolves and checks the intra-doc link to the `pub(super)`
`handlers::client::unix_millis` — a path not reachable from the crate
root, so it fails as a broken link. Render it as a plain code span.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_013MSiZrVoUQzy4J5Ci8RGEu
Two doc-precision fixes on the coarse-clock docs:
- Each read is a single relaxed atomic load; there are still two reads per
  proof (expiry gate + last_voucher_at stamp), so say "each becomes a load"
  rather than implying the two collapse into one.
- The `0` sentinel: a live millisecond reading is 0 only at the Unix epoch
  itself, which a running node's clock is not at — reword to avoid claiming
  0 is impossible, and note a stray 0 just routes reads to the live clock.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_013MSiZrVoUQzy4J5Ci8RGEu
@github-actions

Copy link
Copy Markdown

Coverage report

Total: 82.09% (was 82.08%, ▲ +0.01%) — 68204/83083 lines

File Coverage Lines Δ
crates/node/src/coarse_clock.rs 100.00% 73/73 new
crates/node/src/handlers/client/mod.rs 92.74% 1571/1694 ▲ +0.01%
crates/node/src/handlers/client/voucher.rs 93.21% 494/530 ● 0.00%
crates/node/src/runtime/mod.rs 47.71% 1154/2419 ▼ 0.10%
History
Commit Total Δ vs base
bbbee51 (HEAD) 82.09% ▲ +0.01%

@alpergundogdu
alpergundogdu merged commit 4d51282 into main Aug 30, 2026
25 checks passed
@alpergundogdu
alpergundogdu deleted the claude/issue-1792-bnzq86 branch August 30, 2026 09:03
yigitdot added a commit that referenced this pull request Aug 30, 2026
One conflict, in `dispatch.rs`'s `use super::{…}` list. Main's per-lane
perf work (#1870/#1872/#1873) dropped `Mutex` from it when the accepted
`LaneState` moved into the lane instead of being cloned; this branch had
added `FloorRefusalSite` for the split refusal logging. Took the union:
main's list, minus `Mutex` (no remaining use in the file), plus
`FloorRefusalSite`.

Everything else auto-merged, including both serve loops where the perf
commits and this branch's floor calls are adjacent. Verified the floor
surface survived intact: `release_if_repaid` and the pool-only mid-stream
re-check in `delivery.rs` / `serve_leg.rs`, both admission gates and the
refusal logging in `dispatch.rs`, and the accumulator itself.

Co-Authored-By: Claude Opus 5 (1M context) <[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.

perf(node,incentive): voucher path — global LaneBuffer mutex nested under the per-lane lock; per-proof clones, allocs, and syscalls

3 participants