Skip to content

perf: cheaper local dispatch, linear handler teardown, observability build switch - #1176

Merged
Yaraslaut merged 11 commits into
masterfrom
perf/dispatch-cost
Nov 27, 2026
Merged

Yaraslaut merged 11 commits into
masterfrom
perf/dispatch-cost

Conversation

@Yaraslaut

Copy link
Copy Markdown
Member

Cuts the per-call cost of local dispatch, and adds benchmark gates that keep it down.

Fixes #1173

Changes

  • Handler teardown is linear (bridge.hpp). Each binding records its slot in Bridge::_handlers. Deregistering swaps it with the last entry and pops it, instead of scanning every live handler.
    • Before: 4–134 µs per handler, quadratic in the number of live handlers.
    • After: 0.3–0.9 µs.
  • ThreadPoolExecutor spins before it sleeps (PoolOptions{spinBeforeSleep = 25us, maxSpinners = 1}).
    • post() notifies only when a worker is asleep and more tasks are queued than there are spinning workers to take them.
    • After the spin, the worker re-checks the queue under the lock, which closes the lost-wakeup window. A deterministic test using the afterSpin hook proves this; removing the re-check makes it fail.
    • Throughput, 8 workers, before → after: 1 call in flight 22k → ~70k calls/s; 64 in flight 63k → ~211k calls/s. The owner thread's kernel share went from 69% to 29%. Full table in executor.md.
  • Cheaper local run (backend.hpp).
    • The cancel record and the in-flight counter share one shared_ptr.
    • run.strands is copied only for Task runs.
    • The clock is read only when a metric sink is installed.
    • About 300 fewer instructions per call.
  • MORPH_ENABLE_OBSERVABILITY (default ON). OFF compiles emits, spans, clock reads and the in-flight counter out of the dispatch path. Installing a sink in an OFF build is a static_assert that names the option. A configure-time try_compile proves both the refusal and its message on every platform; a positive control compiles without the macro.
  • Benchmark gates (MORPH_BUILD_LOAD_TESTS):
    • bench.instr_budget: user-space instructions per local call. Linux perf_event_open; other platforms report Skipped, not passed.
    • bench.teardown_scaling: per-handler destroy cost at 32k handlers over the cost at 2k.
    • morph_bench_scaling: strand throughput as threads are added, report only.
    • Each gate was shown to fail against an injected regression.

Verification

  • clang Debug (local): morph_tests 4510/4511, the one failure being the expected-failure case; bench.alloc_budget, bench.instr_budget (57.5k per call, ceiling 65k) and bench.teardown_scaling (ratio 1.2, limit 7) pass.
  • Release (local): bench.instr_budget 7256 per call (ceiling 9000), bench.teardown_scaling ratio about 2.
  • MORPH_ENABLE_OBSERVABILITY=OFF: morph_tests built and passed (4463 + 1 expected failure).
  • TSan: run only on test_executor.cpp built on its own (19 cases, 3 runs, clean), not on the full suite.
  • Windows: not built locally; CI is the check. Pieces that are platform-specific: the pause hint (_mm_pause / __yield), the instruction gate (skips off Linux, and is off under MSVC), and the ScopedObserveOverride constructor-template refusal (covered by the configure-time probe).
  • Local GCC 16 -O3: test_chat_context.cpp fails with -Warray-bounds. This predates the branch: it also fails on a tree with no library changes. CI's GCC 15 is not affected.

🤖 Generated with Claude Code

https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT

Yaraslaut and others added 9 commits November 27, 2026 07:50
Each HandlerBinding records its slot in the bridge's tracking list.
deregisterHandler moves the last entry into that slot, fixes the moved
binding's slot and pops, so removal is O(1) instead of a lock() over every
live handler. Tearing down N handlers is now linear in N.

The list is unordered: switchBackend, the reconnect handler and ~Bridge each
visit every live binding once and depend on no order. Entries whose binding
died without deregistering are compacted whenever the list has doubled since
the last compaction, and by switchBackend, which rewrites the slots.

