diff --git a/docs/gateway/live-sharing.md b/docs/gateway/live-sharing.md index a1fd15df..5b96365a 100644 --- a/docs/gateway/live-sharing.md +++ b/docs/gateway/live-sharing.md @@ -56,8 +56,9 @@ channels, tasks, timers and locks; both speak GraphQL-WS through one codec, `NativeDelivery::live_counts()` reports active groups, consumers, cumulative source attempts, resets, upstream frames, exact duplicate frames and safe handoffs. Source attempts include credential reconnects; they are not a count of active producers. -`GraphqlEngine::live_subscriber_count()` separately reports actual origin producer -subscriptions. No credentials or subject identifiers appear in these counters. +`GraphqlEngine::live_subscriber_count()` reports live subscriptions reaching the +origin and `live_producer_count()` its producers +(one per distinct origin live read; see `docs/live-query-delivery.md`). No credentials or subject identifiers appear in these counters. Disable `live_sharing` and remove the live delivery resource to restore independent subscriptions. Existing client resume/reset and response-sealing behavior remains diff --git a/docs/live-query-delivery.md b/docs/live-query-delivery.md index e25bb459..f957ffb7 100644 --- a/docs/live-query-delivery.md +++ b/docs/live-query-delivery.md @@ -15,13 +15,35 @@ Every live response declares `extensions.distributed.live.mode`: A failed execution has no result and therefore no `live` metadata. It is sent as the terminal failure frame described below. +## Shared execution at the origin + +Subscribers whose live roots are the same read share one producer. A catalog +root is the same read when its role, compiled SQL and every bind (row policies +and claim values included) match and, with the causal protocol on, its cache +scope does too; an external root when its role, root, arguments and session +match. The first subscriber's frame is the producer's first execution; a later +one opens with its own read, which honours its own resume cursors. After that, +each change that touches the read is debounced (100ms) and executed once, and +the frame goes to every subscriber, each with its own hash gate and envelope. +A subscriber whose cursors are not where a frame replays from (it joined +between frames, or skipped one while slow) catches up with one read of its +own, so replay stays exact. The producer keeps only the latest frame, so a +slow subscriber never holds the others back. + +At most `GraphqlEngineBuilder::live_concurrency` live executions (default +8) run at once per engine: first reads, refreshes and catch-ups together. +When the last subscriber of a read leaves, its producer stops. +`GraphqlEngine::live_producer_count()` counts producers (distinct reads); +`GraphqlEngine::live_subscriber_count()` counts subscription streams. + ## Failed live executions A live execution that fails (for example a storage error or statement timeout) has no result. The server sends exactly one **failure frame** and then completes the operation. The failure ends that subscription: the server sends no more frames for it and never attaches a later execution's metadata to the failure -frame. A failure frame has: +frame. A failed shared execution ends every subscription that shares it. A +failure frame has: - `data` that is `null` or absent; - a nonempty `errors` array, where each entry is an object with a string diff --git a/src/graphql/compile/binds.rs b/src/graphql/compile/binds.rs index 4196244f..caa2b5ad 100644 --- a/src/graphql/compile/binds.rs +++ b/src/graphql/compile/binds.rs @@ -18,6 +18,46 @@ pub enum BindValue { Json(JsonValue), } +/// Two binds are equal exactly when the driver receives the same value: an +/// `F64` by its bits, a `Json` by the text it is bound as. Live sharing keys +/// on this, so equal binds must never be told apart by SQL. +impl PartialEq for BindValue { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::Null, Self::Null) => true, + (Self::Bool(a), Self::Bool(b)) => a == b, + (Self::I64(a), Self::I64(b)) => a == b, + (Self::F64(a), Self::F64(b)) => a.to_bits() == b.to_bits(), + (Self::Text(a), Self::Text(b)) => a == b, + (Self::Bytes(a), Self::Bytes(b)) => a == b, + (Self::Json(a), Self::Json(b)) => bound_text(a) == bound_text(b), + _ => false, + } + } +} + +impl Eq for BindValue {} + +/// The text a `Json` bind is sent as (see `apply_binds!`). +fn bound_text(value: &JsonValue) -> String { + value.to_string() +} + +impl std::hash::Hash for BindValue { + fn hash(&self, state: &mut H) { + std::mem::discriminant(self).hash(state); + match self { + Self::Null => {} + Self::Bool(value) => value.hash(state), + Self::I64(value) => value.hash(state), + Self::F64(value) => value.to_bits().hash(state), + Self::Text(value) => value.hash(state), + Self::Bytes(value) => value.hash(state), + Self::Json(value) => bound_text(value).hash(state), + } + } +} + /// Give a numeric column one bind type. /// /// The Postgres driver prepares a statement once per connection and reuses diff --git a/src/graphql/engine/builder.rs b/src/graphql/engine/builder.rs index 8d36d708..d199fa0b 100644 --- a/src/graphql/engine/builder.rs +++ b/src/graphql/engine/builder.rs @@ -40,6 +40,7 @@ impl GraphqlEngineBuilder { pending_errors: Vec::new(), identity: None, websocket: WebsocketLimits::default(), + live_concurrency: crate::graphql::subscribe::DEFAULT_LIVE_CONCURRENCY, read_stores: BTreeMap::new(), external: Vec::new(), } @@ -628,6 +629,20 @@ impl GraphqlEngineBuilder { self.websocket = limits; self } + /// Run at most `n` live executions at once (default + /// [`DEFAULT_LIVE_CONCURRENCY`](crate::graphql::subscribe::DEFAULT_LIVE_CONCURRENCY)). + /// Subscribers to the same read share one execution per change; this + /// bounds how many distinct reads (first reads, refreshes and catch-ups + /// together) hold a pool connection at a time, so a write burst cannot + /// starve one-shot queries. Must be at least 1. + pub fn live_concurrency(mut self, n: usize) -> Self { + if n == 0 { + self.pending_errors + .push("live_concurrency must be at least 1".into()); + } + self.live_concurrency = n; + self + } /// Serve an external read source's roots (queries, `@live` /// subscriptions, the client manifest); see /// [`ExternalReadSource`](crate::graphql::surface::ExternalReadSource). @@ -1112,6 +1127,7 @@ impl GraphqlEngineBuilder { schemas, graphiql_schemas, change_hub, + live: crate::graphql::subscribe::LiveRegistries::new(self.live_concurrency), dialect, identity: IdentityResolver::new(identity), websocket: self.websocket, diff --git a/src/graphql/engine/core.rs b/src/graphql/engine/core.rs index 3499f70a..c6774595 100644 --- a/src/graphql/engine/core.rs +++ b/src/graphql/engine/core.rs @@ -260,6 +260,8 @@ pub(crate) struct EngineInner { /// manifest-fingerprinted execution limits. pub graphiql_schemas: HashMap, pub change_hub: crate::graphql::subscribe::ChangeHub, + /// Shared live reads ([`crate::graphql::subscribe`]). + pub(crate) live: crate::graphql::subscribe::LiveRegistries, pub dialect: SqlDialect, /// How HTTP and WebSocket requests become sessions (see `identity` module). pub(crate) identity: IdentityResolver, @@ -350,6 +352,7 @@ pub struct GraphqlEngineBuilder { pub(crate) pending_errors: Vec, pub(crate) identity: Option, pub(crate) websocket: WebsocketLimits, + pub(crate) live_concurrency: usize, pub(crate) read_stores: BTreeMap, pub(crate) external: Vec>, } diff --git a/src/graphql/engine/delivery.rs b/src/graphql/engine/delivery.rs index 04e80b6f..04110d9f 100644 --- a/src/graphql/engine/delivery.rs +++ b/src/graphql/engine/delivery.rs @@ -31,11 +31,6 @@ fn ineligible() -> Response { ) } impl GraphqlEngine { - /// Active origin live-query producers for delivery diagnostics. - pub fn live_subscriber_count(&self) -> usize { - self.inner.change_hub.subscriber_count() - } - pub(super) fn enable_delivery_capture( &self, session: &Session, diff --git a/src/graphql/engine/public_api.rs b/src/graphql/engine/public_api.rs index a41cfd52..573a4535 100644 --- a/src/graphql/engine/public_api.rs +++ b/src/graphql/engine/public_api.rs @@ -203,4 +203,16 @@ impl GraphqlEngine { pub fn change_hub(&self) -> &crate::graphql::subscribe::ChangeHub { &self.inner.change_hub } + + /// Active live producers: one per distinct shared live read, however + /// many subscribers follow it. + pub fn live_producer_count(&self) -> usize { + self.inner.change_hub.subscriber_count() + } + + /// Active live subscription streams. Identical reads share one producer + /// ([`live_producer_count`](Self::live_producer_count)). + pub fn live_subscriber_count(&self) -> usize { + self.inner.live.subscriber_count() + } } diff --git a/src/graphql/external_roots.rs b/src/graphql/external_roots.rs index 5ba93545..cb5dc09d 100644 --- a/src/graphql/external_roots.rs +++ b/src/graphql/external_roots.rs @@ -7,28 +7,27 @@ use std::collections::BTreeMap; use std::sync::Arc; -use std::time::Duration; use async_graphql::dynamic::{ Field, FieldFuture, InputValue, Object, ResolverContext, Subscription, SubscriptionField, SubscriptionFieldFuture, TypeRef, }; use async_graphql::Value; -use futures_util::Stream; -use tokio::sync::{broadcast, mpsc}; use super::engine::{EngineInner, ExecutionAuthority}; use super::protocol::{ DistributedLiveMetadata, DistributedLiveMode, DistributedQuerySnapshot, - ProtocolResponseAccumulator, + ProtocolResponseAccumulator, RequestedLiveResume, }; use super::schema::{client_error, execution_privilege}; +use super::subscribe::{response_hash, LiveFrame, LiveQueryStream, LiveRead, LiveResult, Record}; use super::surface::external::external_types; use super::surface::{ ExternalField, ExternalReadError, ExternalReadExecutor, ExternalReadResult, ExternalRoot, Surface, }; use crate::microsvc::Session; +use crate::read_model::ReadModelChange; fn type_ref(type_name: &str, nullable: bool) -> TypeRef { if nullable { @@ -117,13 +116,7 @@ pub(crate) fn add_subscription_roots( let name = root.name.clone(); let field = SubscriptionField::new(root.name.clone(), result_type(&root), move |ctx| { let request = Request::from_context(&ctx, &key, &name); - SubscriptionFieldFuture::new(async move { - let request = request?; - // Subscribe before the first read so no change slips between. - let changes = request.inner.change_hub.subscribe(); - let first = request.execute().await?; - Ok(live_stream(request, first, changes)) - }) + SubscriptionFieldFuture::new(async move { Ok(request?.live()) }) }); subscription = subscription.field(with_arguments( field, @@ -139,6 +132,7 @@ pub(crate) fn add_subscription_roots( struct Request { inner: Arc, executor: Arc, + role: String, key: (String, String), root: String, arguments: BTreeMap, @@ -192,6 +186,7 @@ impl Request { protocol: ctx.data_opt::().cloned(), inner, executor, + role, key: key.clone(), root: root.to_string(), arguments, @@ -210,7 +205,7 @@ impl Request { /// envelope marks it incomplete and, live, as snapshot mode. fn record_protocol( &self, - result: &ExternalReadResult, + scope: &serde_json::Value, live: bool, ) -> Result<(), async_graphql::Error> { let Some(protocol) = &self.protocol else { @@ -222,7 +217,7 @@ impl Request { "section": self.key.0, "source": self.key.1, "root": self.root, - "scope": result.scope, + "scope": scope, })) .map_err(encoding)?; let snapshot = DistributedQuerySnapshot { @@ -255,96 +250,106 @@ async fn resolve( ) -> Result, async_graphql::Error> { let request = Request::from_context(ctx, key, root)?; let result = request.execute().await?; - request.record_protocol(&result, false)?; + request.record_protocol(&result.scope, false)?; Ok(match graphql_value(result.value)? { Value::Null => None, value => Some(value), }) } -type LiveItem = Result; +impl Request { + /// Follow this read live, sharing one producer with every subscriber + /// whose read is identical: same role, root, arguments and session (the + /// executor sees nothing else, so their results are the same). + fn live(self) -> LiveQueryStream { + let key = ExternalKey { + role: self.role.clone(), + section: self.key.0.clone(), + source: self.key.1.clone(), + root: self.root.clone(), + arguments: self.arguments.clone(), + session: self + .session + .variables() + .iter() + .map(|(name, value)| (name.clone(), value.clone())) + .collect(), + }; + let inner = Arc::clone(&self.inner); + let read = ExternalRead { + executor: Arc::clone(&self.executor), + root: self.root.clone(), + arguments: self.arguments.clone(), + session: self.session.clone(), + }; + let record: Record = + Box::new(move |meta: &ExternalMeta| self.record_protocol(&meta.scope, true)); + inner.live.external.subscribe( + &inner.change_hub, + key, + RequestedLiveResume::Absent, + || read, + record, + ) + } +} -struct ExternalLiveStream { - rx: mpsc::Receiver, +/// What makes two external live subscriptions one read. +#[derive(Clone, PartialEq, Eq, Hash)] +pub(crate) struct ExternalKey { + role: String, + section: String, + source: String, + root: String, + arguments: BTreeMap, + session: BTreeMap, } -impl Stream for ExternalLiveStream { - type Item = LiveItem; +/// An external root, re-executed live by its executor. +pub(crate) struct ExternalRead { + executor: Arc, + root: String, + arguments: BTreeMap, + session: Session, +} - fn poll_next( - mut self: std::pin::Pin<&mut Self>, - cx: &mut std::task::Context<'_>, - ) -> std::task::Poll> { - self.rx.poll_recv(cx) - } +/// What an external frame carries besides its value. +pub(crate) struct ExternalMeta { + /// What was read (bound into the protocol scope token). + scope: serde_json::Value, + /// The change keys after which the read re-executes. + change_keys: Vec, } -/// `first`, then a re-execution (debounced, hash-gated) whenever one of the -/// read's change keys is published. A failed execution is terminal. -fn live_stream( - request: Request, - first: ExternalReadResult, - mut changes: broadcast::Receiver, -) -> ExternalLiveStream { - let (tx, rx) = mpsc::channel::(8); - tokio::spawn(async move { - let mut last_hash = None; - let mut executed = Ok(first); - loop { - let result = match executed { - Ok(result) => result, - Err(error) => { - let _ = tx.send(Err(error)).await; - return; - } - }; - let keys = result.change_keys.clone(); - let value = match graphql_value(result.value.clone()) { - Ok(value) => value, - Err(error) => { - let _ = tx.send(Err(error)).await; - return; - } - }; - let hash = super::subscribe::response_hash(&value); - if last_hash != Some(hash) { - if let Err(error) = request.record_protocol(&result, true) { - let _ = tx.send(Err(error)).await; - return; - } - last_hash = Some(hash); - if tx.send(Ok(value)).await.is_err() { - return; - } - } - // Wait for a change to one of the keys (an empty set means "all"). - loop { - let change = tokio::select! { - _ = tx.closed() => return, - change = changes.recv() => change, - }; - match change { - Ok(change) - if change.tables.is_empty() - || keys.iter().any(|key| change.tables.contains(key)) => - { - break - } - Ok(_) => continue, - Err(broadcast::error::RecvError::Lagged(_)) => break, - Err(broadcast::error::RecvError::Closed) => return, - } - } - tokio::select! { - _ = tx.closed() => return, - _ = tokio::time::sleep(Duration::from_millis(100)) => {} - } - while let Ok(_) | Err(broadcast::error::TryRecvError::Lagged(_)) = changes.try_recv() {} - executed = tokio::select! { - _ = tx.closed() => return, - executed = request.execute() => executed, - }; - } - }); - ExternalLiveStream { rx } +impl LiveRead for ExternalRead { + type Meta = ExternalMeta; + + async fn execute(&self, _resume: RequestedLiveResume) -> LiveResult { + let result = self + .executor + .execute(&self.root, &self.arguments, &self.session) + .await + .map_err(|error: ExternalReadError| client_error(error.code(), error.message))?; + let value = graphql_value(result.value)?; + Ok(LiveFrame { + hash: response_hash(&value), + value, + // An external result is snapshot mode: nothing to resume. + next: RequestedLiveResume::Absent, + meta: ExternalMeta { + scope: result.scope, + change_keys: result.change_keys, + }, + }) + } + + /// A change to one of the last read's keys; an empty set means "all". + fn touched_by(&self, last: &LiveFrame, change: &ReadModelChange) -> bool { + change.tables.is_empty() + || last + .meta + .change_keys + .iter() + .any(|key| change.tables.contains(key)) + } } diff --git a/src/graphql/protocol/accumulator.rs b/src/graphql/protocol/accumulator.rs index 9b343797..0fa21dc7 100644 --- a/src/graphql/protocol/accumulator.rs +++ b/src/graphql/protocol/accumulator.rs @@ -116,6 +116,27 @@ impl ProtocolResponseAccumulator { } } + /// What every token this accumulator issues is bound to besides its own + /// material: the cache scope (itself a MAC over every authorization input + /// of the request) and the schema hash. Two accumulators with the same + /// scope and codec issue identical query and live tokens. + pub(crate) fn token_scope(&self) -> Result<(String, String), ProtocolAccumulatorError> { + self.with_envelope(|envelope| { + ( + envelope.cache_scope.as_str().to_owned(), + envelope.schema_hash.clone(), + ) + }) + } + + /// A fresh accumulator that issues exactly this one's tokens and shares + /// none of its response state: what a shared live execution evidences + /// with, so no subscriber's accumulator is touched by another's frame. + pub(crate) fn issuer(&self) -> Result { + let envelope = self.with_envelope(Clone::clone)?; + Ok(Self::new(envelope, self.inner.codec.clone())) + } + pub(crate) fn bind_projection_request( &self, request: crate::graphql::projection_delta::runtime::ProtocolProjectionRequestSeed, diff --git a/src/graphql/schema.rs b/src/graphql/schema.rs index 18645d98..315a7b5d 100644 --- a/src/graphql/schema.rs +++ b/src/graphql/schema.rs @@ -302,10 +302,7 @@ pub fn build_role_schema( recorder.record(plan), ); } - let stream = - super::subscribe::live_query_stream(inner, role, plan, protocol) - .await?; - Ok(stream) + super::subscribe::live_query_stream(&inner, role, plan, protocol) }) }, ), diff --git a/src/graphql/subscribe.rs b/src/graphql/subscribe.rs index 7f8f266d..9e920bde 100644 --- a/src/graphql/subscribe.rs +++ b/src/graphql/subscribe.rs @@ -1,35 +1,65 @@ -//! Commit-path subscription invalidation (live query refresh). +//! Live queries: one shared producer per distinct read, fanned out. //! -//! Each subscription field: -//! 1. Executes the query once and yields the initial result. -//! 2. Listens on [`ChangeHub`] (fed by `change_stream` / repo broadcast). -//! 3. On dirty tables intersecting the plan footprint, debounces, re-executes, -//! and yields only when the response hash changes (hash-gated push). +//! Every live root — a catalog plan or an external read — is a [`LiveRead`]. +//! Subscribers whose reads have the same key share one entry of a +//! [`LiveRegistry`] and its one producer loop: //! -//! A failed execution is terminal (`docs/live-query-delivery.md`): the producer -//! yields one error and stops. GraphQL ends the subscription on that error, and -//! the failure frame carries only the base protocol envelope. Protocol frame -//! metadata is a FIFO consumed by each emitted response, so producing another -//! frame after an error could let the error response take that later frame's -//! snapshot/live metadata. - -use std::collections::BTreeSet; +//! 1. The first subscriber creates the entry; the producer's first execution +//! is that subscriber's first frame. A later subscriber opens with its own +//! execution (it may resume from its own cursors), then follows the entry. +//! 2. The producer listens on [`ChangeHub`]. On a change that touches its last +//! result it debounces, executes once, and publishes the frame to every +//! subscriber. +//! 3. Each subscriber keeps its own hash gate and protocol envelope. A frame +//! whose replay starts where the subscriber's last frame ended is taken as +//! is; otherwise (the subscriber joined between frames, or skipped one +//! while it was slow) the subscriber executes once from its own cursors. +//! +//! Publishing never waits on a subscriber: the entry holds only the latest +//! frame, so a slow subscriber skips frames instead of stalling the others. +//! The producer's executions are exclusive on the entry and a subscriber's own +//! are shared, so a published frame is always newer than any own execution a +//! subscriber delivered before it. At most `live_concurrency` live executions +//! (first reads, refreshes and catch-ups) run at once per engine. +//! +//! A failed execution is terminal (`docs/live-query-delivery.md`): a failed +//! shared execution ends every subscriber of the entry with that one error, +//! and the entry is gone before anyone else can join it. Protocol frame +//! metadata is a FIFO consumed by each emitted response, so it is recorded +//! only at the moment its value is yielded. When the last subscriber leaves, +//! the producer stops and the entry is removed. + +use std::collections::{BTreeSet, HashMap}; +use std::future::Future; +use std::hash::Hash; use std::pin::Pin; -use std::sync::Arc; +use std::sync::{Arc, Mutex, Weak}; use std::task::{Context, Poll}; use std::time::Duration; use async_graphql::Value; +use futures_util::stream::BoxStream; use futures_util::Stream; -use tokio::sync::{broadcast, mpsc}; +use tokio::sync::{broadcast, watch, RwLock, Semaphore}; use crate::read_model::ReadModelChange; -use super::compile::{QueryPlan, SqlPlan}; +use super::compile::{BindValue, QueryPlan, SqlPlan}; use super::engine::EngineInner; -use super::execute::{execute_plan, ProtocolRead}; +use super::execute::{execute_plan, ProtocolEvidence, ProtocolRead}; +use super::external_roots::{ExternalKey, ExternalRead}; use super::protocol::{ProtocolResponseAccumulator, RequestedLiveResume}; use super::schema::client_error; +use super::surface::Surface; + +/// Live executions (first reads, refreshes, catch-ups) one engine runs at +/// once unless [`GraphqlEngineBuilder::live_concurrency`] says otherwise. +/// +/// [`GraphqlEngineBuilder::live_concurrency`]: super::GraphqlEngineBuilder::live_concurrency +pub const DEFAULT_LIVE_CONCURRENCY: usize = 8; + +/// How long a producer waits after a change for more to coalesce. +const DEBOUNCE: Duration = Duration::from_millis(100); /// Fan-out hub for read-model change notifications. #[derive(Clone, Debug)] @@ -43,7 +73,7 @@ impl ChangeHub { Self { tx } } - /// Active origin live readers, excluding the external invalidation forwarder. + /// Active live producers (one per shared live read). pub fn subscriber_count(&self) -> usize { self.tx.receiver_count() } @@ -52,11 +82,9 @@ impl ChangeHub { self.tx.subscribe() } + /// Publish a change. An empty table set means "everything changed" (the + /// lag signal the forwarder sends). pub fn publish(&self, change: ReadModelChange) { - if change.is_empty() { - // Empty set is reserved as the all-dirty lag signal; allow it only - // when explicitly published for that purpose (forwarder). - } let _ = self.tx.send(change); } @@ -93,208 +121,528 @@ type LiveItem = Result; /// Stream of GraphQL field values for one live subscription. pub struct LiveQueryStream { - rx: mpsc::Receiver, + inner: BoxStream<'static, LiveItem>, } impl Stream for LiveQueryStream { type Item = LiveItem; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - self.rx.poll_recv(cx) + self.inner.as_mut().poll_next(cx) } } -/// Build a live-query stream for a subscription root field's compiled plan. -pub(crate) async fn live_query_stream( - inner: Arc, - role: String, - plan: QueryPlan, - protocol: Option, -) -> Result { - let plan: Arc = match plan { - QueryPlan::Sql(plan) => plan, - QueryPlan::CellByKey { .. } => { - return Err(client_error("BAD_REQUEST", "unsupported on cell store")); +/// One live execution's result, as every subscriber of its read sees it. +pub(crate) struct LiveFrame { + pub(crate) value: Value, + /// The hash gate's key: a frame equal to the last one is not pushed. + pub(crate) hash: u64, + /// Where the next execution resumes from. + pub(crate) next: RequestedLiveResume, + /// What each subscriber records with the value (protocol evidence). + pub(crate) meta: M, +} + +pub(crate) type LiveResult = Result, async_graphql::Error>; + +/// A read a live producer re-executes, independent of who subscribed to it. +pub(crate) trait LiveRead: Send + Sync + 'static { + type Meta: Send + Sync + 'static; + + /// Execute once, replaying from `resume`. + fn execute( + &self, + resume: RequestedLiveResume, + ) -> impl Future> + Send + '_; + + /// Whether `change` can alter the read whose last frame is `last`. + fn touched_by(&self, last: &LiveFrame, change: &ReadModelChange) -> bool; +} + +/// Records a frame's metadata into one subscriber's response envelope. +pub(crate) type Record = Box Result<(), async_graphql::Error> + Send>; + +/// The live registries of one engine, sharing one execution bound. +pub(crate) struct LiveRegistries { + pub(crate) plans: LiveRegistry, + pub(crate) external: LiveRegistry, +} + +impl LiveRegistries { + pub(crate) fn new(concurrency: usize) -> Self { + let permits = Arc::new(Semaphore::new(concurrency)); + Self { + plans: LiveRegistry::new(Arc::clone(&permits)), + external: LiveRegistry::new(permits), } - }; - let footprint = footprint_from_tables(&plan.tables_touched); - let mut change_rx = inner.change_hub.subscribe(); - let (tx, rx) = mpsc::channel::(8); - let debounce = Duration::from_millis(100); - let requested_live_resume = protocol - .as_ref() - .map(ProtocolResponseAccumulator::requested_live_resume) - .transpose() - .map_err(|_| client_error("BAD_REQUEST", "invalid live resume"))? - .unwrap_or(RequestedLiveResume::Absent); + } - tokio::spawn(async move { - // 1) Initial execution + yield - let initial_result = tokio::select! { - _ = tx.closed() => return, - result = execute_list(&inner, &role, &plan, protocol.as_ref(), requested_live_resume) => result, - }; - let mut initial = match initial_result { - Ok(executed) => executed, - Err(error) => { - let _ = tx.send(Err(error)).await; - return; + /// Live subscription streams across every shared read. + pub(crate) fn subscriber_count(&self) -> usize { + self.plans.subscriber_count() + self.external.subscriber_count() + } +} + +/// Shared live reads by key. +pub(crate) struct LiveRegistry { + entries: Arc>>>, + permits: Arc, +} + +struct Entry { + frames: Weak>>, + shared: Weak>, +} + +/// The latest published frame, if any. +type Slot = Option>>; + +struct Published { + /// Counts the entry's executions; a subscriber takes only newer frames. + version: u64, + /// Where this execution replayed from. + resumed: RequestedLiveResume, + result: LiveResult, +} + +/// What a producer and its subscribers share. +struct Shared { + read: R, + /// The producer's executions take it exclusively, a subscriber's own + /// executions shared, so a frame published after a subscriber's own + /// execution was read from a newer snapshot. + order: RwLock<()>, + permits: Arc, +} + +impl LiveRegistry +where + K: Clone + Eq + Hash + Send + Sync + 'static, + R: LiveRead, +{ + fn new(permits: Arc) -> Self { + Self { + entries: Arc::default(), + permits, + } + } + + /// Follow the live read `key`, creating it from `read` when nobody does + /// yet. `resume` is where this subscriber's first frame replays from. + pub(crate) fn subscribe( + &self, + hub: &ChangeHub, + key: K, + resume: RequestedLiveResume, + read: impl FnOnce() -> R, + record: Record, + ) -> LiveQueryStream { + let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); + let existing = entries + .get(&key) + .and_then(|entry| Some((entry.frames.upgrade()?, entry.shared.upgrade()?))); + let (frames, shared, joined) = match existing { + Some((sender, shared)) => (sender.subscribe(), shared, true), + None => { + let (sender, frames) = watch::channel(None); + let sender = Arc::new(sender); + let shared = Arc::new(Shared { + read: read(), + order: RwLock::new(()), + permits: Arc::clone(&self.permits), + }); + entries.insert( + key.clone(), + Entry { + frames: Arc::downgrade(&sender), + shared: Arc::downgrade(&shared), + }, + ); + let producer = Producer { + key, + entries: Arc::clone(&self.entries), + frames: sender, + shared: Arc::clone(&shared), + }; + // Subscribe before the first read so no change slips between. + tokio::spawn(producer.run(hub.subscribe(), resume.clone())); + (frames, shared, false) } }; - if initial.record_protocol_metadata(protocol.as_ref()).is_err() { - let _ = tx.send(Err(evidence_failed())).await; - return; - } - let mut last_hash = Some(initial.hash); - let mut next_live_resume = initial.next_live_resume; - if tx.send(Ok(initial.value)).await.is_err() { - return; + let seen = frames.borrow().as_ref().map_or(0, |frame| frame.version); + drop(entries); + let subscriber = Subscriber { + shared, + frames, + seen, + resume, + own_first: joined, + last_hash: None, + record, + done: false, + }; + LiveQueryStream { + inner: Box::pin(futures_util::stream::unfold( + subscriber, + |mut subscriber| async move { + let item = subscriber.next().await?; + Some((item, subscriber)) + }, + )), } + } - // 2) Change loop: dirty → debounce → re-exec → hash-gate → yield - loop { - let change = match tokio::select! { - _ = tx.closed() => break, - change = change_rx.recv() => change, - } { - Ok(c) => c, - Err(broadcast::error::RecvError::Lagged(_)) => ReadModelChange { - tables: BTreeSet::new(), - }, - Err(broadcast::error::RecvError::Closed) => break, - }; + /// Subscription streams following this registry's reads (each holds one + /// receiver of its read's frame channel). + fn subscriber_count(&self) -> usize { + let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); + entries + .values() + .filter_map(|entry| entry.frames.upgrade()) + .map(|frames| frames.receiver_count()) + .sum() + } - if !footprint_hits(&footprint, &change) { - continue; + #[cfg(test)] + fn len(&self) -> usize { + self.entries.lock().unwrap().len() + } +} + +struct Producer { + key: K, + entries: Arc>>>, + frames: Arc>>, + shared: Arc>, +} + +impl Producer +where + K: Clone + Eq + Hash + Send + Sync + 'static, + R: LiveRead, +{ + async fn run( + self, + mut changes: broadcast::Receiver, + first: RequestedLiveResume, + ) { + let shared = Arc::clone(&self.shared); + let mut resume = first; + let mut version = 0; + let mut last: Option>> = None; + loop { + if let Some(Ok(frame)) = last.as_ref().map(|published| &published.result) { + // Wait for a change to what the last frame read. + loop { + let Some(change) = self.while_watched(changes.recv()).await else { + return; + }; + match change { + Ok(change) if shared.read.touched_by(frame, &change) => break, + Ok(_) => continue, + Err(broadcast::error::RecvError::Lagged(_)) => break, + Err(broadcast::error::RecvError::Closed) => return self.retire(None), + } + } + if self + .while_watched(tokio::time::sleep(DEBOUNCE)) + .await + .is_none() + { + return; + } + loop { + match changes.try_recv() { + Ok(_) | Err(broadcast::error::TryRecvError::Lagged(_)) => {} + Err(broadcast::error::TryRecvError::Empty) => break, + Err(broadcast::error::TryRecvError::Closed) => return self.retire(None), + } + } } + // Lock, then permit: whoever holds a permit is executing, never + // waiting, so the two cannot deadlock. + let Some(_order) = self.while_watched(shared.order.write()).await else { + return; + }; + let Some(Ok(_permit)) = self.while_watched(shared.permits.acquire()).await else { + return; + }; + let Some(result) = self + .while_watched(shared.read.execute(resume.clone())) + .await + else { + return; + }; + version += 1; + let published = Arc::new(Published { + version, + resumed: std::mem::take(&mut resume), + result, + }); + let Ok(frame) = &published.result else { + return self.retire(Some(published)); + }; + resume = frame.next.clone(); + // Published while the order lock is held. + self.frames.send_replace(Some(Arc::clone(&published))); + last = Some(published); + } + } - // Debounce / coalesce + /// Run `work` unless every subscriber leaves first (`None`: stop). + async fn while_watched(&self, work: impl Future) -> Option { + tokio::pin!(work); + loop { tokio::select! { - _ = tx.closed() => break, - _ = tokio::time::sleep(debounce) => {}, - } - loop { - match change_rx.try_recv() { - Ok(more) => { - // Keep waiting only if still relevant; either way we re-exec once. - let _ = more; + output = &mut work => return Some(output), + _ = self.frames.closed() => { + let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); + // A subscriber may have joined since: joining holds this lock. + if self.frames.receiver_count() == 0 { + self.remove(&mut entries); + return None; } - Err(broadcast::error::TryRecvError::Empty) => break, - Err(broadcast::error::TryRecvError::Lagged(_)) => break, - Err(broadcast::error::TryRecvError::Closed) => return, } } + } + } - let refreshed = tokio::select! { - _ = tx.closed() => break, - result = execute_list(&inner, &role, &plan, protocol.as_ref(), next_live_resume.clone()) => result, - }; - match refreshed { - Ok(mut executed) => { - // Advance the private replay cursor even when a redundant - // execution is hash-gated. Protocol frame metadata is - // enqueued only when the matching GraphQL value is emitted, - // preserving exact data/envelope FIFO ordering. - next_live_resume = executed.next_live_resume.clone(); - if last_hash == Some(executed.hash) { - continue; // hash gate: no push on no-change - } - if executed - .record_protocol_metadata(protocol.as_ref()) - .is_err() - { - let _ = tx.send(Err(evidence_failed())).await; - return; - } - last_hash = Some(executed.hash); - if tx.send(Ok(executed.value)).await.is_err() { - return; - } + /// Stop for good, publishing `last` (a failure) to every subscriber first. + /// Nobody can join between the two: joining holds the registry lock. + fn retire(self, last: Option>>) { + let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(last) = last { + self.frames.send_replace(Some(last)); + } + self.remove(&mut entries); + // Dropping the sender ends every subscriber that has nothing left. + } + + fn remove(&self, entries: &mut HashMap>) { + let ours = entries + .get(&self.key) + .is_some_and(|entry| std::ptr::eq(entry.frames.as_ptr(), Arc::as_ptr(&self.frames))); + if ours { + entries.remove(&self.key); + } + } +} + +struct Subscriber { + shared: Arc>, + frames: watch::Receiver>, + /// The newest frame version this subscriber has taken or outrun. + seen: u64, + /// Where this subscriber's next frame must replay from. + resume: RequestedLiveResume, + /// Joined an existing entry: the first frame is its own execution. + own_first: bool, + last_hash: Option, + record: Record, + done: bool, +} + +impl Subscriber { + async fn next(&mut self) -> Option { + if self.done { + return None; + } + loop { + let own; + let published; + let result = if std::mem::take(&mut self.own_first) { + own = self.execute_own().await; + &own + } else { + // The producer is gone with nothing new: the stream ends. + self.frames.changed().await.ok()?; + let Some(latest) = self.frames.borrow_and_update().clone() else { + continue; + }; + if latest.version <= self.seen { + continue; + } + self.seen = latest.version; + published = latest; + if published.result.is_ok() && published.resumed != self.resume { + // Joined between frames or skipped one: catch up exactly. + own = self.execute_own().await; + &own + } else { + &published.result } + }; + let frame = match result { + Ok(frame) => frame, Err(error) => { - let _ = tx.send(Err(error)).await; - return; + self.done = true; + return Some(Err(error.clone())); } + }; + // Advance the replay cursor even when the frame is hash-gated. + self.resume = frame.next.clone(); + if self.last_hash == Some(frame.hash) { + continue; + } + if let Err(error) = (self.record)(&frame.meta) { + self.done = true; + return Some(Err(error)); } + self.last_hash = Some(frame.hash); + return Some(Ok(frame.value.clone())); } - }); + } - Ok(LiveQueryStream { rx }) + /// Execute from this subscriber's own cursors, ordered against the + /// producer: every frame it publishes afterwards is newer. + async fn execute_own(&mut self) -> LiveResult { + let shared = Arc::clone(&self.shared); + let _order = shared.order.read().await; + let _permit = shared.permits.acquire().await; + self.seen = self + .frames + .borrow() + .as_ref() + .map_or(0, |frame| frame.version); + shared.read.execute(self.resume.clone()).await + } } -fn evidence_failed() -> async_graphql::Error { - client_error("INTERNAL", "query evidence encoding failed") +/// What makes two catalog live subscriptions one read. +/// +/// The plan's SQL and binds carry every row policy and claim value; the +/// role selects the surface its evidence is read under; protocol tokens are +/// MACs over the cache scope (privilege, asserted roles, principal partition +/// and every claim a policy reads) and schema hash. Live subscriptions never +/// carry a gateway capture (`enable_delivery_capture` admits queries only). +#[derive(Clone, PartialEq, Eq, Hash)] +pub(crate) struct PlanKey { + role: String, + sql: Arc, + binds: Vec, + tables: Vec, + bytes_hex_paths: Vec, + protocol: Option<(String, String)>, } -struct ExecutedLiveQuery { - value: Value, - hash: u64, - snapshot: Option, - live: Option, - next_live_resume: RequestedLiveResume, +/// A compiled catalog plan, re-executed live. +pub(crate) struct PlanRead { + inner: Arc, + plan: Arc, + footprint: BTreeSet, + /// The role surface and a token issuer, under the causal protocol. + protocol: Option<(Arc, ProtocolResponseAccumulator)>, } -impl ExecutedLiveQuery { - fn record_protocol_metadata( - &mut self, - protocol: Option<&ProtocolResponseAccumulator>, - ) -> Result<(), String> { - let Some(protocol) = protocol else { - return Ok(()); +impl LiveRead for PlanRead { + type Meta = Option; + + async fn execute(&self, resume: RequestedLiveResume) -> LiveResult { + let read = self + .protocol + .as_ref() + .map(|(role_surface, issuer)| ProtocolRead { + role_surface: Arc::clone(role_surface), + accumulator: issuer.clone(), + live_resume: Some(resume), + }); + let executed = execute_plan(&self.inner, &self.inner.pool, true, &self.plan, read) + .await + .map_err(|error| error.client_error())?; + let Some(evidence) = executed.protocol else { + return Ok(LiveFrame { + hash: response_hash(&executed.value), + value: executed.value, + next: RequestedLiveResume::Absent, + meta: None, + }); }; - let snapshot = self - .snapshot - .take() - .ok_or_else(|| "causal live query omitted its snapshot metadata".to_string())?; - protocol - .record_query_metadata(snapshot, self.live.take()) - .map_err(|error| error.to_string()) + let hash = hash_json(&(&executed.value, &evidence.snapshot, &evidence.live)); + let next = evidence + .live + .as_ref() + .filter(|live| live.mode == super::protocol::DistributedLiveMode::Resumable) + .map(|live| RequestedLiveResume::Cursors(live.cursors.clone())) + .unwrap_or(RequestedLiveResume::Absent); + Ok(LiveFrame { + value: executed.value, + hash, + next, + meta: Some(evidence), + }) + } + + fn touched_by(&self, _last: &LiveFrame, change: &ReadModelChange) -> bool { + footprint_hits(&self.footprint, change) } } -async fn execute_list( - inner: &EngineInner, - role: &str, - plan: &SqlPlan, - protocol: Option<&ProtocolResponseAccumulator>, - requested_live_resume: RequestedLiveResume, -) -> Result { - let read = match protocol { +/// Build a live-query stream for a subscription root field's compiled plan. +pub(crate) fn live_query_stream( + inner: &Arc, + role: String, + plan: QueryPlan, + protocol: Option, +) -> Result { + let plan: Arc = match plan { + QueryPlan::Sql(plan) => plan, + QueryPlan::CellByKey { .. } => { + return Err(client_error("BAD_REQUEST", "unsupported on cell store")); + } + }; + let resume = protocol + .as_ref() + .map(ProtocolResponseAccumulator::requested_live_resume) + .transpose() + .map_err(|_| client_error("BAD_REQUEST", "invalid live resume"))? + .unwrap_or(RequestedLiveResume::Absent); + let shared_protocol = match &protocol { None => None, - Some(accumulator) => Some(ProtocolRead { - role_surface: inner.role_surfaces.get(role).cloned().ok_or_else(|| { + Some(accumulator) => { + // Matching compiler plans share one comparable snapshot scope, so + // a lagging refresh is never authoritative over a newer frame. + accumulator + .bind_query_snapshot_scope(&plan.snapshot_scope()) + .map_err(|_| evidence_failed())?; + let role_surface = inner.role_surfaces.get(&role).cloned().ok_or_else(|| { client_error("INTERNAL", "authorized GraphQL role surface is unavailable") - })?, - accumulator: accumulator.clone(), - live_resume: Some(requested_live_resume), - }), + })?; + let scope = accumulator.token_scope().map_err(|_| evidence_failed())?; + let issuer = accumulator.issuer().map_err(|_| evidence_failed())?; + Some((scope, role_surface, issuer)) + } }; - let executed = execute_plan(inner, &inner.pool, true, plan, read) - .await - .map_err(|error| error.client_error())?; - let Some(evidence) = executed.protocol else { - return Ok(ExecutedLiveQuery { - hash: response_hash(&executed.value), - value: executed.value, - snapshot: None, - live: None, - next_live_resume: RequestedLiveResume::Absent, - }); + let key = PlanKey { + role, + sql: Arc::clone(&plan.sql), + binds: plan.binds.clone(), + tables: plan.tables_touched.clone(), + bytes_hex_paths: plan.bytes_hex_paths.clone(), + protocol: shared_protocol.as_ref().map(|(scope, ..)| scope.clone()), + }; + let record: Record> = Box::new(move |meta| { + let Some(protocol) = &protocol else { + return Ok(()); + }; + let evidence = meta.as_ref().ok_or_else(evidence_failed)?; + protocol + .record_query_metadata(evidence.snapshot.clone(), evidence.live.clone()) + .map_err(|_| evidence_failed()) + }); + let read = || PlanRead { + inner: Arc::clone(inner), + footprint: footprint_from_tables(&plan.tables_touched), + plan: Arc::clone(&plan), + protocol: shared_protocol.map(|(_, role_surface, issuer)| (role_surface, issuer)), }; - let hash = hash_json(&(&executed.value, &evidence.snapshot, &evidence.live)); - let next_live_resume = evidence + Ok(inner .live - .as_ref() - .filter(|live| live.mode == super::protocol::DistributedLiveMode::Resumable) - .map(|live| RequestedLiveResume::Cursors(live.cursors.clone())) - .unwrap_or(RequestedLiveResume::Absent); - Ok(ExecutedLiveQuery { - value: executed.value, - hash, - snapshot: Some(evidence.snapshot), - live: evidence.live, - next_live_resume, - }) + .plans + .subscribe(&inner.change_hub, key, resume, read, record)) +} + +fn evidence_failed() -> async_graphql::Error { + client_error("INTERNAL", "query evidence encoding failed") } fn footprint_hits(footprint: &BTreeSet, change: &ReadModelChange) -> bool { @@ -342,3 +690,6 @@ fn hash_json(value: &impl serde::Serialize) -> u64 { pub fn spawn_change_forwarder(hub: ChangeHub, rx: broadcast::Receiver) { hub.spawn_forward_from(rx); } + +#[cfg(test)] +mod tests; diff --git a/src/graphql/subscribe/tests.rs b/src/graphql/subscribe/tests.rs new file mode 100644 index 00000000..a35126db --- /dev/null +++ b/src/graphql/subscribe/tests.rs @@ -0,0 +1,333 @@ +//! The shared producer loop, driven by a counting read under paused time: +//! every assertion counts executions or entries, none waits on a clock. + +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; + +use futures_util::{FutureExt, StreamExt}; + +use super::*; +use crate::graphql::protocol::{DistributedLiveCursor, ProtocolTokenCodec, ProtocolTokenPurpose}; + +/// The data a read sees, and what its executions did. +#[derive(Clone, Default)] +struct Store { + data: Arc, + fail: Arc, + executions: Arc, + in_flight: Arc, + max_in_flight: Arc, +} + +impl Store { + fn executions(&self) -> usize { + self.executions.load(Ordering::SeqCst) + } + + fn set(&self, data: u64) { + self.data.store(data, Ordering::SeqCst); + } +} + +struct Counted { + store: Store, + /// Holds every execution until a permit is added. + gate: Option>, + /// Frames resume from a cursor at the data they read. + resumable: bool, +} + +fn cursor(data: u64) -> RequestedLiveResume { + let token = ProtocolTokenCodec::new([7; 32]) + .issue(ProtocolTokenPurpose::LiveResume, &data) + .unwrap(); + RequestedLiveResume::Cursors(vec![DistributedLiveCursor { + projection: "p".into(), + position: data.to_string(), + token, + }]) +} + +impl LiveRead for Counted { + type Meta = u64; + + async fn execute(&self, _resume: RequestedLiveResume) -> LiveResult { + let store = &self.store; + store.executions.fetch_add(1, Ordering::SeqCst); + let now = store.in_flight.fetch_add(1, Ordering::SeqCst) + 1; + store.max_in_flight.fetch_max(now, Ordering::SeqCst); + if let Some(gate) = &self.gate { + gate.acquire().await.unwrap().forget(); + } + store.in_flight.fetch_sub(1, Ordering::SeqCst); + if store.fail.load(Ordering::SeqCst) { + return Err(async_graphql::Error::new("boom")); + } + let data = store.data.load(Ordering::SeqCst); + Ok(LiveFrame { + value: Value::from(data), + hash: data, + next: if self.resumable { + cursor(data) + } else { + RequestedLiveResume::Absent + }, + meta: data, + }) + } + + fn touched_by(&self, _last: &LiveFrame, change: &ReadModelChange) -> bool { + change.tables.is_empty() || change.tables.contains("t") + } +} + +fn registry(concurrency: usize) -> LiveRegistry<&'static str, Counted> { + LiveRegistry::new(Arc::new(Semaphore::new(concurrency))) +} + +fn follow( + registry: &LiveRegistry<&'static str, Counted>, + hub: &ChangeHub, + key: &'static str, + store: &Store, +) -> LiveQueryStream { + follow_read( + registry, + hub, + key, + Counted { + store: store.clone(), + gate: None, + resumable: false, + }, + ) +} + +fn follow_read( + registry: &LiveRegistry<&'static str, Counted>, + hub: &ChangeHub, + key: &'static str, + read: Counted, +) -> LiveQueryStream { + registry.subscribe( + hub, + key, + RequestedLiveResume::Absent, + || read, + Box::new(|_| Ok(())), + ) +} + +fn touch(hub: &ChangeHub) { + hub.publish(ReadModelChange::new(["t"])); +} + +/// With the clock paused, this returns only once every task is idle. +async fn settle() { + tokio::time::sleep(Duration::from_secs(1)).await; +} + +async fn next_value(stream: &mut LiveQueryStream) -> u64 { + let value = stream.next().await.expect("frame").expect("value"); + match value { + Value::Number(number) => number.as_u64().unwrap(), + other => panic!("{other:?}"), + } +} + +#[tokio::test(start_paused = true)] +async fn subscribers_to_one_read_share_one_execution_per_change() { + let (hub, registry, store) = (ChangeHub::new(), registry(8), Store::default()); + let mut streams = (0..10) + .map(|_| follow(®istry, &hub, "q", &store)) + .collect::>(); + for stream in &mut streams { + assert_eq!(next_value(stream).await, 0); + } + // The producer's first read, then each later subscriber's own. + assert_eq!(store.executions(), 10); + assert_eq!((registry.len(), hub.subscriber_count()), (1, 1)); + + for data in 1..=3 { + store.set(data); + touch(&hub); + for stream in &mut streams { + assert_eq!(next_value(stream).await, data); + } + assert_eq!(store.executions(), 10 + data as usize); + } + + // An unrelated change and a redundant one cost nothing / push nothing. + hub.publish(ReadModelChange::new(["other"])); + touch(&hub); + settle().await; + assert_eq!(store.executions(), 14); + for stream in &mut streams { + assert!(stream.next().now_or_never().is_none(), "hash-gated"); + } +} + +#[tokio::test(start_paused = true)] +async fn different_keys_never_share() { + let (hub, registry, store) = (ChangeHub::new(), registry(8), Store::default()); + let mut a = follow(®istry, &hub, "a", &store); + let mut b = follow(®istry, &hub, "b", &store); + assert_eq!((next_value(&mut a).await, next_value(&mut b).await), (0, 0)); + assert_eq!((registry.len(), hub.subscriber_count()), (2, 2)); + store.set(1); + touch(&hub); + assert_eq!((next_value(&mut a).await, next_value(&mut b).await), (1, 1)); + assert_eq!(store.executions(), 4); +} + +#[tokio::test(start_paused = true)] +async fn live_executions_never_exceed_the_engine_bound() { + let (hub, registry, store) = (ChangeHub::new(), registry(2), Store::default()); + let gate = Arc::new(Semaphore::new(0)); + let readers = ["a", "b", "c", "d", "e"].map(|key| { + let mut stream = follow_read( + ®istry, + &hub, + key, + Counted { + store: store.clone(), + gate: Some(Arc::clone(&gate)), + resumable: false, + }, + ); + tokio::spawn(async move { next_value(&mut stream).await }) + }); + settle().await; + assert_eq!( + store.in_flight.load(Ordering::SeqCst), + 2, + "two run, three wait" + ); + assert_eq!(store.executions(), 2); + for released in 1..=5 { + gate.add_permits(1); + settle().await; + assert!(store.in_flight.load(Ordering::SeqCst) <= 2); + assert_eq!(store.executions(), (released + 2).min(5)); + } + for reader in readers { + assert_eq!(reader.await.unwrap(), 0); + } + assert_eq!(store.max_in_flight.load(Ordering::SeqCst), 2); +} + +#[tokio::test(start_paused = true)] +async fn the_last_subscriber_leaving_tears_the_entry_down() { + let (hub, registry, store) = (ChangeHub::new(), registry(8), Store::default()); + let mut first = follow(®istry, &hub, "q", &store); + let mut second = follow(®istry, &hub, "q", &store); + assert_eq!( + (next_value(&mut first).await, next_value(&mut second).await), + (0, 0) + ); + + drop(first); + settle().await; + assert_eq!((registry.len(), hub.subscriber_count()), (1, 1)); + + drop(second); + settle().await; + assert_eq!((registry.len(), hub.subscriber_count()), (0, 0)); + let executions = store.executions(); + touch(&hub); + settle().await; + assert_eq!(store.executions(), executions, "no work after teardown"); + + // The key is free again: a new subscriber creates a fresh entry. + let mut again = follow(®istry, &hub, "q", &store); + assert_eq!(next_value(&mut again).await, 0); + assert_eq!(registry.len(), 1); +} + +#[tokio::test(start_paused = true)] +async fn a_slow_subscriber_skips_to_the_latest_frame_without_stalling_others() { + let (hub, registry, store) = (ChangeHub::new(), registry(8), Store::default()); + let mut fast = follow(®istry, &hub, "q", &store); + let mut slow = follow(®istry, &hub, "q", &store); + assert_eq!( + (next_value(&mut fast).await, next_value(&mut slow).await), + (0, 0) + ); + for data in 1..=3 { + store.set(data); + touch(&hub); + assert_eq!(next_value(&mut fast).await, data); + } + assert_eq!(store.executions(), 2 + 3); + // Snapshot frames need no replay: the slow subscriber takes the latest. + assert_eq!(next_value(&mut slow).await, 3); + assert_eq!(store.executions(), 5); + assert!(slow.next().now_or_never().is_none()); +} + +#[tokio::test(start_paused = true)] +async fn a_subscriber_that_skipped_a_resumable_frame_catches_up_from_its_own_cursor() { + let (hub, registry, store) = (ChangeHub::new(), registry(8), Store::default()); + let read = || Counted { + store: store.clone(), + gate: None, + resumable: true, + }; + let mut fast = follow_read(®istry, &hub, "q", read()); + let mut slow = follow_read(®istry, &hub, "q", read()); + assert_eq!( + (next_value(&mut fast).await, next_value(&mut slow).await), + (0, 0) + ); + for data in 1..=2 { + store.set(data); + touch(&hub); + assert_eq!(next_value(&mut fast).await, data); + } + assert_eq!(store.executions(), 4); + // The latest frame replays from 1; the slow subscriber stands at 0. + assert_eq!(next_value(&mut slow).await, 2); + assert_eq!(store.executions(), 5, "one catch-up execution"); + + // Both now stand where the producer does: the next frame is shared. + store.set(3); + touch(&hub); + assert_eq!( + (next_value(&mut fast).await, next_value(&mut slow).await), + (3, 3) + ); + assert_eq!(store.executions(), 6); +} + +#[tokio::test(start_paused = true)] +async fn a_failed_shared_execution_ends_every_subscriber_and_the_entry() { + let (hub, registry, store) = (ChangeHub::new(), registry(8), Store::default()); + let mut first = follow(®istry, &hub, "q", &store); + let mut second = follow(®istry, &hub, "q", &store); + assert_eq!( + (next_value(&mut first).await, next_value(&mut second).await), + (0, 0) + ); + + store.fail.store(true, Ordering::SeqCst); + touch(&hub); + for stream in [&mut first, &mut second] { + assert!(stream.next().await.expect("failure frame").is_err()); + assert!(stream.next().await.is_none(), "a failure is terminal"); + } + assert_eq!((registry.len(), hub.subscriber_count()), (0, 0)); + + store.fail.store(false, Ordering::SeqCst); + let mut fresh = follow(®istry, &hub, "q", &store); + assert_eq!(next_value(&mut fresh).await, 0); +} + +#[tokio::test(start_paused = true)] +async fn a_closed_hub_ends_every_subscriber() { + let (registry, store) = (registry(8), Store::default()); + let hub = ChangeHub::new(); + let mut stream = follow(®istry, &hub, "q", &store); + assert_eq!(next_value(&mut stream).await, 0); + drop(hub); + assert!(stream.next().await.is_none()); + assert_eq!(registry.len(), 0); +} diff --git a/tests/gateway-worker/load-runtime.mjs b/tests/gateway-worker/load-runtime.mjs index 01ab6802..85e8f41f 100644 --- a/tests/gateway-worker/load-runtime.mjs +++ b/tests/gateway-worker/load-runtime.mjs @@ -113,21 +113,23 @@ async function modeRun(host,mode,runtime){ } try{ const consumers=[]; - // Sequential admission makes steady-state producer count deterministic; - // all100 remain concurrently subscribed during the measured commit fanout. + // Sequential admission makes the steady-state upstream count deterministic; + // all 100 remain concurrently subscribed during the measured commit fanout. + // Gateway live sharing decides how many subscriptions reach the origin; the + // origin then shares identical reads, so it runs one producer either way. for(let index=0;index<100;index++)consumers.push(await connect(String(index))); - const producerCount=(await metrics()).producers; - assert.equal(producerCount,mode==='live'?1:100); + const {subscribers:upstreamCount,producers:producerCount}=await metrics(); + assert.equal(upstreamCount,mode==='live'?1:100);assert.equal(producerCount,1); const initial=consumers[0].frames[0];for(const consumer of consumers)assert.deepEqual(consumer.frames[0],initial); const commitStart=performance.now(),title=await advance(); await until(()=>consumers.every(consumer=>consumer.frames.some(frame=>frame.data?.causal_query_views?.[0]?.title.startsWith(title))),'100 commit deliveries'); const fanoutMs=performance.now()-commitStart; - const liveReport={logicalSubscriptions:100,upstreamProducers:producerCount,origin:difference(await metrics(),liveBefore),wire:difference(snapshots(),liveBytes),clientFrameBytes:receivedBytes,initialLatencyMs:latency(consumers.map(consumer=>consumer.ms)),commitFanoutMs:fanoutMs}; + const liveReport={logicalSubscriptions:100,upstreamSubscriptions:upstreamCount,originProducers:producerCount,origin:difference(await metrics(),liveBefore),wire:difference(snapshots(),liveBytes),clientFrameBytes:receivedBytes,initialLatencyMs:latency(consumers.map(consumer=>consumer.ms)),commitFanoutMs:fanoutMs}; const bob=await connect('bob','bob');assert.notEqual(bob.frames[0].extensions.distributed.cacheScope,initial.extensions.distributed.cacheScope); - assert.equal((await metrics()).producers,producerCount+1);bob.cancel(); - await until(async()=>(await metrics()).producers===producerCount,'subject control teardown'); + const withBob=await metrics();assert.equal(withBob.subscribers,upstreamCount+1);assert.equal(withBob.producers,producerCount+1);bob.cancel(); + await until(async()=>(await metrics()).subscribers===upstreamCount,'subject control teardown'); for(const consumer of consumers)consumer.cancel(); - await until(async()=>(await metrics()).producers===0,'last subscriber teardown'); + await until(async()=>{const m=await metrics();return m.subscribers===0&&m.producers===0;},'last subscriber teardown'); const recoveryBefore=await metrics(),recoveryBytes=snapshots(),recoveryClientBytes=receivedBytes; let recovery; if(mode==='live'){ @@ -147,7 +149,7 @@ async function modeRun(host,mode,runtime){ recovery={origin:difference(await metrics(),recoveryBefore),wire:difference(snapshots(),recoveryBytes),clientFrameBytes:receivedBytes-recoveryClientBytes,cursorResets:1,slowClientResets:host==='workerd'?1:0}; } report.rows.push({host,mode,recovery,query:queryReport,live:liveReport,decisions:await counts(),subjectControls:'query and live scope differ; separate producer',invalidation:'new projection returned; old cache envelope rejected'}); - console.log(`PASS ${host}/${mode}: 100 queries -> ${queryWork.resultExecutions} result SQL; 100 live -> ${producerCount} producers; measured origin and client bytes`); + console.log(`PASS ${host}/${mode}: 100 queries -> ${queryWork.resultExecutions} result SQL; 100 live -> ${upstreamCount} origin subscriptions, ${producerCount} producer; measured origin and client bytes`); }finally{for(const socket of clients)socket.terminate();} } try{ diff --git a/tests/graphql_query_protocol/load.rs b/tests/graphql_query_protocol/load.rs index cc4d1a39..d76a80f5 100644 --- a/tests/graphql_query_protocol/load.rs +++ b/tests/graphql_query_protocol/load.rs @@ -88,7 +88,7 @@ async fn separate_origin_and_client_savings() { let repository = fixture.repository.clone(); let bus = fixture.bus.clone(); let control = Router::new() - .route("/__metrics", get(move || {let engine=observed.clone();let versions=counters.clone();async move {let m=versions.metrics();axum::Json(json!({"producers":engine.live_subscriber_count(),"validations":m.validations,"resultExecutions":m.result_executions}))}})) + .route("/__metrics", get(move || {let engine=observed.clone();let versions=counters.clone();async move {let m=versions.metrics();axum::Json(json!({"subscribers":engine.live_subscriber_count(),"producers":engine.live_producer_count(),"validations":m.validations,"resultExecutions":m.result_executions}))}})) .route("/__block", post(move || {let gate=gate.clone();async move {gate.forget_permits(gate.available_permits());"blocked"}})) .route("/__release", post(move || {let gate=release.clone();async move {gate.add_permits(10000);"released"}})) .route("/__next/{position}",post(move |axum::extract::Path(position):axum::extract::Path| {let repository=repository.clone();let bus=bus.clone();async move {project_item(&repository,&bus,position,&format!("load-{position}-{}","x".repeat(4096))).await;"committed"}})); diff --git a/tests/graphql_query_protocol/main.rs b/tests/graphql_query_protocol/main.rs index 64d153dd..b1557002 100644 --- a/tests/graphql_query_protocol/main.rs +++ b/tests/graphql_query_protocol/main.rs @@ -2227,6 +2227,74 @@ pub async fn hundred_reads_one_execution_with_cache_disabled(db: Db) { assert_eq!(delivery.flight_counts(), (0, 0)); } +/// A hundred origin subscribers to one query, with no gateway sharing in +/// front: each opens with its own read, then every change costs the origin +/// one execution, fanned out to all of them. +#[cfg(feature = "gateway")] +pub async fn hundred_origin_subscribers_share_one_execution_per_change(db: Db) { + use distributed::graphql::delivery::GatewayVersionStore; + let fixture = protocol_fixture_with_retention(db, 10).await; + // The store counts result executions; it changes nothing about them. + let versions = GatewayVersionStore::install( + &fixture.repository.graphql_pool(), + "live-sharing", + ["causal_query_views".into()], + ) + .await + .unwrap(); + let engine = GraphqlEngine::builder(fixture.repository.pool()) + .identity(IdentityConfig::dev_headers()) + .service_id(SERVICE_ID) + .protocol_token_key(TEST_PROTOCOL_TOKEN_KEY) + .roles(&["user"]) + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .client_projectors([projector()]) + .change_stream(fixture.repository.read_model_changes()) + .gateway_versions(versions.clone()) + .build() + .unwrap(); + let mut streams = (0..100) + .map(|_| engine.execute_stream(&user_session(), Request::new(LIVE_SUBSCRIPTION))) + .collect::>(); + for stream in &mut streams { + let frame = next_wire_frame(stream).await; + assert_live_frame(&frame, "causal_query_views", "causal row", "1", false); + } + let opened = versions.metrics().result_executions; + let producers = engine.live_producer_count(); + assert_eq!(engine.live_subscriber_count(), 100, "every stream is counted"); + + project_item(&fixture.repository, &fixture.bus, 2, "causal row 2").await; + let mut first = None; + for stream in &mut streams { + let frame = next_wire_frame(stream).await; + assert_live_frame(&frame, "causal_query_views", "causal row 2", "2", false); + match &first { + None => first = Some(frame), + Some(first) => assert_eq!(&frame, first, "one result, fanned out"), + } + } + let refreshed = versions.metrics().result_executions - opened; + eprintln!( + "100 origin subscribers: {producers} producers, {opened} executions to open, {refreshed} per change" + ); + assert_eq!(producers, 1, "one shared producer"); + assert_eq!(opened, 100, "each subscriber opens with its own read"); + assert_eq!( + refreshed, 1, + "one execution per change, not one per subscriber" + ); + + drop(streams); + tokio::time::timeout(Duration::from_secs(5), async { + while engine.live_producer_count() != 0 { + tokio::task::yield_now().await; + } + }) + .await + .expect("the last subscriber tears the shared producer down"); +} + #[cfg(feature = "gateway-graphql-native")] pub async fn hundred_subscribers_one_upstream_over_embedded_websockets(db: Db) { hundred_subscribers_one_upstream(db, false).await; @@ -2439,7 +2507,7 @@ async fn hundred_subscribers_one_upstream(db: Db, remote: bool) { (delivery.live_counts().0, delivery.live_counts().1), (1, 100) ); - assert_eq!(engine.live_subscriber_count(), 1); + assert_eq!(engine.live_producer_count(), 1); assert_eq!(versions.metrics().validations, 100); assert_eq!( versions.metrics().result_executions, @@ -2462,7 +2530,7 @@ async fn hundred_subscribers_one_upstream(db: Db, remote: bool) { bob_frame["extensions"]["distributed"]["cacheScope"] ); assert_eq!( - (delivery.live_counts().0, engine.live_subscriber_count()), + (delivery.live_counts().0, engine.live_producer_count()), (2, 2), "identical roles/data must not cross subject scopes" ); @@ -2488,7 +2556,7 @@ async fn hundred_subscribers_one_upstream(db: Db, remote: bool) { let replay = next(&mut resumed, "legacy-resume", "committed-live").await; assert_eq!(replay["extensions"]["distributed"]["live"]["reset"], false); tokio::time::timeout(Duration::from_secs(5), async { - while delivery.live_counts().0 != 1 || engine.live_subscriber_count() != 1 { + while delivery.live_counts().0 != 1 || engine.live_producer_count() != 1 { tokio::time::sleep(Duration::from_millis(5)).await; } }) @@ -2514,7 +2582,7 @@ async fn hundred_subscribers_one_upstream(db: Db, remote: bool) { .await .unwrap(); assert_eq!( - engine.live_subscriber_count(), + engine.live_producer_count(), 1, "remaining resumed client retains upstream ownership" ); @@ -2528,7 +2596,7 @@ async fn hundred_subscribers_one_upstream(db: Db, remote: bool) { .unwrap(); let _ = resumed.close(None).await; tokio::time::timeout(Duration::from_secs(5), async { - while delivery.live_counts().0 != 0 || engine.live_subscriber_count() != 0 { + while delivery.live_counts().0 != 0 || engine.live_producer_count() != 0 { tokio::time::sleep(Duration::from_millis(5)).await; } }) @@ -2672,7 +2740,7 @@ async fn worker_live_coordinator_uses_actual_oidc_origin() { let router = distributed::graphql::graphql_router_composed(engine.clone(), None, None); let repository = fixture.repository.clone(); let bus = fixture.bus.clone(); - let control=Router::new().route("/__metrics",axum::routing::get(move ||{let engine=engine.clone();let versions=versions.clone();async move{let metrics=versions.metrics();axum::Json(json!({"producers":engine.live_subscriber_count(),"validations":metrics.validations,"resultExecutions":metrics.result_executions}))}})) + let control=Router::new().route("/__metrics",axum::routing::get(move ||{let engine=engine.clone();let versions=versions.clone();async move{let metrics=versions.metrics();axum::Json(json!({"subscribers":engine.live_subscriber_count(),"producers":engine.live_producer_count(),"validations":metrics.validations,"resultExecutions":metrics.result_executions}))}})) .route("/__commit",axum::routing::post(move ||{let repository=repository.clone();let bus=bus.clone();async move{project_item(&repository,&bus,2,"worker committed").await;"committed"}})); let next_repository = fixture.repository.clone(); let next_bus = fixture.bus.clone(); @@ -2744,6 +2812,8 @@ on_each_dialect! { ; native_snapshot_cache_revalidates_each_consumer_without_result_sql, #[cfg(feature = "gateway-graphql-native")] hundred_reads_one_execution_with_cache_disabled, + #[cfg(feature = "gateway")] + hundred_origin_subscribers_share_one_execution_per_change, #[cfg(feature = "gateway-graphql-native")] hundred_subscribers_one_upstream_over_embedded_websockets, #[cfg(feature = "gateway-graphql-native")] diff --git a/tests/graphql_subscriptions_sqlite/main.rs b/tests/graphql_subscriptions_sqlite/main.rs index 8f9d02be..1cc5620e 100644 --- a/tests/graphql_subscriptions_sqlite/main.rs +++ b/tests/graphql_subscriptions_sqlite/main.rs @@ -349,3 +349,84 @@ async fn subscription_claim_isolation_across_tenants() { assert_eq!(notes_b2[0]["owner_id"], "tenant-b"); } } + +/// Live sharing keys on the compiled SQL and every bind: two sessions whose +/// claims compile to different row-policy binds get separate producers, and +/// two sessions with the same claims share one. +#[tokio::test] +async fn sessions_share_a_live_producer_only_when_their_binds_match() { + use distributed::ReadModel; + use serde::{Deserialize, Serialize}; + + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] + #[table("notes")] + struct NoteView { + #[id("note_id")] + note_id: String, + owner_id: String, + body: String, + } + + let repo = distributed::SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .unwrap(); + Db::Sqlite(repo.clone()) + .seed( + [("n-a1", "tenant-a", "a1"), ("n-b1", "tenant-b", "b1")].map( + |(note_id, owner_id, body)| NoteView { + note_id: note_id.into(), + owner_id: owner_id.into(), + body: body.into(), + }, + ), + ) + .await; + let engine = GraphqlEngine::builder(repo.pool().clone()) + .identity(IdentityConfig::dev_headers()) + .roles(&["user"]) + .model::( + ModelPermissions::new().grant( + "user", + read() + .all_columns() + .rows(col("owner_id").eq(claim("x-user-id"))), + ), + ) + .change_stream(repo.read_model_changes()) + .build() + .expect("build"); + let tenant = |tenant: &str| { + let mut session = Session::new(); + session.set(ROLE_KEY, "user"); + session.set(USER_ID_KEY, tenant); + session + }; + let document = r#"subscription { notes { note_id owner_id body } }"#; + let open = |tenant: Session| { + let mut stream = Box::pin(engine.execute_stream(&tenant, Request::new(document))); + async move { + let first = stream.next().await.expect("first frame"); + assert!(!first.is_err(), "{:?}", first.errors); + (stream, serde_json::to_value(&first.data).unwrap()) + } + }; + + let (_a, data_a) = open(tenant("tenant-a")).await; + let (_b, data_b) = open(tenant("tenant-b")).await; + assert_eq!(data_a["notes"][0]["owner_id"], "tenant-a"); + assert_eq!(data_b["notes"][0]["owner_id"], "tenant-b"); + assert_eq!( + engine.live_producer_count(), + 2, + "different claim binds must never share a producer" + ); + + let (_a2, data_a2) = open(tenant("tenant-a")).await; + assert_eq!(data_a2, data_a); + assert_eq!( + engine.live_producer_count(), + 2, + "identical SQL and binds share the tenant's producer" + ); + assert_eq!(engine.live_subscriber_count(), 3, "every stream is counted"); +}