From cd5cea4d28710023d1cc10bc5bef00943fbc628b Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 19 Aug 2026 14:27:40 +0100 Subject: [PATCH 1/8] fix(lib-rt-core): stop a handler that never answers from stalling its stream Credit and a place for its tag are consumed when an event is dispatched and returned when the handler answers, including when it answers late. Nothing accounted for a handler that never answers at all. The deadline cancels the event and stops the caller waiting, and the dispatcher was never told, so the place stayed consumed for the life of the process. A handler that hangs took a place with it every time, and a stream that lost enough of them dispatched nothing ever again. A cancellation now leaves the event five seconds to be answered and then takes the place back. That is not a claim the handler stopped, since nothing can make it stop. It says the runtime will no longer keep room for an answer it asked to be abandoned. Taking a place back makes two more rules necessary, both about an answer that arrives afterwards. A grant is dropped, since returning the same place twice would grow the window past what the handler declared. No grant is a handler withholding, which means the same however late it arrives, so the runtime undoes its own return rather than sending work to a handler that said it could take none. Separately, a tag with no declared limit could take the whole window and leave every other tag unable to dispatch, since credit is refused to all of them once it runs out. The tags that suffer most are the ones nothing else can stand in for, a connection's disconnect handler among them. Every tag now keeps a place, though never more than half the window, since a handler serving twenty tags on a window of eight cannot give each of them one, and capping all of them at a single event would cost whichever tag carries the traffic more than the starvation it avoids. The protocol carries all of this now, so an SDK author reading it alone learns that a cancelled event should still be answered and what happens when it is not. --- libs/runtime/core/src/consts.rs | 31 ++ libs/runtime/core/src/dispatcher.rs | 399 +++++++++++++++++- .../core/src/generated/celerity.runtime.v1.rs | 13 + .../proto/celerity/runtime/v1/runtime.proto | 13 + 4 files changed, 448 insertions(+), 8 deletions(-) diff --git a/libs/runtime/core/src/consts.rs b/libs/runtime/core/src/consts.rs index e130bb82..73a3cec4 100644 --- a/libs/runtime/core/src/consts.rs +++ b/libs/runtime/core/src/consts.rs @@ -127,6 +127,8 @@ pub const WS_CONNECTION_WORK_SHED_GRACE_MS: u64 = 1_000; // enough for work that is nearly done to land. pub const WS_CONNECTION_DRAIN_GRACE_MS: u64 = 5_000; +// How many of one connection's messages may be handled at the same time. +// // The `retryAfter` hint sent in the close frame when a connection is shed for // outrunning its handlers. // @@ -136,6 +138,35 @@ pub const WS_CONNECTION_DRAIN_GRACE_MS: u64 = 5_000; // their own jitter. pub const WS_CONNECTION_SATURATED_RETRY_AFTER_MS: u64 = 5_000; +// How long a cancelled event is left with its handler before the runtime takes +// back what it was holding. +// +// Credit and a per tag place are consumed when an event is dispatched and +// returned when the handler answers, including when it answers late. A handler +// that never answers would otherwise hold both for the life of the process, so +// a stream would lose a place every time one hung and would eventually stop +// dispatching altogether. +// +// Taking them back is not a statement that the handler stopped, since nothing +// can make it stop. It says the runtime will no longer keep room for an answer +// it asked to be abandoned. Long enough for a handler that honours a +// cancellation to unwind and answer, which is the case that should not be +// treated as a hang. +pub const HANDLER_CANCEL_RECLAIM_GRACE_SECS: u64 = 5; + +// How long the runtime remembers an event whose place it took back. +// +// A result carrying no credit is a handler withholding, asking for nothing +// further until it grants again. Arriving after the place was taken back, that +// asks for a place the runtime has already returned, so the return has to be +// undone or the handler is sent work it said it could not take. Remembering +// which events those were is what makes that possible. +// +// Bounded because a handler that never answers would otherwise be remembered +// for good, and generous because the answer being late is the whole reason +// there is anything to remember. +pub const HANDLER_RECLAIM_MEMORY_SECS: u64 = 60; + // How many dispatcher commands may be queued before a handler stream waits. // Commands are small and are drained by a single task, so this only needs to // absorb bursts of results arriving together. diff --git a/libs/runtime/core/src/dispatcher.rs b/libs/runtime/core/src/dispatcher.rs index 03af5bce..3c369848 100644 --- a/libs/runtime/core/src/dispatcher.rs +++ b/libs/runtime/core/src/dispatcher.rs @@ -34,7 +34,10 @@ use tokio::{ use tracing::{debug, info, warn}; use crate::{ - consts::{HANDLER_ATTACH_GRACE_SECS, MAX_DERIVED_DRAIN_TIMEOUT_SECS}, + consts::{ + HANDLER_ATTACH_GRACE_SECS, HANDLER_CANCEL_RECLAIM_GRACE_SECS, HANDLER_RECLAIM_MEMORY_SECS, + MAX_DERIVED_DRAIN_TIMEOUT_SECS, + }, event_queue::{EventQueueReceivers, HandlerTimeouts, InFlightEntry, InFlightTable}, types::{CancelReason, CancelRequest, EventData, EventOutcome, EventTuple, UnservableReason}, }; @@ -137,6 +140,11 @@ struct StreamState { tags: HashSet, credit: u32, limits: HashMap, + /// What a tag may hold when the handler declared no limit for it. + /// + /// Leaves room for every other tag to place one event, so no tag can take + /// the window and leave the rest of them unable to dispatch at all. + default_limit: u32, /// How many events are in flight to this stream, per tag. in_flight: HashMap, /// The events this stream is holding, by event id and the tag they were @@ -155,13 +163,40 @@ impl StreamState { if self.draining || self.credit == 0 || !self.tags.contains(handler_tag) { return false; } - match self.limits.get(handler_tag) { - Some(cap) => self.in_flight.get(handler_tag).copied().unwrap_or(0) < *cap, - None => true, - } + let cap = self + .limits + .get(handler_tag) + .copied() + .unwrap_or(self.default_limit); + self.in_flight.get(handler_tag).copied().unwrap_or(0) < cap } } +/// What a tag may hold when the handler declared no limit for it. +/// +/// A window is one per stream and is refused to every tag once it runs out, so +/// without this a single tag can take all of it and the others are not just slow, +/// they are stopped. That matters most for the tags nothing else can stand in +/// for. A connection's disconnect handler shares a window with the messages +/// that connection sent, and credit comes back only when a handler answers, so +/// handlers that never answer would otherwise leave the connection unable to +/// finish tearing down. +/// +/// Holds back a place for each of the other tags, but never more than half the +/// window. What is being bought is that no tag can take all of it, and a +/// handler serving many tags on a small window cannot give each of them a place +/// anyway. Without the halving, an application with twenty handlers and a window +/// of eight would cap every one of them at a single event, which is a worse +/// trade than the starvation it avoids for whichever handler carries the +/// traffic. +/// +/// A handler that wants a different split declares its own limits, which are +/// used as given. +fn default_tag_limit(credit: u32, tags: usize) -> u32 { + let held_back = (tags.saturating_sub(1) as u32).min(credit / 2); + credit.saturating_sub(held_back).max(1) +} + /// Runs the dispatch loop until shutdown. pub struct Dispatcher { /// One queue per handler tag. Ordered so that round-robin selection visits @@ -180,6 +215,25 @@ pub struct Dispatcher { /// Publishes whether any stream is attached, for readiness probes and for /// the startup deadline a supervising runtime applies. readiness: watch::Sender, + /// Events that have been cancelled and the moment the runtime stops keeping + /// room for an answer to them. + /// + /// Every entry is given the same grace period, so they are added in the order they + /// fall due and the earliest is always the front. + reclaims: VecDeque<(Instant, String)>, + /// How long a cancelled event is left with its handler before what it holds + /// is taken back. + reclaim_grace: Duration, + /// Events whose place has been taken back, kept so that a handler answering + /// late can still withhold the place rather than be sent more work. + /// + /// Ordered by when they stop being remembered, which is the same span for + /// each, so the earliest is always the front. + reclaimed: VecDeque<(Instant, String)>, + /// The same events, for looking one up when a late answer names it. + reclaimed_ids: HashSet, + /// How long a taken back event is remembered. Shortened by tests. + reclaim_memory: Duration, } /// Whether a handlers executable is attached and able to be given work. @@ -279,6 +333,11 @@ impl Dispatcher { timeouts, drain_timeout, readiness: watch::Sender::new(false), + reclaims: VecDeque::new(), + reclaim_grace: Duration::from_secs(HANDLER_CANCEL_RECLAIM_GRACE_SECS), + reclaimed: VecDeque::new(), + reclaimed_ids: HashSet::new(), + reclaim_memory: Duration::from_secs(HANDLER_RECLAIM_MEMORY_SECS), } } @@ -321,10 +380,20 @@ impl Dispatcher { // Recomputed each pass because attaching a stream can make a queue // servable again, and dispatching can empty one. let shed_at = self.next_shed_deadline(); + let reclaim_at = match (self.reclaims.front(), self.reclaimed.front()) { + (Some((due, _)), Some((forget, _))) => Some(*due.min(forget)), + (Some((due, _)), None) => Some(*due), + (None, Some((forget, _))) => Some(*forget), + (None, None) => None, + }; tokio::select! { _ = &mut shutdown_rx => break, _ = sleep_until_or_never(shed_at) => self.shed_unservable(), + _ = sleep_until_or_never(reclaim_at) => { + self.reclaim_abandoned(); + self.dispatch_ready().await; + } taken = events.recv() => match taken { Some((result_tx, event)) => { self.enqueue(QueuedEvent { @@ -376,6 +445,13 @@ impl Dispatcher { return; }; + // Whatever the handler does with the cancellation, the runtime stops + // keeping room for an answer to it once the grace period passes. A handler + // that honours it and answers releases what it holds the ordinary way, + // well within the grace period. + self.reclaims + .push_back((Instant::now() + self.reclaim_grace, event_id.clone())); + // A caller that went away leaves an entry nobody will ever read, so it // is released here rather than being held until its deadline, which // would also produce a second cancellation for the same event. A @@ -397,6 +473,61 @@ impl Dispatcher { } } + /// Takes back what cancelled events are still holding, once the grace period for + /// answering has passed. + /// + /// An event the handler answered in time is already gone from `holders`, so + /// what is left here is what nothing came back for. Doing this is what + /// keeps a handler that ignores cancellation from shrinking its stream's + /// window one event at a time until it dispatches nothing at all. + fn reclaim_abandoned(&mut self) { + let now = Instant::now(); + while self + .reclaims + .front() + .is_some_and(|(due_at, _)| *due_at <= now) + { + let Some((_, event_id)) = self.reclaims.pop_front() else { + break; + }; + let Some(stream_id) = self.holders.remove(&event_id) else { + continue; + }; + let Some(stream) = self.streams.get_mut(&stream_id) else { + continue; + }; + let Some(handler_tag) = stream.holding.remove(&event_id) else { + continue; + }; + if let Some(count) = stream.in_flight.get_mut(&handler_tag) { + *count = count.saturating_sub(1); + } + stream.credit = stream.credit.saturating_add(1); + warn!( + stream_id, + %event_id, + %handler_tag, + "no answer to a cancelled event within the grace, taking back the place \ + it was holding" + ); + // Remembered so that an answer arriving later can still withhold + // the place, which is the handler saying it cannot take more. + self.reclaimed + .push_back((now + self.reclaim_memory, event_id.clone())); + self.reclaimed_ids.insert(event_id); + } + + while self + .reclaimed + .front() + .is_some_and(|(forget_at, _)| *forget_at <= now) + { + if let Some((_, event_id)) = self.reclaimed.pop_front() { + self.reclaimed_ids.remove(&event_id); + } + } + } + /// Stops dispatching, tells attached streams to finish, and waits for what /// is already in flight. /// @@ -492,12 +623,15 @@ impl Dispatcher { throughput will be bounded by the buffer" ); } + let tags: HashSet = registration.handler_tags.into_iter().collect(); + let default_limit = default_tag_limit(registration.initial_credit, tags.len()); self.streams.insert( stream_id, StreamState { - tags: registration.handler_tags.into_iter().collect(), + tags, credit: registration.initial_credit, limits: registration.limits, + default_limit, in_flight: HashMap::new(), holding: HashMap::new(), draining: false, @@ -526,13 +660,26 @@ impl Dispatcher { credit_grant, } => { self.holders.remove(&event_id); + let taken_back = self.reclaimed_ids.remove(&event_id); if let Some(stream) = self.streams.get_mut(&stream_id) { if let Some(handler_tag) = stream.holding.remove(&event_id) { if let Some(count) = stream.in_flight.get_mut(&handler_tag) { *count = count.saturating_sub(1); } + stream.credit = stream.credit.saturating_add(credit_grant); + } else if taken_back && credit_grant == 0 { + // The place is already back, so a grant would grow the + // window past what the handler declared and is dropped. + // No grant is a handler withholding though, and it means + // the same whenever it arrives, so the place goes back + // to the handler's account rather than the runtime's. + stream.credit = stream.credit.saturating_sub(1); + debug!( + stream_id, + %event_id, + "a late answer withheld the place that was taken back" + ); } - stream.credit = stream.credit.saturating_add(credit_grant); } } DispatcherCommand::Grant { @@ -879,7 +1026,10 @@ mod tests { let (command_tx, command_rx) = mpsc::channel(16); let (shutdown_tx, shutdown_rx) = oneshot::channel(); - let dispatcher = Dispatcher::new(handles.in_flight.clone(), timeouts(), drain_timeout); + let mut dispatcher = Dispatcher::new(handles.in_flight.clone(), timeouts(), drain_timeout); + // The real grace is measured in seconds, which no test can wait out. + dispatcher.reclaim_grace = Duration::from_millis(100); + dispatcher.reclaim_memory = Duration::from_secs(30); let readiness = dispatcher.readiness(); tokio::spawn(dispatcher.run(receivers, command_rx, shutdown_rx)); @@ -1586,4 +1736,237 @@ mod tests { assert!(!attached); } + + /// Every tag keeps a place, so no tag can take the window and leave the + /// others unable to dispatch at all. + #[test] + fn a_tag_is_held_back_from_taking_the_whole_window() { + assert_eq!(default_tag_limit(8, 3), 6); + assert_eq!(default_tag_limit(8, 2), 7); + } + + /// Nothing to starve, so nothing is held back. + #[test] + fn a_stream_serving_one_tag_gives_it_everything() { + assert_eq!(default_tag_limit(8, 1), 8); + } + + /// More tags than credit cannot leave a place for each, so every tag gets + /// one and the window itself is what turns them away. + #[test] + fn a_window_too_small_to_share_still_lets_every_tag_try() { + assert_eq!(default_tag_limit(2, 5), 1); + assert_eq!(default_tag_limit(0, 3), 1); + } + + /// Many handlers on a small window would otherwise cap each of them at a + /// single event, which costs whichever one carries the traffic far more + /// than the starvation it avoids. + #[test] + fn a_stream_serving_many_tags_still_keeps_half_the_window_for_one() { + assert_eq!(default_tag_limit(8, 20), 4); + assert_eq!(default_tag_limit(64, 100), 32); + } + + /// A handler that never answers a cancellation does not keep what it was + /// holding. + /// + /// Credit and a per tag place come back when a handler answers, so a + /// handler that ignores a cancellation would otherwise leave a stream one + /// place smaller for good, and enough of them would stop it dispatching + /// anything at all. + #[tokio::test] + async fn takes_back_what_a_cancelled_event_was_holding_when_nothing_answers() { + let harness = start(32); + // One place, so what happens to it is the whole of what this observes. + let mut stream = attach(&harness, 1, &["work"], 1, HashMap::new()).await; + + harness + .queue + .enqueue( + event("event-1", "work"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + let dispatched = recv_dispatch(&mut stream) + .await + .expect("the first event should be dispatched"); + assert_eq!(dispatched.event.id, "event-1"); + + harness + .queue + .enqueue( + event("event-2", "work"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + assert!( + recv_dispatch(&mut stream).await.is_none(), + "the window is held by the first event, so the second should wait" + ); + + // The caller has gone. The handler is told to stop and never answers, + // which is what a hung or crashed handler looks like from here. + drop(harness.queue.cancel_on_drop("event-1".to_string())); + match recv(&mut stream).await { + Some(StreamFrame::Cancel { event_id, .. }) => assert_eq!(event_id, "event-1"), + other => panic!("expected a cancellation, got {other:?}"), + } + + tokio::time::sleep(Duration::from_millis(250)).await; + + let second = recv_dispatch(&mut stream) + .await + .expect("the place the cancelled event held should have come back"); + assert_eq!(second.event.id, "event-2"); + } + + /// An answer that arrives after the runtime gave up waiting does not put a + /// place back that has already been taken back. + /// + /// The handler declares its own limits here, generously, so that credit is + /// the only thing bounding what can be in flight. Without that the per tag + /// limit hides an inflated window rather than the test finding it. + #[tokio::test] + async fn does_not_credit_an_answer_that_comes_after_the_place_was_taken_back() { + let harness = start(32); + let mut stream = attach( + &harness, + 1, + &["work"], + 2, + HashMap::from([("work".to_string(), 10)]), + ) + .await; + + for index in 0..2 { + harness + .queue + .enqueue( + event(&format!("held-{index}"), "work"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + for _ in 0..2 { + recv_dispatch(&mut stream) + .await + .expect("both events should be dispatched, which is the whole window"); + } + + drop(harness.queue.cancel_on_drop("held-0".to_string())); + match recv(&mut stream).await { + Some(StreamFrame::Cancel { .. }) => {} + other => panic!("expected a cancellation, got {other:?}"), + } + tokio::time::sleep(Duration::from_millis(250)).await; + + // The handler answers late, returning the credit it believes it still + // holds. That place is already back, so this must add nothing. + harness + .commands + .send(DispatcherCommand::Completed { + stream_id: 1, + event_id: "held-0".to_string(), + credit_grant: 1, + }) + .await + .unwrap(); + + for index in 0..2 { + harness + .queue + .enqueue( + event(&format!("later-{index}"), "work"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + + assert!( + recv_dispatch(&mut stream).await.is_some(), + "the place the cancelled event held should have come back" + ); + assert!( + recv_dispatch(&mut stream).await.is_none(), + "a late answer should not grow the window past what the handler declared" + ); + } + + /// A handler answering late with no credit is still withholding, and the + /// place the runtime took back on its behalf goes back to it. + /// + /// No credit on a result means stop dispatching until a later grant. The + /// runtime returned that place when nothing answered in time, so honouring + /// the withhold means undoing its own return rather than ignoring what the + /// handler asked for and sending it work it said it could not take. + #[tokio::test] + async fn honours_a_withhold_that_arrives_after_the_place_was_taken_back() { + let harness = start(32); + let mut stream = attach( + &harness, + 1, + &["work"], + 2, + HashMap::from([("work".to_string(), 10)]), + ) + .await; + + for index in 0..2 { + harness + .queue + .enqueue( + event(&format!("held-{index}"), "work"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + for _ in 0..2 { + recv_dispatch(&mut stream) + .await + .expect("both events should be dispatched, which is the whole window"); + } + + drop(harness.queue.cancel_on_drop("held-0".to_string())); + match recv(&mut stream).await { + Some(StreamFrame::Cancel { .. }) => {} + other => panic!("expected a cancellation, got {other:?}"), + } + tokio::time::sleep(Duration::from_millis(250)).await; + + // Late, and withholding. The place the runtime returned is the one the + // handler is saying it does not want. + harness + .commands + .send(DispatcherCommand::Completed { + stream_id: 1, + event_id: "held-0".to_string(), + credit_grant: 0, + }) + .await + .unwrap(); + // Waited for rather than raced. A withhold governs what is dispatched + // after it is read, and work already waiting when the place came back + // may have gone out before it arrived, which is what being late costs. + tokio::time::sleep(Duration::from_millis(100)).await; + + harness + .queue + .enqueue( + event("later-0", "work"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + + assert!( + recv_dispatch(&mut stream).await.is_none(), + "a handler that withheld should not be sent more work, however late it said so" + ); + } } diff --git a/libs/runtime/core/src/generated/celerity.runtime.v1.rs b/libs/runtime/core/src/generated/celerity.runtime.v1.rs index 9c720863..332c51dd 100644 --- a/libs/runtime/core/src/generated/celerity.runtime.v1.rs +++ b/libs/runtime/core/src/generated/celerity.runtime.v1.rs @@ -157,6 +157,14 @@ pub mod dispatch { /// /// May arrive for an event that has already completed, which handlers must /// ignore rather than treat as an error. +/// +/// A cancelled event should still be answered with a Result, which is what +/// returns the place it holds in the credit window. The runtime waits a short +/// grace period and then takes that place back itself, since a handler that has hung or +/// died would otherwise shrink the window for the life of the process. That is +/// not a claim that the handler stopped, only that the runtime will no longer keep +/// room for an answer it asked to be abandoned, a handler that answers +/// promptly never meets it. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct Cancel { #[prost(string, tag = "1")] @@ -357,6 +365,11 @@ pub struct Result { /// to stop dispatching to this stream until a later CreditGrant. SDKs should /// default to 1 and must send this even when the handler panics, since a /// missed grant drains the window and stalls the stream silently. + /// + /// When the runtime has already taken the place back, having cancelled the + /// event and waited out the grace period, a grant here is ignored, since + /// returning the same place twice would grow the window. Zero still withholds, + /// and the runtime gives up the place it returned. #[prost(uint32, tag = "2")] pub credit_grant: u32, #[prost(oneof = "result::Outcome", tags = "10, 11, 12, 13, 14, 15")] diff --git a/libs/runtime/proto/celerity/runtime/v1/runtime.proto b/libs/runtime/proto/celerity/runtime/v1/runtime.proto index 02c3fd8f..99aab0d3 100644 --- a/libs/runtime/proto/celerity/runtime/v1/runtime.proto +++ b/libs/runtime/proto/celerity/runtime/v1/runtime.proto @@ -118,6 +118,14 @@ message Dispatch { // // May arrive for an event that has already completed, which handlers must // ignore rather than treat as an error. +// +// A cancelled event should still be answered with a Result, which is what +// returns the place it holds in the credit window. The runtime waits a short +// grace period and then takes that place back itself, since a handler that has hung or +// died would otherwise shrink the window for the life of the process. That is +// not a claim that the handler stopped, only that the runtime will no longer keep +// room for an answer it asked to be abandoned, a handler that answers +// promptly never meets it. message Cancel { string id = 1; @@ -242,6 +250,11 @@ message Result { // to stop dispatching to this stream until a later CreditGrant. SDKs should // default to 1 and must send this even when the handler panics, since a // missed grant drains the window and stalls the stream silently. + // + // When the runtime has already taken the place back, having cancelled the + // event and waited out the grace period, a grant here is ignored, since + // returning the same place twice would grow the window. Zero still withholds, + // and the runtime gives up the place it returned. uint32 credit_grant = 2; oneof outcome { From 2c63a454b90b3f5f26544f8d8828f5fb4340eac6 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 19 Aug 2026 14:28:00 +0100 Subject: [PATCH 2/8] feat(lib-rt-core): handle a connection's messages beside each other A connection's messages were handled one at a time, which made this the only target that puts them in a queue. The same API deploys here or to a serverless gateway that runs a function per message with nothing between them, so an application built against the order it found here would carry a dependency it cannot see until it is deployed somewhere that does not honour it. Eight at a time now, and one for a deployment whose messages have to be handled in the order they arrived, through CELERITY_WS_HANDLER_CONCURRENCY. Eight rather than any other number is a judgement rather than something the serverless target implies, since a function per message is bounded by an account's concurrency rather than by anything this small. It is enough that a connection waiting on a handler is not serialised behind itself, and few enough to leave a handler's credit window worth sharing between connections. A close is settled where it lands rather than beside the messages it follows, so the disconnect handler still runs after them however many were in flight, which is what the teardown already promised in writing. This waited on credit accounting. A connection that could hold several places at once could take a stream's whole window, and the disconnect handler shares that window with the messages that consumed it, so raising this earlier would have left a connection unable to finish tearing down. --- libs/runtime/core/src/application.rs | 6 +- libs/runtime/core/src/config.rs | 50 ++++++ libs/runtime/core/src/consts.rs | 13 ++ libs/runtime/core/src/transform_config.rs | 1 + libs/runtime/core/src/websocket.rs | 77 ++++++-- libs/runtime/core/tests/ipc_websocket_test.rs | 169 ++++++++++++++++++ 6 files changed, 296 insertions(+), 20 deletions(-) diff --git a/libs/runtime/core/src/application.rs b/libs/runtime/core/src/application.rs index c8b50a32..0fdc43b6 100644 --- a/libs/runtime/core/src/application.rs +++ b/libs/runtime/core/src/application.rs @@ -54,7 +54,7 @@ use crate::{ }, consts::{ DEFAULT_EVENT_QUEUE_CAPACITY, DEFAULT_RUNTIME_HEALTH_CHECK_ENDPOINT, - DISPATCHER_COMMAND_BUFFER, + DISPATCHER_COMMAND_BUFFER, WS_CONNECTION_DEFAULT_HANDLER_CONCURRENCY, }, consumer_handler::{ ConsumerEventHandler, EventQueueConsumerEventHandler, SharedConsumerEventHandler, @@ -444,6 +444,10 @@ impl Application { .map(|_| websocket_config.auth_strategy.clone()), connection_auth_guard_names: websocket_config.connection_auth_guard.clone(), connection_auth_guards: self.custom_auth_guards.clone(), + handler_concurrency: self + .runtime_config + .ws_handler_concurrency + .unwrap_or(WS_CONNECTION_DEFAULT_HANDLER_CONCURRENCY), cors: api_config.cors.clone(), resource_store: resource_store.clone(), }), diff --git a/libs/runtime/core/src/config.rs b/libs/runtime/core/src/config.rs index df5b387a..0ff22012 100644 --- a/libs/runtime/core/src/config.rs +++ b/libs/runtime/core/src/config.rs @@ -194,6 +194,14 @@ pub struct RuntimeConfig { /// for the suggested default the WebSocket runtime protocol names, which is 3. /// Set via `CELERITY_WS_ACK_MAX_ATTEMPTS`. pub ws_ack_max_attempts: Option, + /// How many of one connection's messages may be handled at the same time. + /// + /// Leave unset for eight. Set it to one for a connection whose messages have + /// to be handled in the order they arrived, at the cost of capping the + /// connection at one handler's worth of latency per message. Bounds one + /// connection rather than the process. + /// Set via `CELERITY_WS_HANDLER_CONCURRENCY`. + pub ws_handler_concurrency: Option, } impl RuntimeConfig { @@ -363,6 +371,7 @@ impl RuntimeConfig { let ws_ack_timeout_ms = ws_ack_timeout_ms_from_env(env); let ws_ack_max_attempts = ws_ack_max_attempts_from_env(env); + let ws_handler_concurrency = ws_handler_concurrency_from_env(env); RuntimeConfig { blueprint_config_path, @@ -393,6 +402,7 @@ impl RuntimeConfig { deploy_target, ws_ack_timeout_ms, ws_ack_max_attempts, + ws_handler_concurrency, } } @@ -450,6 +460,23 @@ pub fn ws_ack_max_attempts_from_env(env: &impl EnvVars) -> Option { }) } +/// Reads how many of a connection's messages may be handled at the same time. +/// +/// See [`ws_ack_timeout_ms_from_env`] for why this is not only read in +/// [`RuntimeConfig::from_env`]. +pub fn ws_handler_concurrency_from_env(env: &impl EnvVars) -> Option { + env.var("CELERITY_WS_HANDLER_CONCURRENCY").ok().map(|val| { + let concurrency: usize = val + .parse() + .expect("Invalid WebSocket handler concurrency, must be a whole number"); + assert!( + concurrency > 0, + "Invalid WebSocket handler concurrency, a connection has to handle one message at a time at the least" + ); + concurrency + }) +} + #[derive(Debug)] pub struct AppConfig { pub api: Option, @@ -857,4 +884,27 @@ mod tests { fn test_an_ack_timeout_that_is_not_a_number_is_refused() { RuntimeConfig::from_env(&env(&[("CELERITY_WS_ACK_TIMEOUT_MS", "ten seconds")])); } + + #[test] + fn test_handler_concurrency_is_left_to_the_runtime_when_unset() { + assert_eq!( + RuntimeConfig::from_env(&env(&[])).ws_handler_concurrency, + None + ); + } + + #[test] + fn test_handler_concurrency_is_read_from_the_environment() { + let config = RuntimeConfig::from_env(&env(&[("CELERITY_WS_HANDLER_CONCURRENCY", "8")])); + + assert_eq!(config.ws_handler_concurrency, Some(8)); + } + + /// Nothing at all would leave a connection unable to handle anything, + /// rather than meaning handle nothing in parallel. + #[test] + #[should_panic(expected = "one message at a time")] + fn test_no_handler_concurrency_at_all_is_refused() { + RuntimeConfig::from_env(&env(&[("CELERITY_WS_HANDLER_CONCURRENCY", "0")])); + } } diff --git a/libs/runtime/core/src/consts.rs b/libs/runtime/core/src/consts.rs index 73a3cec4..d8c58750 100644 --- a/libs/runtime/core/src/consts.rs +++ b/libs/runtime/core/src/consts.rs @@ -129,6 +129,19 @@ pub const WS_CONNECTION_DRAIN_GRACE_MS: u64 = 5_000; // How many of one connection's messages may be handled at the same time. // +// More than one, because the same API deploys here or to a serverless gateway, +// which runs a function per message with nothing between them. Handling one at +// a time would make this the only target that puts a connection's messages in a +// queue, and an application built against that would carry an ordering +// dependency it cannot see until it is deployed somewhere that does not honour +// it. A deployment that needs them in order asks for one. +// +// Bounds one connection rather than the process. What bounds the process is the +// credit a handler grants its stream, and what stops a connection's messages +// taking all of that is the default per tag limit, which keeps a place for the +// tags nothing else can stand in for, the disconnect handler among them. +pub const WS_CONNECTION_DEFAULT_HANDLER_CONCURRENCY: usize = 8; + // The `retryAfter` hint sent in the close frame when a connection is shed for // outrunning its handlers. // diff --git a/libs/runtime/core/src/transform_config.rs b/libs/runtime/core/src/transform_config.rs index 2b2850a4..ed791bf3 100644 --- a/libs/runtime/core/src/transform_config.rs +++ b/libs/runtime/core/src/transform_config.rs @@ -1496,6 +1496,7 @@ mod tests { deploy_target: None, ws_ack_timeout_ms: None, ws_ack_max_attempts: None, + ws_handler_concurrency: None, } } diff --git a/libs/runtime/core/src/websocket.rs b/libs/runtime/core/src/websocket.rs index 175fc03b..6d60a545 100644 --- a/libs/runtime/core/src/websocket.rs +++ b/libs/runtime/core/src/websocket.rs @@ -36,7 +36,7 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use tokio::{ sync::{mpsc, mpsc::error::SendTimeoutError, Mutex}, - task::JoinHandle, + task::{JoinHandle, JoinSet}, }; use tracing::{debug, error, field, info, info_span, warn, Instrument}; @@ -78,6 +78,8 @@ pub(crate) struct WebSocketAppState { pub connection_auth_guard_names: Option>, pub connection_auth_guards: Arc>>>, + // How many of this connection's messages may be handled at the same time. + pub handler_concurrency: usize, pub cors: Option, pub resource_store: Arc, // What the node has already seen from its clients, so a message resent @@ -367,14 +369,11 @@ async fn handle_socket( return; } - // Messages are processed off this loop, one at a time, by a worker for - // this connection. One at a time because that is how they were handled - // before, inline in this loop, and a fix for the loop stalling should - // not quietly start running an application's messages in parallel. - // Ordering is not something the platform promises, a serverless target - // runs a function per message with nothing between them, so this is - // about leaving behaviour alone rather than a guarantee being made. - // The point here is only that reading no longer waits for handling. + // Messages are processed off this loop by a worker for this + // connection, several at a time unless the deployment asks for one. The + // protocol promises nothing about ordering and a serverless target runs + // a function per message with nothing between them, so handling them in + // order here would be a guarantee only this target could keep. // // Bounded, so a client that outruns its handlers is pushed back on // rather than growing a queue without limit. Once the buffer is full @@ -388,6 +387,7 @@ async fn handle_socket( socket_ref.clone(), connection_id.clone(), state.clone(), + state.handler_concurrency, ); let mut connection_alive = true; @@ -725,26 +725,65 @@ fn create_connect_message( } } -/// Runs a connection's messages, one at a time, off its read loop. +/// Runs a connection's messages off its read loop, up to `concurrency` of them +/// at a time. +/// +/// A close is settled here rather than alongside the messages it follows, so +/// the connection ends after them however many were in flight. fn spawn_message_worker( mut work_rx: mpsc::Receiver<(Message, Option, WebSocketRequestContext)>, socket_ref: Arc>, connection_id: String, state: WebSocketAppState, + concurrency: usize, ) -> JoinHandle<()> { tokio::spawn(async move { + let mut in_flight = JoinSet::new(); + while let Some((message, parsed, request_ctx)) = work_rx.recv().await { - if process_message(message, parsed, connection_id.clone(), request_ctx, &state) - .await - .is_break() - { - // The connection is finished, and the read loop is waiting on a - // socket that may never produce anything again. Closing it is - // what wakes the loop so the connection can be torn down. - close_connection(socket_ref.clone()).await; - return; + // Only an application message is worth running beside another. A + // close ends the connection and the rest carry no handler, so they + // wait for what came before them and are settled here. At a + // concurrency of one nothing is ever in flight and this is the only + // path, which is what keeps the default exactly as it was. + let alongside_others = + concurrency > 1 && matches!(message, Message::Text(_) | Message::Binary(_)); + + if !alongside_others { + while in_flight.join_next().await.is_some() {} + if process_message(message, parsed, connection_id.clone(), request_ctx, &state) + .await + .is_break() + { + // The connection is finished, and the read loop is waiting on a + // socket that may never produce anything again. Closing it is + // what wakes the loop so the connection can be torn down. + close_connection(socket_ref.clone()).await; + return; + } + continue; + } + + // Waits for room rather than queueing behind it, so the buffer the + // read loop pushes back on stays the one thing bounding how far a + // client can run ahead. + while in_flight.len() >= concurrency { + in_flight.join_next().await; } + + let connection_id = connection_id.clone(); + let state = state.clone(); + in_flight.spawn(async move { + // Only a close asks for the connection to end, and a close is + // never spawned, so there is no outcome to read here. + let _ = process_message(message, parsed, connection_id, request_ctx, &state).await; + }); } + + // The read loop has finished with this connection. What is still + // running is left to finish, since teardown waits on this task and + // bounds that wait itself. + while in_flight.join_next().await.is_some() {} }) } diff --git a/libs/runtime/core/tests/ipc_websocket_test.rs b/libs/runtime/core/tests/ipc_websocket_test.rs index 24054dd2..324c3ec0 100644 --- a/libs/runtime/core/tests/ipc_websocket_test.rs +++ b/libs/runtime/core/tests/ipc_websocket_test.rs @@ -1284,6 +1284,175 @@ async fn settles_a_message_acknowledged_with_an_escaped_event_name() { let _ = tokio::fs::remove_file(&socket).await; } +/// A connection handles its messages beside each other unless it is asked for +/// one at a time. +/// +/// The handler is left holding the first message, never answering it, so the +/// second can only reach it if something is running the two side by side. +/// Paired with the test below, which is the same run asking for order, so what +/// each proves is read against the other. +#[test_log::test(tokio::test)] +async fn handles_messages_beside_each_other_by_default() { + let dispatched = dispatches_seen_while_the_first_is_held("ipc-ws-concurrent", &[]).await; + + assert_eq!( + dispatched, 2, + "a second message should not wait for a handler that is still going" + ); +} + +/// The order a serverless target cannot give, for an application that needs it +/// and accepts being capped at one handler's worth of latency per message. +#[test_log::test(tokio::test)] +async fn handles_one_message_at_a_time_when_asked_to() { + let dispatched = dispatches_seen_while_the_first_is_held( + "ipc-ws-serial", + &[("CELERITY_WS_HANDLER_CONCURRENCY", "1")], + ) + .await; + + assert_eq!( + dispatched, 1, + "a second message should wait for the first when order was asked for" + ); +} + +/// Sends two messages to a handler that never answers, and reports how many of +/// them reached it. +/// +/// The handler holding the first is what makes the count mean something. An +/// answer would free the worker and both would arrive whatever the concurrency. +async fn dispatches_seen_while_the_first_is_held( + name: &str, + overrides: &[(&'static str, &str)], +) -> usize { + let socket = socket_path(name); + let env_vars = ipc_env( + name, + "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", + &socket, + overrides, + ); + let runtime_config = RuntimeConfig::from_env(&env_vars); + let mut app = Application::new(runtime_config, Box::new(env_vars)); + app.setup().unwrap(); + let addr = app.run(false).await.unwrap().http_server_address.unwrap(); + + // Never answered, so the runtime is still waiting on the first message when + // the second arrives. + let mut handler = HandlerStub::attach(&socket, |_| None).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + + for text in ["first", "second"] { + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "text": text } }).to_string(), + )) + .await + .unwrap(); + } + + let mut dispatched = 0; + while tokio::time::timeout(Duration::from_secs(2), handler.next_dispatch()) + .await + .ok() + .flatten() + .is_some() + { + dispatched += 1; + } + + let _ = socket_conn.close(None).await; + let _ = tokio::fs::remove_file(&socket).await; + dispatched +} + +/// A connection can be left unable to finish tearing down by work other +/// connections are holding. +/// +/// Credit is one window per handler stream, refused to every tag once it runs +/// out, and it comes back only when a handler answers. Handlers that never +/// answer therefore take the window away permanently, and the disconnect +/// handler is dispatched through the same window as the messages that consumed +/// it. Each connection here holds a single message, which is all the current +/// default allows, so this is reachable without any concurrency being raised. +#[test_log::test(tokio::test)] +async fn tears_a_connection_down_while_other_connections_hold_the_credit() { + let socket = socket_path("ipc-ws-credit-starve"); + let env_vars = ipc_env( + "ipc-ws-credit-starve", + "tests/data/fixtures/ipc-websocket-disconnect.blueprint.yaml", + &socket, + &[], + ); + let runtime_config = RuntimeConfig::from_env(&env_vars); + let mut app = Application::new(runtime_config, Box::new(env_vars)); + app.setup().unwrap(); + let addr = app.run(false).await.unwrap().http_server_address.unwrap(); + + // Never answered, and a cancel is ignored the way a hung handler would. + let mut handler = HandlerStub::attach(&socket, |_| None).await; + + // As many connections as the stream has credit, each holding one message. + let mut connections = Vec::new(); + for _ in 0..8 { + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "text": "hold" } }).to_string(), + )) + .await + .unwrap(); + connections.push(socket_conn); + } + + // Taken until they stop coming rather than counted, since how many reach + // the handler at once is the cap's business and not this test's. + let mut held = 0; + while tokio::time::timeout(Duration::from_secs(2), handler.next_dispatch()) + .await + .ok() + .flatten() + .is_some() + { + held += 1; + } + assert!( + held > 0, + "the connections should have reached the handler at all" + ); + + // Whatever reached the handler is now held by work that will never answer. + let mut closing = connections.pop().unwrap(); + let _ = closing.close(None).await; + + let disconnected = tokio::time::timeout(Duration::from_secs(10), async { + while let Some(dispatch) = handler.next_dispatch().await { + if let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source { + if message.route == "$disconnect" { + return true; + } + } + } + false + }) + .await; + + assert_eq!( + disconnected, + Ok(true), + "a connection that has gone should still run its disconnect handler, or it stays \ + in the registry and counted for the life of the process" + ); + + let _ = tokio::fs::remove_file(&socket).await; +} + /// A guard that lets any non-empty token through, since what is under test is /// what the runtime says once a guard has passed rather than how it decides. #[derive(Debug)] From bf1838450360b86db19eaaa45061592cd44c60eb Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 19 Aug 2026 14:28:13 +0100 Subject: [PATCH 3/8] fix(lib-rt-sdk-ffi): carry the handler concurrency through to the runtime An application started over the FFI boundary builds its own runtime configuration, so a deployment asking for a different number of messages in flight per connection would have been given the default whatever it set. Read the way the deploy target and the acknowledgement timings are, from the process environment at the point the configuration is built, rather than added to the configuration the caller passes in. --- libs/runtime/sdk/bindgen-ffi/src/application.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libs/runtime/sdk/bindgen-ffi/src/application.rs b/libs/runtime/sdk/bindgen-ffi/src/application.rs index fb7bdd7a..34fdb2e9 100644 --- a/libs/runtime/sdk/bindgen-ffi/src/application.rs +++ b/libs/runtime/sdk/bindgen-ffi/src/application.rs @@ -8,7 +8,8 @@ use celerity_helpers::{ use celerity_runtime_core::{ application::Application as RuntimeApp, config::{ - ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ClientIpSource, RuntimeConfig, + ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ws_handler_concurrency_from_env, + ClientIpSource, RuntimeConfig, }, errors::{ApplicationStartError, ConfigError}, }; @@ -69,6 +70,7 @@ pub unsafe fn application_create(core_runtime_config: CoreRuntimeConfig) -> *mut deploy_target: std::env::var("CELERITY_DEPLOY_TARGET").ok(), ws_ack_timeout_ms: ws_ack_timeout_ms_from_env(&ProcessEnvVars::new()), ws_ack_max_attempts: ws_ack_max_attempts_from_env(&ProcessEnvVars::new()), + ws_handler_concurrency: ws_handler_concurrency_from_env(&ProcessEnvVars::new()), }, Box::new(ProcessEnvVars::new()), ), From 5cf002a78e0937c2f0d440451d78f3f646d0fbe4 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 19 Aug 2026 14:28:15 +0100 Subject: [PATCH 4/8] fix(lib-rt-sdk-node): carry the handler concurrency through to the runtime The Node SDK rebuilds a runtime configuration from the one it is handed, so a deployment asking for a different number of messages in flight per connection would have been given the default whatever its environment set. Read the way the deploy target and the acknowledgement timings are, from the process environment at the point the configuration is rebuilt, so the same variable works whichever way the runtime is started. --- libs/runtime/sdk/node/src/lib.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/libs/runtime/sdk/node/src/lib.rs b/libs/runtime/sdk/node/src/lib.rs index d9a9ac26..b891372d 100644 --- a/libs/runtime/sdk/node/src/lib.rs +++ b/libs/runtime/sdk/node/src/lib.rs @@ -30,11 +30,11 @@ use celerity_runtime_core::{ auth_custom::{AuthGuardHandler, AuthGuardValidateError, AuthGuardValidateInput}, auth_http::AuthContext, config::{ - ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ApiConfig, AppConfig, ClientIpSource, - ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, CustomHandlersConfig, EventConfig, - EventHandlerDefinition, EventsConfig, GuardHandlerDefinition, GuardsConfig, HttpConfig, - HttpHandlerDefinition, RuntimeConfig, ScheduleConfig, SchedulesConfig, WebSocketConfig, - WebSocketHandlerDefinition, + ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ws_handler_concurrency_from_env, + ApiConfig, AppConfig, ClientIpSource, ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, + CustomHandlersConfig, EventConfig, EventHandlerDefinition, EventsConfig, + GuardHandlerDefinition, GuardsConfig, HttpConfig, HttpHandlerDefinition, RuntimeConfig, + ScheduleConfig, SchedulesConfig, WebSocketConfig, WebSocketHandlerDefinition, }, consts::{ DEFAULT_RESOURCE_STORE_CACHE_ENTRY_TTL, DEFAULT_RESOURCE_STORE_CLEANUP_INTERVAL, @@ -1333,6 +1333,7 @@ impl CoreRuntimeApplication { deploy_target: std::env::var("CELERITY_DEPLOY_TARGET").ok(), ws_ack_timeout_ms: ws_ack_timeout_ms_from_env(&ProcessEnvVars::new()), ws_ack_max_attempts: ws_ack_max_attempts_from_env(&ProcessEnvVars::new()), + ws_handler_concurrency: ws_handler_concurrency_from_env(&ProcessEnvVars::new()), }; let inner = Application::new(native_runtime_config, Box::new(ProcessEnvVars::new())); CoreRuntimeApplication { From dabd83b7b0c6362b5f239179541d3004109c1398 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 19 Aug 2026 14:28:17 +0100 Subject: [PATCH 5/8] fix(lib-rt-sdk-python): carry the handler concurrency through to the runtime The Python SDK rebuilds a runtime configuration from the one it is handed, so a deployment asking for a different number of messages in flight per connection would have been given the default whatever its environment set. Read the way the deploy target and the acknowledgement timings are, from the process environment at the point the configuration is rebuilt, so the same variable works whichever way the runtime is started. --- libs/runtime/sdk/python/src/lib.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/libs/runtime/sdk/python/src/lib.rs b/libs/runtime/sdk/python/src/lib.rs index e1c93d14..30c2bbf2 100644 --- a/libs/runtime/sdk/python/src/lib.rs +++ b/libs/runtime/sdk/python/src/lib.rs @@ -25,10 +25,10 @@ use celerity_runtime_core::{ application::Application, auth_http::AuthContext, config::{ - ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ApiConfig, AppConfig, ClientIpSource, - ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, CustomHandlersConfig, EventConfig, - EventHandlerDefinition, EventsConfig, GuardHandlerDefinition, GuardsConfig, RuntimeConfig, - ScheduleConfig, SchedulesConfig, + ws_ack_max_attempts_from_env, ws_ack_timeout_ms_from_env, ws_handler_concurrency_from_env, + ApiConfig, AppConfig, ClientIpSource, ConsumerConfig, ConsumersConfig, CustomHandlerDefinition, + CustomHandlersConfig, EventConfig, EventHandlerDefinition, EventsConfig, + GuardHandlerDefinition, GuardsConfig, RuntimeConfig, ScheduleConfig, SchedulesConfig, }, request::{MatchedRoute, RequestId, ResolvedClientIp, ResolvedUserAgent}, telemetry_utils::extract_trace_context, @@ -514,6 +514,7 @@ impl CoreRuntimeApplication { deploy_target: std::env::var("CELERITY_DEPLOY_TARGET").ok(), ws_ack_timeout_ms: ws_ack_timeout_ms_from_env(&ProcessEnvVars::new()), ws_ack_max_attempts: ws_ack_max_attempts_from_env(&ProcessEnvVars::new()), + ws_handler_concurrency: ws_handler_concurrency_from_env(&ProcessEnvVars::new()), }; println!("Creating CoreRuntimeApplication with config: {native_runtime_config:?}"); let inner = Application::new(native_runtime_config, Box::new(ProcessEnvVars::new())); From 3ee04efdb388f74f4444af0e122c85e6c6b24425 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 19 Aug 2026 15:38:05 +0100 Subject: [PATCH 6/8] test(lib-rt-core): hold the per tag limit to a test that can tell it apart The end to end test that a closing connection still tears down was mutation checked against the per tag limit before the reclaim existed. Once it did, removing the limit only delayed teardown until a place came free rather than preventing it, and the test waited long enough to see that, so it passed with the thing it covers taken out. Its window is now shorter than the earliest a reclaim can free anything, which is a handler timeout of a second and five more of grace, so what it observes is the place held back for the disconnect handler rather than one that happened to come free. A unit test covers the same rule directly, since an end to end test is a poor place to pin down an accounting rule and a slow one to run when it fails. The two concurrency tests were never at risk, with fifteen seconds before a place could come free against a two second wait, but nothing said so and the margin is not obvious. Now it is written down. Also, the credit the stub handler declares is named rather than repeated, since a test that fills the window has to know what filling it means. The declaration on StreamRegistration::limits said a tag with no entry is bounded only by the credit window, which the default limit made untrue. And an assertion message had a run of spaces in it, from a line continuation that went missing. --- libs/runtime/core/src/config.rs | 3 +- libs/runtime/core/src/dispatcher.rs | 52 ++++++++++++++++++- libs/runtime/core/tests/common/ipc.rs | 8 ++- libs/runtime/core/tests/ipc_websocket_test.rs | 18 +++++-- 4 files changed, 74 insertions(+), 7 deletions(-) diff --git a/libs/runtime/core/src/config.rs b/libs/runtime/core/src/config.rs index 0ff22012..9e3809f3 100644 --- a/libs/runtime/core/src/config.rs +++ b/libs/runtime/core/src/config.rs @@ -471,7 +471,8 @@ pub fn ws_handler_concurrency_from_env(env: &impl EnvVars) -> Option { .expect("Invalid WebSocket handler concurrency, must be a whole number"); assert!( concurrency > 0, - "Invalid WebSocket handler concurrency, a connection has to handle one message at a time at the least" + "Invalid WebSocket handler concurrency, a connection has to handle at least one \ + message at a time" ); concurrency }) diff --git a/libs/runtime/core/src/dispatcher.rs b/libs/runtime/core/src/dispatcher.rs index 3c369848..29a3926f 100644 --- a/libs/runtime/core/src/dispatcher.rs +++ b/libs/runtime/core/src/dispatcher.rs @@ -85,8 +85,9 @@ pub struct StreamRegistration { pub handler_tags: Vec, /// How many events may be in flight to this stream at once. pub initial_credit: u32, - /// Optional per-tag concurrency caps. A tag with no entry is bounded only - /// by the credit window. + /// Optional per-tag concurrency caps. A tag with no entry is bounded by the + /// credit window and by a default cap, which keeps a place for the other + /// tags so that no one of them can take the window entirely. pub limits: HashMap, /// Where dispatched events and the frames concerning them are sent. pub dispatch_tx: mpsc::Sender, @@ -1768,6 +1769,53 @@ mod tests { assert_eq!(default_tag_limit(64, 100), 32); } + /// A tag the handler declared no limit for still cannot take the window. + /// + /// The reclaim would eventually free the places a stalled tag holds, so + /// this is what keeps the other tags dispatching in the meantime rather + /// than waiting out a grace before they can be served at all. + #[tokio::test] + async fn a_tag_with_no_declared_limit_still_leaves_room_for_the_others() { + let harness = start(64); + let mut stream = attach(&harness, 1, &["hot", "cold"], 4, HashMap::new()).await; + + // More of the hot tag than the window holds, and none of them answered. + for index in 0..8 { + harness + .queue + .enqueue( + event(&format!("hot-{index}"), "hot"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + let mut hot = 0; + while let Some(dispatched) = recv_dispatch(&mut stream).await { + assert!(dispatched.event.id.starts_with("hot-")); + hot += 1; + } + assert!( + hot < 4, + "the hot tag took {hot} of a window of 4, leaving nothing for the other tag" + ); + + // The cold tag has never been served and nothing has answered, so the + // only reason it can be dispatched is the place held back for it. + harness + .queue + .enqueue( + event("cold-0", "cold"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + let cold = recv_dispatch(&mut stream) + .await + .expect("a tag that has taken nothing should still have a place"); + assert_eq!(cold.event.id, "cold-0"); + } + /// A handler that never answers a cancellation does not keep what it was /// holding. /// diff --git a/libs/runtime/core/tests/common/ipc.rs b/libs/runtime/core/tests/common/ipc.rs index a68da4d9..ebae80c9 100644 --- a/libs/runtime/core/tests/common/ipc.rs +++ b/libs/runtime/core/tests/common/ipc.rs @@ -17,9 +17,15 @@ use celerity_runtime_core::{ }, }; use tokio::{net::UnixStream, sync::mpsc}; + use tokio_stream::StreamExt; use tonic::transport::{Endpoint, Uri}; +/// The credit the stub handler declares, which is how many events the runtime +/// may have in flight to it at once. Named because a test that fills the window +/// has to know what filling it means. +pub const HANDLER_INITIAL_CREDIT: u32 = 8; + pub fn ipc_env( service_name: &str, fixture: &str, @@ -143,7 +149,7 @@ impl HandlerStub { .iter() .map(|handler| handler.handler_tag.clone()) .collect(), - initial_credit: 8, + initial_credit: HANDLER_INITIAL_CREDIT, sdk_version: "test/0.1".to_string(), limits: vec![], })), diff --git a/libs/runtime/core/tests/ipc_websocket_test.rs b/libs/runtime/core/tests/ipc_websocket_test.rs index 324c3ec0..a1910631 100644 --- a/libs/runtime/core/tests/ipc_websocket_test.rs +++ b/libs/runtime/core/tests/ipc_websocket_test.rs @@ -17,7 +17,9 @@ use celerity_runtime_core::{ consts::CELERITY_WS_CAPABILITIES_SIGNAL, ipc_proto::{self as proto}, }; -use common::ipc::{ipc_env, socket_path, start_runtime, websocket_ack, HandlerStub}; +use common::ipc::{ + ipc_env, socket_path, start_runtime, websocket_ack, HandlerStub, HANDLER_INITIAL_CREDIT, +}; use futures::SinkExt; use serde_json::json; use tokio_stream::StreamExt; @@ -1322,6 +1324,11 @@ async fn handles_one_message_at_a_time_when_asked_to() { /// /// The handler holding the first is what makes the count mean something. An /// answer would free the worker and both would arrive whatever the concurrency. +/// +/// The two second wait below is short for the same reason. The first message +/// stops holding its place fifteen seconds in, ten for the handler timeout and +/// five more for the cancellation grace perios, and a second message arriving after +/// that would mean a place came free rather than two being handled at once. async fn dispatches_seen_while_the_first_is_held( name: &str, overrides: &[(&'static str, &str)], @@ -1398,7 +1405,7 @@ async fn tears_a_connection_down_while_other_connections_hold_the_credit() { // As many connections as the stream has credit, each holding one message. let mut connections = Vec::new(); - for _ in 0..8 { + for _ in 0..HANDLER_INITIAL_CREDIT { let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) .await .expect("the WebSocket server should accept the connection"); @@ -1431,7 +1438,12 @@ async fn tears_a_connection_down_while_other_connections_hold_the_credit() { let mut closing = connections.pop().unwrap(); let _ = closing.close(None).await; - let disconnected = tokio::time::timeout(Duration::from_secs(10), async { + // The messages above fall due after a second and their places are taken + // back five seconds after that, so nothing the reclaim frees can arrive + // before six seconds in. This window closes well before then, which is what + // makes this the place held for the disconnect handler rather than a place + // that happened to come free. Teardown should not have to wait out a grace period. + let disconnected = tokio::time::timeout(Duration::from_secs(2), async { while let Some(dispatch) = handler.next_dispatch().await { if let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source { if message.route == "$disconnect" { From fd07c273755eac2c4d5e3d6c7ea99e761f4d6cd0 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 19 Aug 2026 17:52:55 +0100 Subject: [PATCH 7/8] fix(lib-rt-core): leave a place for the tags that are holding nothing A fixed share per tag stops any one of them taking the whole window, but the shares can add up to more than the window and then two tags take it between them anyway. Three tags on a window of four get two places each, and the first two to arrive leave the third nothing. The tag that suffers is the one nothing else can stand in for, a connection's disconnect handler among them. A place is now kept for each tag that is holding nothing, decided when the question is asked rather than fixed when the stream attached. The reservation shrinks as tags are served, so the last tag to arrive is not asked to leave room for tags that are already busy, which is what a fixed share cannot manage however the number is chosen. Still never more than half the window. A stream serving twenty tags on a window of eight cannot keep a place for each of them, and holding the window half empty for tags that may send nothing would cost whichever tag carries the traffic more than the starvation it avoids. The window is read as the credit in hand plus what is held rather than from what was declared at attach, so a grant that resizes it is accounted for without anything to recompute or forget to. --- libs/runtime/core/src/dispatcher.rs | 150 ++++++++++++++++------------ 1 file changed, 86 insertions(+), 64 deletions(-) diff --git a/libs/runtime/core/src/dispatcher.rs b/libs/runtime/core/src/dispatcher.rs index 29a3926f..9f20c9d9 100644 --- a/libs/runtime/core/src/dispatcher.rs +++ b/libs/runtime/core/src/dispatcher.rs @@ -141,11 +141,6 @@ struct StreamState { tags: HashSet, credit: u32, limits: HashMap, - /// What a tag may hold when the handler declared no limit for it. - /// - /// Leaves room for every other tag to place one event, so no tag can take - /// the window and leave the rest of them unable to dispatch at all. - default_limit: u32, /// How many events are in flight to this stream, per tag. in_flight: HashMap, /// The events this stream is holding, by event id and the tag they were @@ -164,38 +159,38 @@ impl StreamState { if self.draining || self.credit == 0 || !self.tags.contains(handler_tag) { return false; } - let cap = self - .limits - .get(handler_tag) - .copied() - .unwrap_or(self.default_limit); - self.in_flight.get(handler_tag).copied().unwrap_or(0) < cap + if let Some(cap) = self.limits.get(handler_tag) { + if self.in_flight.get(handler_tag).copied().unwrap_or(0) >= *cap { + return false; + } + } + self.credit.saturating_sub(1) >= self.reserved_for_other_tags(handler_tag) } -} -/// What a tag may hold when the handler declared no limit for it. -/// -/// A window is one per stream and is refused to every tag once it runs out, so -/// without this a single tag can take all of it and the others are not just slow, -/// they are stopped. That matters most for the tags nothing else can stand in -/// for. A connection's disconnect handler shares a window with the messages -/// that connection sent, and credit comes back only when a handler answers, so -/// handlers that never answer would otherwise leave the connection unable to -/// finish tearing down. -/// -/// Holds back a place for each of the other tags, but never more than half the -/// window. What is being bought is that no tag can take all of it, and a -/// handler serving many tags on a small window cannot give each of them a place -/// anyway. Without the halving, an application with twenty handlers and a window -/// of eight would cap every one of them at a single event, which is a worse -/// trade than the starvation it avoids for whichever handler carries the -/// traffic. -/// -/// A handler that wants a different split declares its own limits, which are -/// used as given. -fn default_tag_limit(credit: u32, tags: usize) -> u32 { - let held_back = (tags.saturating_sub(1) as u32).min(credit / 2); - credit.saturating_sub(held_back).max(1) + /// How many places have to be left for the tags holding nothing. + /// + /// Counted against the tags holding nothing rather than against all of + /// them, so it shrinks as they are served and the last tag to arrive is not + /// asked to leave room for tags already busy. A fixed share cannot manage + /// that. Give three tags a window of four and two places each, and the + /// first two take everything between them. + /// + /// Never more than half the window, since a stream serving many tags on a + /// small one cannot keep a place for each of them, and holding the window + /// half empty for tags that may send nothing would cost whichever tag + /// carries the traffic more than the starvation it avoids. + fn reserved_for_other_tags(&self, handler_tag: &str) -> u32 { + let idle = self + .tags + .iter() + .filter(|tag| tag.as_str() != handler_tag) + .filter(|tag| self.in_flight.get(*tag).copied().unwrap_or(0) == 0) + .count() as u32; + // Taken as it stands rather than as it was declared, since a grant may + // have resized the window since the stream attached. + let window = self.credit + self.holding.len() as u32; + idle.min(window / 2) + } } /// Runs the dispatch loop until shutdown. @@ -624,15 +619,12 @@ impl Dispatcher { throughput will be bounded by the buffer" ); } - let tags: HashSet = registration.handler_tags.into_iter().collect(); - let default_limit = default_tag_limit(registration.initial_credit, tags.len()); self.streams.insert( stream_id, StreamState { - tags, + tags: registration.handler_tags.into_iter().collect(), credit: registration.initial_credit, limits: registration.limits, - default_limit, in_flight: HashMap::new(), holding: HashMap::new(), draining: false, @@ -1738,35 +1730,65 @@ mod tests { assert!(!attached); } - /// Every tag keeps a place, so no tag can take the window and leave the - /// others unable to dispatch at all. - #[test] - fn a_tag_is_held_back_from_taking_the_whole_window() { - assert_eq!(default_tag_limit(8, 3), 6); - assert_eq!(default_tag_limit(8, 2), 7); - } + /// Three tags on a window of four, which a fixed share of two apiece cannot + /// serve: the first two take everything between them and the third is not + /// slow, it is stopped. + #[tokio::test] + async fn a_window_too_small_to_share_evenly_still_reaches_every_tag() { + let harness = start(64); + let mut stream = attach(&harness, 1, &["a", "b", "c"], 4, HashMap::new()).await; - /// Nothing to starve, so nothing is held back. - #[test] - fn a_stream_serving_one_tag_gives_it_everything() { - assert_eq!(default_tag_limit(8, 1), 8); - } + for tag in ["a", "b"] { + for index in 0..4 { + harness + .queue + .enqueue( + event(&format!("{tag}-{index}"), tag), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + } + let mut taken = Vec::new(); + while let Some(dispatched) = recv_dispatch(&mut stream).await { + taken.push(dispatched.event.id); + } - /// More tags than credit cannot leave a place for each, so every tag gets - /// one and the window itself is what turns them away. - #[test] - fn a_window_too_small_to_share_still_lets_every_tag_try() { - assert_eq!(default_tag_limit(2, 5), 1); - assert_eq!(default_tag_limit(0, 3), 1); + harness + .queue + .enqueue(event("c-0", "c"), admission_wait(Duration::from_secs(60))) + .await + .unwrap(); + let third = recv_dispatch(&mut stream).await; + assert_eq!( + third.map(|dispatched| dispatched.event.id), + Some("c-0".to_string()), + "the third tag was left nothing, the other two took {taken:?}" + ); } - /// Many handlers on a small window would otherwise cap each of them at a - /// single event, which costs whichever one carries the traffic far more - /// than the starvation it avoids. - #[test] - fn a_stream_serving_many_tags_still_keeps_half_the_window_for_one() { - assert_eq!(default_tag_limit(8, 20), 4); - assert_eq!(default_tag_limit(64, 100), 32); + /// Nothing to leave room for, so the whole window is available. + #[tokio::test] + async fn a_stream_serving_one_tag_gives_it_the_whole_window() { + let harness = start(64); + let mut stream = attach(&harness, 1, &["only"], 4, HashMap::new()).await; + + for index in 0..6 { + harness + .queue + .enqueue( + event(&format!("only-{index}"), "only"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + let mut taken = 0; + while recv_dispatch(&mut stream).await.is_some() { + taken += 1; + } + assert_eq!(taken, 4, "one tag alone should be able to fill the window"); } /// A tag the handler declared no limit for still cannot take the window. From f41f2b5871221944c0a29dc25f755f60c384ee42 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 19 Aug 2026 18:31:39 +0100 Subject: [PATCH 8/8] fix(lib-rt-core): keep the reservation window inside a u32 Credit saturates rather than wrapping, so a handler can declare or grant its way to the top of a u32. Dispatching moves a place from the credit to what is held and the two sum to the window, which alone cannot pass it, but a grant arriving while events are held parts them and the sum goes over. Nothing follows from it that can be seen from outside, since the wrap leaves a window of almost nothing and a credit that large refuses nothing anyway, and this profile does not check for the overflow. What it costs is a word, and what it buys is a debug build that does not panic. --- libs/runtime/core/src/dispatcher.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/libs/runtime/core/src/dispatcher.rs b/libs/runtime/core/src/dispatcher.rs index 9f20c9d9..b0e706ec 100644 --- a/libs/runtime/core/src/dispatcher.rs +++ b/libs/runtime/core/src/dispatcher.rs @@ -187,8 +187,10 @@ impl StreamState { .filter(|tag| self.in_flight.get(*tag).copied().unwrap_or(0) == 0) .count() as u32; // Taken as it stands rather than as it was declared, since a grant may - // have resized the window since the stream attached. - let window = self.credit + self.holding.len() as u32; + // have resized the window since the stream attached. Saturating because + // credit does, and a grant arriving while events are held can carry the + // sum past a u32. + let window = self.credit.saturating_add(self.holding.len() as u32); idle.min(window / 2) } }