Fixes #1173

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT
morph_bench_instr counts retired user-space instructions (Linux
perf_event_open, inherited by the pool's workers) across a steady-state batch
of local round trips and fails above --budget. The ceiling is the cache
variable MORPH_INSTR_BUDGET_PER_CALL, 65000 in Debug and 9000 in the optimized
build types, each the worst measured figure plus a margin.

Where the counter cannot be opened, and on every non-Linux platform, the
binary prints the reason and exits 77, registered as SKIP_RETURN_CODE, so
ctest reports Skipped rather than a pass that measured nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT
morph_bench_teardown destroys 2000 and then 32000 live handlers on one
Bridge and fails when the per-handler destroy cost at the large count exceeds
--max-ratio times the cost at the small one. A ratio cancels machine speed and
build type: constant-cost teardown reads near 1 (1.3 to 4.8 measured), a scan
of every live handler reads 9.5 to 12.6 in Release. The ceiling is the cache
variable MORPH_TEARDOWN_MAX_RATIO, 7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT
morph_bench_scaling posts empty, ~1 us and ~5 us tasks over 1024 keys with 1,
2, 4 and 8 producers and workers, to ModelStrands and to the bare pool, and
prints rate and efficiency against the one-thread rate. It is a measurement
with no ctest case, since wall-clock scaling is machine-dependent; it exits
non-zero only when a task is lost, doubled or late.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT
A worker that finds the queue empty spins on an atomic queue counter for up to
`PoolOptions::spinBeforeSleep` (25 us by default) before it takes the lock and
sleeps. A task posted during the spin is taken with no system call on either
side. At most `maxSpinners` workers (default 1) spin at once; the rest sleep
immediately.

`post()` notifies a sleeper only when one exists and more tasks are queued than
workers are spinning. The sleeping and spinning counts change under the pool's
mutex, and a worker leaving its spin re-tests the queue under that mutex before
it waits, so a task posted in the gap is never missed. A worker that takes a
task applies the same rule to what remains.

`spinBeforeSleep = 0` restores sleeping at once. The spin is bounded by elapsed
time and uses a CPU relax hint (`_mm_pause`, `__yield`, `yield`, or nothing)
rather than a system call.

Measured with a tiny model on an 8-worker pool (loaded 12-core machine): 64
calls in flight went from about 62k to about 205k calls/s, and CPU per call
from 16.5 us to 4.4 us; the owner thread's kernel share fell from 69% to 29%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT
… only when timed

An ordinary run no longer copies the strands pointer: only a Task run reaches
the strands after its strand task returns. The cancel record and the in-flight
counter live in one shared object, so a run holds one `shared_ptr` for both
instead of two.

`admitLocal` reads the clock only when a metric sink is installed at that
moment; a call that starts with no sink emits no latency sample, and a
dispatch with no sink costs no clock reads. Tracing is decided separately at
`beginSpan`.

Measured with SPIN_US=0 and no sinks (tiny model, 8 workers, instructions per
call, three runs each): 7831 before, 7544 after with one call in flight; 7688
and 7708 before, 7347 and 7414 after with 64 in flight.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT
…ce seams out

The CMake option (default ON) defines MORPH_OBSERVABILITY_DISABLED publicly on
the morph target when OFF. With it defined, `emitMetric`, `beginSpan` and
`endSpan` are empty inline functions, `metricsEnabled()` is the constant
`false`, and `LocalBackend` takes no clock readings and keeps no in-flight
counter, which exists only to feed the `executeInFlight` metric.

`setMetricSink`, `setTraceSink` and `ScopedObserveOverride` refuse to compile in
that build, with a static_assert whose message names the option, instead of
accepting a sink that is never called. The refusal is a dependent static_assert
rather than `= delete("...")`, which not every supported compiler accepts.

Test cases and the concepts example that install a sink are wrapped in
`#if !defined(MORPH_OBSERVABILITY_DISABLED)`. A configure-time try_compile
proves each of the three ways of installing a sink fails with the message when
the macro is defined, and compiles when it is not.

Measured with SPIN_US=0 and no sinks (tiny model, 8 workers, instructions per
call): 7543 with the option ON (unchanged), 7437 with it OFF at one call in
flight; 7403 and 7297 at 64 in flight.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT
A spinning worker's instructions follow how long it waited, not what a
call executed, so the gate's pool does not spin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT
Matches how include/ and src/ write them, and what
readability-use-concise-preprocessor-directives asks for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT
@Yaraslaut Yaraslaut added enhancement New feature or request area: core Subsystem: core labels Nov 27, 2026
Yaraslaut and others added 2 commits November 27, 2026 10:59
…aces the end of a spin

Waiting for exactly one sleeping worker raced the spinner's own timeout,
and Windows' coarse sleep clock stepped over that window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01No1NznVMyxFCQxEaxFfFAT
@codecov

codecov Bot commented Nov 27, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.77419% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
include/morph/core/bridge.hpp 90.00% 1 Missing and 2 partials ⚠️

📢 Thoughts on this report? Let us know!

@Yaraslaut
Yaraslaut merged commit 7684a61 into master Nov 27, 2026
34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: core Subsystem: core enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bridge: destroying a BridgeHandler scans every live handler, so tearing down N handlers is O(N²) on the owner thread

1 participant