Skip to content

feat: run request handlers off Crow's io threads (#120) - #137

Closed
jrosskopf wants to merge 4 commits into
mainfrom
feat/gh-120-async-offload
Closed

jrosskopf wants to merge 4 commits into
mainfrom
feat/gh-120-async-offload

Conversation

@jrosskopf

@jrosskopf jrosskopf commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Closes #120.

The measurement

One ~6.5s query, 40 concurrent probes, a single io thread:

probes blocked >0.5s reported 503 stalled worst
offload OFF 40/40 0/40 5.04s
offload ON 0/40 40/40 0.005s

That is the whole of #120: the probe could not report the stall, because the stall was blocking the probe.

An earlier run of this measurement was wrong

It reported 0/40 blocked with the offload on, and I nearly wrote it up as success — but 0/40 also reported the stall, which makes no sense. The server had never started: /slow returned 000 in 0.2 ms and the config file was missing, so all forty "probes" were instant failures.

The script now sanity-checks that /slow really is slow and counts failed requests separately. Every number above comes from a run where /slow took 6.5 s and nothing failed.

What crosses the thread boundary

Three things, each necessary — this is where the observability work was genuinely at risk:

  • the keepalive handle (crow overlay port), or prepare_buffers() clears the connection's only remaining owners and destroys it mid-function once the io callback has returned. This is what crashed the original prototype;
  • RequestContextScope::activate on the worker and clearIf on the way out, so the audit line keeps its request id and a job that raced us is not stripped of its context;
  • SpanScope::activateOnThisThread, because OpenTelemetry's active-span stack is thread-local and the inner pipeline relies on it for parenting.

The tracing and audit integration tests now cross that boundary on every request rather than testing it directly. Inner spans, trace correlation and the audit log are all green with the offload on by default — that is the evidence the three rebindings work, and it is stronger than a dedicated test would have been.

Load shedding

A full pool answers 503 with Retry-After rather than queueing. Silently queueing turns a slow backend into unbounded memory and eventually serves a client that stopped waiting.

FLAPI_DISABLE_HANDLER_OFFLOAD=1 restores the inline path, for a deployment that hits something this did not anticipate.

Review note

The crow overlay port cannot be exercised locally — vcpkg has no network in this environment — so I patched the installed headers by hand with the port's own patch in order to build and measure. CI is the first place the port itself runs, and I would want that green before trusting it.

757 unit, 372 standalone integration, all green. No existing test modified.

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

…self

Landing the supporting work separately so each part is reviewable on its
own and none of it depends on the offload being finished.

1. ports/crow - a vcpkg overlay port carrying one patch.

   Crow already supports deferred completion: while a response is
   incomplete the read loop stops and records
   need_to_start_read_after_complete_, so no second request can land on
   that connection. What it does not offer is a way to keep the connection
   ALIVE across that window.

   prepare_buffers() starts by clearing complete_request_handler_ and
   is_alive_helper_. From the original io callback that is safe, because
   do_read's lambda still holds `self` on the stack. From a completion
   posted after that callback returned, those two lambdas are the only
   owners - so clearing them destroys `this` and every line after is a
   use-after-free. That is precisely where the prototype crashed.

   The patch adds a public shared_ptr<void> on crow::response, set
   alongside the existing handler and cleared alongside it, which a handler
   can capture to hold the connection open. Verified by experiment: the
   offload experiment that crashed reliably now answers 40/40 probes with
   none blocked and the server still alive.

   Synchronous handlers never touch it, and it is reset on the same lines
   as the references it sits with, so it adds no cycle of its own.

2. HandlerPool - bounded, with a real shutdown.

   The prototype had an unbounded queue and no shutdown ordering. An
   unbounded queue turns a slow backend into unbounded memory and unbounded
   latency, and eventually serves a client that stopped waiting long ago -
   so submit() refuses when full and the caller answers 503. Shutdown
   DRAINS rather than drops: every queued job owns a connection waiting for
   a response.

3. SpanScope::Activation - re-activate a span on another thread.

   OpenTelemetry's active-span stack is thread-local, which is what lets
   the inner pipeline parent its spans without threading a parameter
   through DatabaseManager, SQLTemplateProcessor and QueryExecutor. Work
   moved to another thread therefore starts with whatever that thread last
   had on top, and its inner spans would re-parent or become roots.
   Implemented in both twins; a no-op when tracing is compiled out.

4. RequestContextScope::clearIf - clear only what you own.

   finish() runs on the io thread, which once handlers can be offloaded may
   have picked up a different request by the time the completion posts
   back. An unconditional clear strips the newcomer of its context: no
   request id on its audit line, no correlation on its log lines, and no
   error either way.

Not yet wired up: nothing calls the pool, so behaviour is unchanged. The
offload itself, and its measurement, come next.

752 unit tests.
Wires up the pieces from the previous commit. Handlers now run on a
bounded worker pool and the response is completed back on the connection's
own io_service, holding the connection open with the keepalive handle the
crow overlay port adds.

Measured, one ~6.5s query with 40 concurrent probes, a single io thread:

  offload OFF : 40/40 probes blocked,  0/40 reported the stall, worst 5.04s
  offload ON  :  0/40 probes blocked, 40/40 reported the stall, worst 0.005s

That is the whole of #120: the probe could not report a stall because the
stall was blocking the probe.

An earlier run of this measurement was WRONG and is worth recording. It
reported "0/40 blocked" with offload on and I nearly wrote it up as a
success - but 0/40 also reported the stall, which made no sense. The server
had never started: /slow returned 000 in 0.2ms and the config file was
missing, so all forty "probes" were instant failures. The script now
sanity-checks that /slow really is slow and counts failed requests
separately, and every number above comes from a run where /slow took 6.5s
and nothing failed.

What crosses the thread boundary, and why each is needed:

- the keepalive handle, or prepare_buffers() destroys the connection
  mid-function once the io callback has returned;
- RequestContextScope::activate on the worker and clearIf on the way out,
  so the audit line keeps its request id and a job that raced us is not
  stripped of its context;
- SpanScope::activateOnThisThread, because OpenTelemetry's active-span
  stack is thread-local and the inner pipeline relies on it for parenting.

The tracing and audit integration tests now exercise that boundary on every
request rather than testing it directly - inner spans, trace correlation
and the audit log are all green with the offload on by default, which is
the evidence that the three rebindings work.

Saturation sheds rather than queues: a full pool answers 503 with
Retry-After. Silently queueing would eventually serve a client that stopped
waiting.

FLAPI_DISABLE_HANDLER_OFFLOAD=1 restores the inline path, for a deployment
that hits something this did not anticipate.

757 unit tests, 372 standalone integration tests.

Note for review: the crow overlay port cannot be exercised locally - vcpkg
has no network in this environment - so the installed headers were patched
by hand with the port's own patch to build and measure. CI is the first
place the port itself runs.
F1 - the handler pool outlived the Crow app.

  handlerPool was declared BEFORE app, so ~APIServer destroyed the io
  contexts and connections before joining the workers, and stop() never
  touched the pool at all. A worker still mid-query at SIGTERM would finish,
  post to a destroyed io_service, then drop a keepalive holding a connection
  whose socket belonged to it.

  The pool's "drain, don't drop" promise was vacuous after app.stop(): no
  posted completion can run. shutdown() now happens BEFORE app.stop(), and
  the member is declared after app so destruction order is safe regardless.

F5 - completion was a code-path property, not a structural one.

  The job caught std::exception only. Anything else escaped to
  HandlerPool::run's catch(...), which logged and dropped it - so no
  completion was posted, and the connection was left held only by its own
  self-references with the read loop paused and the deadline timer
  cancelled. finish() never ran, the in-flight slot never cleared, and
  readiness reported 503 for the life of the process.

  An RAII Completer now posts something on every exit path, so "complete
  exactly once" holds by type rather than by remembering.

F11 - the io thread kept claiming a request after handing it away.

  t_current stayed set until the posted completion ran. Crow logs
  "Request:" for the NEXT connection on that thread before its before_handle
  runs, so those lines carried the offloaded request's id and trace id -
  mis-correlating exactly the logs this release advertises. Cleared right
  after a successful submit.

F6 - out-of-order OTel scope detach.

  SpanScope::Impl pushed a context scope on the io thread and popped it in
  finish(). While handlers ran inline that was strictly nested. With the
  offload, two requests on one io thread can finish in the other order, and
  a non-LIFO Detach fails: the token stays on the stack, later requests
  without a traceparent parent to an ended span, and each mismatched pair
  leaks a shared_ptr.

  The scope is now optional, and the offload path releases it immediately
  after submit while it is still innermost; the worker re-activates on its
  own thread. Inline paths are untouched.

Also: my own offload tests did not discriminate.

  The review found three of the four tests added with #137 would pass
  against the defect they claimed to pin. test_handler_offload.py said so in
  its own docstring - it used the shipped thread count, and on a many-core
  machine the condition never arises, so the pre-offload server passed it.

  FLAPI_IO_THREADS forces the minimum (one accept + one io thread) so the
  condition actually occurs, and a new test asserts requests ARE blocked
  with FLAPI_DISABLE_HANDLER_OFFLOAD=1 - so the others now demonstrably
  measure something.

757 unit tests, 377 standalone integration tests.
CI caught what I could not build locally: `include/crow/http_connection.h:195:
patch does not apply`.

Two mistakes, and the second is the one that mattered.

1. The patch was generated against the wrong source.

   I diffed the headers installed in vcpkg_installed/, which are crow 1.2.0.
   The port I copied from upstream fetches v1.3.0, where `self` is captured
   from an outer scope rather than re-acquired inside the `if (!res.completed_)`
   block - so my context did not match. The lifetime analysis holds in 1.3.0
   unchanged; only the patch context differed.

2. The port would have SILENTLY UPGRADED crow.

   I copied the upstream port wholesale, which declares 1.3.0. This project
   builds 1.2.0 - vcpkg.spdx.json in the installed tree says so. Adding a
   three-line patch would have carried a dependency minor-version bump with
   it, in a PR about request handling, with nobody asking for it and nothing
   testing the difference.

   The port is now pinned to the 1.2.0 tarball the project already builds,
   with the SHA512 of the tarball in the vcpkg download cache, so the patch
   is the only change.

Also dropped remove-cpm.patch, which came with the copied port: it targets
1.3.0's CMakeLists, and 1.2.0 has no CPM reference at all, so applying it
fails.

Verified against a pristine copy of the 1.2.0 source rather than against my
own tree: the patch applies cleanly, both files.

This is exactly the caveat I flagged on the PR - the overlay port cannot be
exercised locally because vcpkg has no network here, so CI is the first place
it runs. It was right to flag it and wrong to assume it would hold.
@jrosskopf

Copy link
Copy Markdown
Contributor Author

Superseded by #144, the v26.09.23 release candidate, which carries this work plus the fixes its integration CI was failing on. Closing in favour of that PR.

@jrosskopf jrosskopf closed this Sep 23, 2026
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.

Readiness can be blocked by the very stall it reports (Crow io-thread head-of-line blocking)

1 participant