Skip to main content

reddb_server/wire/redwire/
session.rs

1//! Per-connection RedWire session: handshake → frame loop → bye.
2//!
3//! Dispatches the full RedWire frame set:
4//!   - Hello / AuthResponse (handshake only — once)
5//!   - Query / BulkInsert / TypedInsert / Get / Delete (data plane)
6//!   - QueryBinary / BulkInsertBinary / BulkInsertPrevalidated
7//!     (binary fast paths)
8//!   - BulkStreamStart/Rows/Commit (streaming bulk)
9//!   - Prepare / ExecutePrepared (prepared statements)
10//!   - Ping / Pong / Bye (lifecycle)
11
12use std::io;
13use std::sync::Arc;
14
15use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
16use tokio::sync::mpsc;
17
18use crate::application::{OperationContext, OperationContextFactory, OperationContextInput};
19use crate::auth::store::AuthStore;
20use crate::auth::Role;
21use crate::runtime::query_request::{
22    ParamValue, PreparedRegistry, QueryRequest, QueryRequestExecutor,
23};
24use crate::runtime::RedDBRuntime;
25use crate::serde_json::{self, Value as JsonValue};
26use reddb_wire::query_with_params::{
27    decode_query_with_params_request, ParamValue as RedWireParamValue, FEATURE_PARAMS,
28};
29use reddb_wire::redwire::operations::{
30    decode_delete_payload, decode_get_payload, decode_insert_dispatch_payload,
31    encode_bulk_ok_payload_from_json_id_literals, encode_delete_ok_payload,
32    encode_get_result_payload,
33};
34use reddb_wire::redwire::scram::{ScramServerHandshake, ScramServerInput, ScramServerOutput};
35use reddb_wire::redwire::{decode_typed_insert, FEATURE_TYPED_MUTATIONS};
36
37use super::auth::{build_auth_ok, pick_auth_method, validate_auth_response, AuthOutcome};
38use super::validate_minor_version;
39use reddb_wire::redwire::handshake::{
40    build_auth_fail_payload, build_auth_ok_frame_from_payload, build_hello_ack_frame,
41    expect_auth_response_payload, parse_auth_response_oauth_jwt, Hello,
42};
43use reddb_wire::redwire::{
44    build_dispatch_reply_frame, build_error_frame_lossy, build_reply_frame,
45    choose_hello_minor_version, decode_frame, encode_frame, read_frame_async,
46    rewrap_length_prefixed_handler_response, Frame, MessageDirection, MessageKind, REDWIRE_MAGIC,
47};
48
49enum QueryResponse {
50    Frame(Frame),
51    Legacy(crate::wire::listener::LegacyQueryResponse, u64),
52}
53
54struct AuthedSession {
55    username: String,
56    role: Role,
57    tenant: Option<String>,
58    session_id: String,
59    _lease: Option<crate::auth::store::ConnectionLease>,
60}
61
62fn acquire_local_connection_lease(
63    auth_store: Option<&Arc<AuthStore>>,
64    tenant: Option<&str>,
65    username: &str,
66) -> Result<Option<crate::auth::store::ConnectionLease>, String> {
67    let Some(store) = auth_store else {
68        return Ok(None);
69    };
70    let principal = crate::auth::UserId::from_parts(tenant, username);
71    if store.get_user(tenant, username).is_none() {
72        return Ok(None);
73    }
74    store
75        .acquire_connection_lease(&principal)
76        .map(Some)
77        .map_err(|_| "authentication refused".to_string())
78}
79
80async fn send_auth_refusal<S>(stream: &mut S, correlation_id: u64, reason: &str) -> io::Result<()>
81where
82    S: AsyncWrite + Unpin,
83{
84    let frame = encode_frame(&reply_frame_or_io_error(
85        correlation_id,
86        MessageKind::AuthFail,
87        build_auth_fail_payload(reason),
88    )?);
89    stream.write_all(&frame).await
90}
91
92struct RedWireAuthenticatedSessionPolicy;
93
94impl crate::server::route_catalog::CommandPolicyEngine for RedWireAuthenticatedSessionPolicy {
95    fn allows(
96        &self,
97        _ctx: &OperationContext,
98        _command: &crate::server::route_catalog::CommandSpec,
99    ) -> bool {
100        // Reaching the frame loop means the RedWire handshake accepted this
101        // session (including explicitly configured anonymous sessions). The
102        // catalog authorizer still owns command lookup and the mandatory
103        // authorization consult, while this adapter preserves the handshake's
104        // existing credential decision.
105        true
106    }
107}
108
109fn redwire_operation_context(
110    session: &AuthedSession,
111    connection_id: u64,
112    correlation_id: u64,
113) -> OperationContext {
114    OperationContextFactory::build(OperationContextInput {
115        request_id: Some(format!("redwire-{}-{correlation_id}", session.session_id)),
116        connection_id: Some(connection_id),
117        principal: Some(session.username.clone()),
118        tenant: session.tenant.clone(),
119        ..OperationContextInput::default()
120    })
121}
122
123fn authorize_redwire_frame<P: crate::server::route_catalog::CommandPolicyEngine + ?Sized>(
124    ctx: &OperationContext,
125    kind: MessageKind,
126    policy: &P,
127) -> Result<(), crate::server::route_catalog::CommandAuthorizationError> {
128    let Some(command_id) = redwire_command_id(kind) else {
129        return Ok(());
130    };
131    crate::server::route_catalog::CommandAuthorizer::new(
132        crate::server::discovered_route_catalog(),
133        policy,
134    )
135    .authorize(ctx, command_id)
136}
137
138/// Canonical command id for every RedWire frame kind this server dispatches.
139/// `Hello` and `AuthResponse` are handled by the handshake; the other bound
140/// kinds have real arms in `handle_session`. `None` means the wire vocabulary
141/// declares the kind but this server does not dispatch it.
142pub(crate) const fn redwire_command_id(kind: MessageKind) -> Option<&'static str> {
143    match kind {
144        MessageKind::Hello
145        | MessageKind::HelloAck
146        | MessageKind::AuthRequest
147        | MessageKind::AuthResponse
148        | MessageKind::AuthOk
149        | MessageKind::AuthFail => Some("auth.login"),
150
151        MessageKind::Bye | MessageKind::Ping | MessageKind::Pong => Some("health.live"),
152        MessageKind::Topology => Some("client.topology"),
153
154        MessageKind::Query
155        | MessageKind::Result
156        | MessageKind::Error
157        | MessageKind::QueryBinary
158        | MessageKind::Prepare
159        | MessageKind::PreparedOk
160        | MessageKind::ExecutePrepared
161        | MessageKind::QueryWithParams
162        | MessageKind::QueueWaitOpen
163        | MessageKind::QueueEventPush
164        | MessageKind::QueueWaitTimeout
165        | MessageKind::MovedRedirect
166        | MessageKind::Compress => Some("query.execute"),
167
168        MessageKind::TypedInsert => Some("collections.rows.create"),
169
170        MessageKind::BulkInsert
171        | MessageKind::BulkOk
172        | MessageKind::BulkInsertBinary
173        | MessageKind::BulkInsertPrevalidated
174        | MessageKind::BulkStreamStart
175        | MessageKind::BulkStreamRows
176        | MessageKind::BulkStreamCommit
177        | MessageKind::BulkStreamAck => Some("collections.batch.insert"),
178
179        MessageKind::Get => Some("collections.entities.get"),
180        MessageKind::Delete | MessageKind::DeleteOk => Some("collections.entities.delete"),
181
182        MessageKind::OpenStream
183        | MessageKind::OpenAck
184        | MessageKind::RowDescription
185        | MessageKind::StreamEnd => Some("streams.query.output"),
186        MessageKind::StreamChunk => Some("streams.input"),
187        MessageKind::Cancel | MessageKind::StreamCancel | MessageKind::StreamError => {
188            Some("streams.query.cancel")
189        }
190
191        MessageKind::SetSession
192        | MessageKind::Notice
193        | MessageKind::VectorSearch
194        | MessageKind::GraphTraverse => None,
195    }
196}
197
198struct RedWireExecutionContextGuard {
199    previous_connection_id: u64,
200    previous_tenant: Option<String>,
201    previous_identity: Option<(String, Role)>,
202    previous_principal: Option<crate::auth::UserId>,
203}
204
205impl RedWireExecutionContextGuard {
206    fn install(ctx: &OperationContext, role: Role) -> Self {
207        let previous_connection_id = crate::runtime::execution_context::current_connection_id();
208        if let Some(connection_id) = ctx.connection_id {
209            crate::runtime::execution_context::set_current_connection_id(connection_id);
210        }
211        let previous_tenant = crate::runtime::execution_context::current_tenant();
212        let previous_identity = crate::runtime::execution_context::current_auth_identity();
213        let previous_principal = crate::runtime::execution_context::current_auth_principal();
214        match &ctx.tenant {
215            Some(tenant) => crate::runtime::execution_context::set_current_tenant(tenant.clone()),
216            None => crate::runtime::execution_context::clear_current_tenant(),
217        }
218        // Anonymous sessions exist only when server auth is disabled (the
219        // handshake refuses anonymous otherwise) and historically ran with
220        // NO installed identity — enforcement off. Installing the handshake's
221        // `Read` role here would reject every anonymous write (issue #2149
222        // review). The tenant install above still applies for RLS.
223        if ctx.audit_principal == "anonymous" {
224            crate::runtime::execution_context::clear_current_auth_identity();
225        } else {
226            crate::runtime::execution_context::set_current_auth_principal(
227                crate::auth::UserId::from_parts(ctx.tenant.as_deref(), &ctx.audit_principal),
228                role,
229            );
230        }
231        Self {
232            previous_connection_id,
233            previous_tenant,
234            previous_identity,
235            previous_principal,
236        }
237    }
238}
239
240impl Drop for RedWireExecutionContextGuard {
241    fn drop(&mut self) {
242        crate::runtime::execution_context::set_current_connection_id(self.previous_connection_id);
243        match (
244            self.previous_principal.take(),
245            self.previous_identity.take(),
246        ) {
247            (Some(principal), Some((_, role))) => {
248                crate::runtime::execution_context::set_current_auth_principal(principal, role)
249            }
250            _ => crate::runtime::execution_context::clear_current_auth_identity(),
251        }
252        match self.previous_tenant.take() {
253            Some(tenant) => crate::runtime::execution_context::set_current_tenant(tenant),
254            None => crate::runtime::execution_context::clear_current_tenant(),
255        }
256    }
257}
258
259pub(super) fn execute_with_redwire_context<T>(
260    ctx: &OperationContext,
261    role: Role,
262    execute: impl FnOnce() -> T,
263) -> T {
264    let _guard = RedWireExecutionContextGuard::install(ctx, role);
265    execute()
266}
267
268#[derive(Debug)]
269pub(super) enum RedWireExecutionError {
270    QueueFull,
271    QueueTimeout,
272    Closed,
273    Task(tokio::task::JoinError),
274}
275
276impl RedWireExecutionError {
277    pub(super) fn code(&self) -> &'static str {
278        match self {
279            Self::QueueFull => "execution_queue_full",
280            Self::QueueTimeout => "execution_queue_timeout",
281            Self::Closed => "execution_admission_closed",
282            Self::Task(_) => "execution_task_failed",
283        }
284    }
285
286    pub(super) fn client_message(&self) -> String {
287        match self {
288            Self::QueueFull => {
289                "execution_queue_full: engine execution queue is full; retryable=true".to_string()
290            }
291            Self::QueueTimeout => {
292                "execution_queue_timeout: deadline expired while waiting to execute; retryable=true"
293                    .to_string()
294            }
295            Self::Closed => {
296                "execution_admission_closed: engine execution admission is unavailable".to_string()
297            }
298            Self::Task(error) => format!("engine execution task failed: {error}"),
299        }
300    }
301}
302
303/// Keep RedWire's thread-local identity and transaction context on the
304/// connection thread while allowing Tokio to replace this worker for other
305/// async tasks during synchronous engine work.
306fn run_redwire_blocking<T>(execute: impl FnOnce() -> T) -> T {
307    use tokio::runtime::{Handle, RuntimeFlavor};
308
309    match Handle::try_current().map(|handle| handle.runtime_flavor()) {
310        Ok(RuntimeFlavor::MultiThread) => tokio::task::block_in_place(execute),
311        _ => execute(),
312    }
313}
314
315#[cfg(test)]
316static REDWIRE_TEST_BLOCKING_GATE_CORRELATION: std::sync::atomic::AtomicU64 =
317    std::sync::atomic::AtomicU64::new(0);
318#[cfg(test)]
319static REDWIRE_TEST_BLOCKING_GATE_ENTERED: std::sync::atomic::AtomicU64 =
320    std::sync::atomic::AtomicU64::new(0);
321
322#[cfg(test)]
323fn redwire_test_blocking_gate(correlation_id: u64) {
324    use std::sync::atomic::Ordering;
325
326    if REDWIRE_TEST_BLOCKING_GATE_CORRELATION.load(Ordering::Acquire) != correlation_id {
327        return;
328    }
329    REDWIRE_TEST_BLOCKING_GATE_ENTERED.store(correlation_id, Ordering::Release);
330    while REDWIRE_TEST_BLOCKING_GATE_CORRELATION.load(Ordering::Acquire) == correlation_id
331        && crate::runtime::query_budget::charge(0).is_ok()
332    {
333        std::thread::yield_now();
334    }
335}
336
337pub(super) async fn redwire_spawn_blocking<F, R>(
338    runtime: &RedDBRuntime,
339    execute: F,
340) -> Result<R, RedWireExecutionError>
341where
342    F: FnOnce() -> R + Send + 'static,
343    R: Send + 'static,
344{
345    let permit = redwire_execution_permit(runtime).await?;
346    redwire_spawn_blocking_with_ticket(runtime, permit, None, execute).await
347}
348
349/// Shared-execution dispatch with a watchdog ticket (staging incident
350/// 2026-11-17): a wire execution that outlives `execution_queue_timeout`
351/// degrades `/health/ready` exactly like an HTTP handler that overruns
352/// `handler_timeout`. Without this, a wedged wire worker holds its
353/// admission permit invisibly while probes keep answering ready.
354async fn redwire_spawn_blocking_with_ticket<F, R>(
355    runtime: &RedDBRuntime,
356    permit: crate::transport::execution_admission::ExecutionPermit,
357    cancellation: Option<crate::runtime::query_budget::RequestCancellation>,
358    execute: F,
359) -> Result<R, RedWireExecutionError>
360where
361    F: FnOnce() -> R + Send + 'static,
362    R: Send + 'static,
363{
364    let ticket = runtime.execution_watchdog().start();
365    // Deadline marker runs on its own task: it degrades readiness the moment
366    // a *running* span overruns the deadline. Spans the worker spends
367    // intentionally parked (QUEUE READ … WAIT on an empty queue) suspend the
368    // deadline, which restarts when work resumes — a long-poll is idle by
369    // design, not wedged (staging incident 2026-11-19).
370    let marker = tokio::spawn(crate::runtime::execution_watchdog::enforce_deadline(
371        std::sync::Arc::clone(&ticket),
372        runtime.execution_queue_timeout(),
373    ));
374    let result = redwire_spawn_blocking_with_permit_cancellation(
375        permit,
376        cancellation,
377        Some(ticket),
378        execute,
379    )
380    .await;
381    // The worker settled its ticket; don't leave one sleeping timer per
382    // execution behind until the deadline elapses.
383    marker.abort();
384    result
385}
386
387async fn redwire_execution_permit(
388    runtime: &RedDBRuntime,
389) -> Result<crate::transport::execution_admission::ExecutionPermit, RedWireExecutionError> {
390    use crate::transport::execution_admission::ExecutionAdmissionError;
391
392    let admission = runtime.execution_admission();
393    match tokio::time::timeout(runtime.execution_queue_timeout(), admission.acquire()).await {
394        Ok(Ok(permit)) => Ok(permit),
395        Ok(Err(ExecutionAdmissionError::QueueFull)) => Err(RedWireExecutionError::QueueFull),
396        Ok(Err(ExecutionAdmissionError::Closed)) => Err(RedWireExecutionError::Closed),
397        Err(_) => Err(RedWireExecutionError::QueueTimeout),
398    }
399}
400
401pub(super) async fn redwire_spawn_blocking_with_permit<F, R>(
402    runtime: &RedDBRuntime,
403    permit: crate::transport::execution_admission::ExecutionPermit,
404    execute: F,
405) -> Result<R, RedWireExecutionError>
406where
407    F: FnOnce() -> R + Send + 'static,
408    R: Send + 'static,
409{
410    redwire_spawn_blocking_with_ticket(runtime, permit, None, execute).await
411}
412
413async fn redwire_spawn_blocking_with_permit_cancellation<F, R>(
414    permit: crate::transport::execution_admission::ExecutionPermit,
415    cancellation: Option<crate::runtime::query_budget::RequestCancellation>,
416    ticket: Option<std::sync::Arc<crate::runtime::execution_watchdog::ExecutionTicket>>,
417    execute: F,
418) -> Result<R, RedWireExecutionError>
419where
420    F: FnOnce() -> R + Send + 'static,
421    R: Send + 'static,
422{
423    // Worker-owned completion: created before the spawn so a closure that is
424    // dropped unrun still settles the ticket, and recorded only when the
425    // engine work itself ends — not when the session future goes away.
426    let completion = ticket.as_ref().map(|ticket| ticket.completion());
427    tokio::task::spawn_blocking(move || {
428        let _permit = permit;
429        let _completion = completion;
430        let _ticket_scope = ticket.as_ref().map(|ticket| ticket.install());
431        let _cancellation_scope = cancellation.map(|cancellation| cancellation.install());
432        execute()
433    })
434    .await
435    .map_err(RedWireExecutionError::Task)
436}
437
438async fn send_execution_error(
439    out_tx: &super::output_stream::FrameTx,
440    correlation_id: u64,
441    error: RedWireExecutionError,
442) -> io::Result<()> {
443    queue_send(
444        out_tx,
445        build_error_frame_lossy(correlation_id, &error.client_message()),
446    )
447    .await
448}
449
450pub async fn handle_session<S>(
451    mut stream: S,
452    runtime: Arc<RedDBRuntime>,
453    auth_store: Option<Arc<AuthStore>>,
454    oauth: Option<Arc<crate::auth::oauth::OAuthValidator>>,
455) -> io::Result<()>
456where
457    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
458{
459    // Discriminator byte was already consumed by the service-router
460    // detector when it dispatched here. If callers wire this from
461    // a non-router path they must consume it themselves first.
462    let session = perform_handshake(
463        &mut stream,
464        runtime.as_ref(),
465        auth_store.as_ref(),
466        oauth.as_deref(),
467    )
468    .await?;
469    if session.is_none() {
470        return Ok(());
471    }
472    let session = session.unwrap();
473    // Own the runtime lease through EOF/Bye/error so teardown rolls back
474    // this connection's transaction before its ID can be reused.
475    let connection = Arc::new(
476        runtime
477            .acquire_wire_connection()
478            .map_err(|error| io::Error::other(error.to_string()))?,
479    );
480
481    // Per-connection state for prepared statements + streaming
482    // bulk inserts. Owned by the session; dropped on disconnect. The
483    // prepared registry inside `prepared_stmts` is also the Request
484    // module's execution scope for this connection's queries.
485    let mut stream_session: Option<crate::wire::listener::BulkStreamSession> = None;
486    let mut prepared_stmts = crate::wire::listener::PreparedStatements::default();
487
488    // After handshake, split the socket so reads and writes are
489    // independent: this is what makes RedWire multiplex (PRD #759
490    // S3) — two concurrent output-stream workers can interleave
491    // their chunks back to the client without contending on the
492    // reader side. All outbound bytes are routed through an
493    // bounded, byte-admitted mpsc; one drain task writes complete frames.
494    let (mut reader, writer) = tokio::io::split(stream);
495    let (out_tx, out_rx) = mpsc::channel::<bytes::Bytes>(OUTBOUND_QUEUE_FRAMES);
496    let out_tx = super::output_stream::FrameTx::new(out_tx, Arc::clone(&runtime));
497    let _writer_task = out_tx.spawn_writer(out_rx, writer);
498
499    // Keep reading independently of synchronous engine execution. Otherwise
500    // EOF cannot be observed while this task awaits `spawn_blocking`, so a
501    // disconnected client can strand the worker and its execution permit.
502    let session_cancellation = crate::runtime::query_budget::RequestCancellation::new();
503    let reader_cancellation = session_cancellation.clone();
504    let (incoming_tx, mut incoming_rx) =
505        mpsc::channel::<Result<Frame, reddb_wire::redwire::RedWireIoError>>(INBOUND_QUEUE_FRAMES);
506    let mut reader_tasks = tokio::task::JoinSet::new();
507    reader_tasks.spawn(async move {
508        loop {
509            let incoming = read_frame_async(&mut reader).await;
510            let terminal = incoming.is_err();
511            if terminal {
512                reader_cancellation.cancel();
513            }
514            if incoming_tx.send(incoming).await.is_err() || terminal {
515                return;
516            }
517        }
518    });
519
520    // Per-connection output-stream registry (issue #762). Tracks
521    // active stream workers so a `StreamCancel` for one stream_id
522    // does not disturb the rest of the connection.
523    let stream_registry = Arc::new(super::output_stream::StreamRegistry::new());
524    let mut output_stream_tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
525
526    // Per-connection input-stream registry (issue #764 / S5). Input
527    // streams are driven inline from this reader loop — each
528    // `StreamChunk` commits synchronously — so the registry is a plain
529    // owned map rather than the `Arc<Mutex<…>>` the spawned output
530    // workers share. Output and input streams are keyed by `stream_id`
531    // in separate registries, so the two multiplex on one connection
532    // without colliding (AC #2).
533    let mut input_registry = super::input_stream::InputStreamRegistry::new();
534
535    // In-flight live queue-wait tasks (issue #920). Unlike the
536    // output-stream workers — which notice a closed connection the
537    // instant they try to push and self-terminate — a queue-wait task
538    // parks on the registry's async wake head and would otherwise linger
539    // until its `wait_ms` deadline after the client disconnects, holding
540    // a registry slot reference and a tokio worker the whole time. Owning
541    // the tasks in a `JoinSet` scoped to this connection fixes that: when
542    // the frame loop returns (Bye / EOF / I/O error), the set is dropped
543    // and every still-parked wait is aborted, dropping its waiter and so
544    // releasing the slot reference promptly (AC #1, AC #3). The
545    // registry's own `cancel_all` still drives the server-shutdown path
546    // (AC #2/#4) independently of this connection-scoped abort.
547    let mut queue_wait_tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
548
549    loop {
550        while output_stream_tasks.try_join_next().is_some() {}
551        // Reap finished wait tasks so the set does not accumulate joined
552        // handles over a long-lived connection. Non-blocking — only
553        // already-complete tasks are drained.
554        while queue_wait_tasks.try_join_next().is_some() {}
555
556        let incoming = tokio::select! {
557            _ = out_tx.failed() => return Err(io::Error::other("redwire: outbound response unavailable")),
558            frame = incoming_rx.recv() => match frame {
559                Some(frame) => frame,
560                None => return Err(io::Error::other("redwire: inbound frame reader unavailable")),
561            },
562        };
563        let frame = match incoming {
564            Ok(frame) => frame,
565            Err(reddb_wire::redwire::RedWireIoError::Io(err))
566                if err.kind() == io::ErrorKind::UnexpectedEof =>
567            {
568                return Ok(())
569            }
570            Err(err) => return Err(redwire_io_err(err)),
571        };
572
573        let operation_context =
574            redwire_operation_context(&session, connection.id(), frame.correlation_id);
575        if let Err(error) = authorize_redwire_frame(
576            &operation_context,
577            frame.kind,
578            &RedWireAuthenticatedSessionPolicy,
579        ) {
580            let err_frame = build_error_frame_lossy(frame.correlation_id, &error.to_string());
581            queue_send(&out_tx, err_frame).await?;
582            continue;
583        }
584
585        // Catalog-driven direction gate: server-only kinds (PreparedOk,
586        // AuthOk/Fail, BulkOk, …) must never arrive *from* a client.
587        // The catalog (`MessageKind::direction`) is the single source
588        // of truth — see `frame.rs::catalog_tests::direction_matrix_is_pinned`.
589        if frame.kind.direction() == MessageDirection::ServerToClient {
590            let err_frame = build_error_frame_lossy(
591                frame.correlation_id,
592                &format!("redwire: {:?} is server-only", frame.kind),
593            );
594            queue_send(&out_tx, err_frame).await?;
595            continue;
596        }
597
598        match frame.kind {
599            MessageKind::Topology => {
600                let protocol = std::str::from_utf8(&frame.payload).unwrap_or("");
601                if !reddb_wire::routing::ROUTING_PROTOCOLS.contains(&protocol) {
602                    queue_send(
603                        &out_tx,
604                        build_error_frame_lossy(
605                            frame.correlation_id,
606                            "unsupported topology transport",
607                        ),
608                    )
609                    .await?;
610                    continue;
611                }
612                let auth = if session.username == "anonymous" {
613                    crate::auth::middleware::AuthResult::Anonymous
614                } else {
615                    crate::auth::middleware::AuthResult::password_principal(
616                        crate::auth::UserId::from_parts(
617                            session.tenant.as_deref(),
618                            &session.username,
619                        ),
620                        session.role,
621                    )
622                };
623                let topology = runtime.client_topology(protocol, &auth);
624                let response = reply_frame_or_io_error(
625                    frame.correlation_id,
626                    MessageKind::Result,
627                    reddb_wire::encode_topology(&topology),
628                )?;
629                queue_send(&out_tx, response).await?;
630            }
631            MessageKind::Bye => {
632                let bye = reply_frame_or_io_error(frame.correlation_id, MessageKind::Bye, vec![])?;
633                let _ = out_tx.send_frame(bye).await;
634                return Ok(());
635            }
636            MessageKind::Ping => {
637                let pong =
638                    reply_frame_or_io_error(frame.correlation_id, MessageKind::Pong, vec![])?;
639                queue_send(&out_tx, pong).await?;
640            }
641            MessageKind::Query
642            | MessageKind::QueryWithParams
643            | MessageKind::QueryBinary
644            | MessageKind::ExecutePrepared => {
645                // The synchronous engine can park on QUEUE READ WAIT. Keep
646                // it off Tokio's I/O workers, and install its thread-local
647                // security/transaction context on the blocking worker itself.
648                let permit = match redwire_execution_permit(runtime.as_ref()).await {
649                    Ok(permit) => permit,
650                    Err(error) => {
651                        send_execution_error(&out_tx, frame.correlation_id, error).await?;
652                        continue;
653                    }
654                };
655                let task_runtime = Arc::clone(&runtime);
656                let connection = Arc::clone(&connection);
657                let statements = std::mem::take(&mut prepared_stmts);
658                let role = session.role;
659                let correlation_id = frame.correlation_id;
660                let cancellation = matches!(
661                    frame.kind,
662                    MessageKind::Query | MessageKind::QueryWithParams
663                )
664                .then(|| session_cancellation.clone());
665                let result = redwire_spawn_blocking_with_ticket(
666                    runtime.as_ref(),
667                    permit,
668                    cancellation,
669                    move || {
670                        #[cfg(test)]
671                        redwire_test_blocking_gate(correlation_id);
672                        // A started blocking task cannot be aborted. Retain the
673                        // lease until execution ends, even if the session is dropped.
674                        let _connection = connection;
675                        let response =
676                            execute_with_redwire_context(&operation_context, role, || match frame
677                                .kind
678                            {
679                                MessageKind::Query => QueryResponse::Frame(run_query(
680                                    &task_runtime,
681                                    statements.registry(),
682                                    &frame,
683                                )),
684                                MessageKind::QueryWithParams => {
685                                    QueryResponse::Frame(run_query_with_params(
686                                        &task_runtime,
687                                        statements.registry(),
688                                        &frame,
689                                    ))
690                                }
691                                MessageKind::QueryBinary => QueryResponse::Legacy(
692                                    crate::wire::listener::handle_query_binary(
693                                        &task_runtime,
694                                        &frame.payload,
695                                    ),
696                                    frame.correlation_id,
697                                ),
698                                MessageKind::ExecutePrepared => QueryResponse::Legacy(
699                                    crate::wire::listener::handle_execute_prepared(
700                                        &task_runtime,
701                                        &frame.payload,
702                                        &statements,
703                                    ),
704                                    frame.correlation_id,
705                                ),
706                                _ => {
707                                    unreachable!("only query frames enter the blocking dispatcher")
708                                }
709                            });
710                        (response, statements)
711                    },
712                )
713                .await;
714                let (response, statements) = match result {
715                    Ok(result) => result,
716                    Err(error) => {
717                        send_execution_error(&out_tx, correlation_id, error).await?;
718                        prepared_stmts = crate::wire::listener::PreparedStatements::default();
719                        continue;
720                    }
721                };
722                prepared_stmts = statements;
723                match response {
724                    QueryResponse::Frame(frame) => queue_send(&out_tx, frame).await?,
725                    QueryResponse::Legacy(response, correlation_id) => {
726                        out_tx
727                            .send_legacy_response(response, correlation_id)
728                            .await?
729                    }
730                }
731            }
732            // BulkInsert handles both single-row and bulk shapes off
733            // the same frame kind: payload `payload` = single,
734            // payload `payloads` = array.
735            MessageKind::BulkInsert => {
736                let task_runtime = Arc::clone(&runtime);
737                let role = session.role;
738                let correlation_id = frame.correlation_id;
739                let result = redwire_spawn_blocking(runtime.as_ref(), move || {
740                    execute_with_redwire_context(&operation_context, role, || {
741                        run_insert_dispatch(&task_runtime, &frame)
742                    })
743                })
744                .await;
745                match result {
746                    Ok(response) => queue_send(&out_tx, response).await?,
747                    Err(error) => send_execution_error(&out_tx, correlation_id, error).await?,
748                }
749            }
750            MessageKind::TypedInsert => {
751                let task_runtime = Arc::clone(&runtime);
752                let role = session.role;
753                let correlation_id = frame.correlation_id;
754                let result = redwire_spawn_blocking(runtime.as_ref(), move || {
755                    execute_with_redwire_context(&operation_context, role, || {
756                        run_typed_insert(&task_runtime, &frame)
757                    })
758                })
759                .await;
760                match result {
761                    Ok(response) => queue_send(&out_tx, response).await?,
762                    Err(error) => send_execution_error(&out_tx, correlation_id, error).await?,
763                }
764            }
765            MessageKind::BulkInsertBinary => {
766                let task_runtime = Arc::clone(&runtime);
767                let role = session.role;
768                let correlation_id = frame.correlation_id;
769                let result = redwire_spawn_blocking(runtime.as_ref(), move || {
770                    execute_with_redwire_context(&operation_context, role, || {
771                        crate::wire::listener::handle_bulk_insert_binary(
772                            &task_runtime,
773                            &frame.payload,
774                        )
775                    })
776                })
777                .await;
778                match result {
779                    Ok(raw) => {
780                        queue_send(
781                            &out_tx,
782                            rewrap_length_prefixed_handler_response(&raw, correlation_id),
783                        )
784                        .await?
785                    }
786                    Err(error) => send_execution_error(&out_tx, correlation_id, error).await?,
787                }
788            }
789            MessageKind::BulkInsertPrevalidated => {
790                let task_runtime = Arc::clone(&runtime);
791                let role = session.role;
792                let correlation_id = frame.correlation_id;
793                let result = redwire_spawn_blocking(runtime.as_ref(), move || {
794                    execute_with_redwire_context(&operation_context, role, || {
795                        crate::wire::listener::handle_bulk_insert_binary_prevalidated(
796                            &task_runtime,
797                            &frame.payload,
798                        )
799                    })
800                })
801                .await;
802                match result {
803                    Ok(raw) => {
804                        queue_send(
805                            &out_tx,
806                            rewrap_length_prefixed_handler_response(&raw, correlation_id),
807                        )
808                        .await?
809                    }
810                    Err(error) => send_execution_error(&out_tx, correlation_id, error).await?,
811                }
812            }
813            // Streaming bulk insert (PG COPY equivalent).
814            MessageKind::BulkStreamStart => {
815                let raw =
816                    crate::wire::listener::handle_stream_start(&frame.payload, &mut stream_session);
817                queue_send(
818                    &out_tx,
819                    rewrap_length_prefixed_handler_response(&raw, frame.correlation_id),
820                )
821                .await?;
822            }
823            MessageKind::BulkStreamRows => {
824                let permit = match redwire_execution_permit(runtime.as_ref()).await {
825                    Ok(permit) => permit,
826                    Err(error) => {
827                        send_execution_error(&out_tx, frame.correlation_id, error).await?;
828                        continue;
829                    }
830                };
831                let task_runtime = Arc::clone(&runtime);
832                let role = session.role;
833                let correlation_id = frame.correlation_id;
834                let task_session = stream_session.take();
835                let result =
836                    redwire_spawn_blocking_with_permit(runtime.as_ref(), permit, move || {
837                        let mut task_session = task_session;
838                        let raw = execute_with_redwire_context(&operation_context, role, || {
839                            crate::wire::listener::handle_stream_rows(
840                                &task_runtime,
841                                &frame.payload,
842                                &mut task_session,
843                            )
844                        });
845                        (raw, task_session)
846                    })
847                    .await;
848                match result {
849                    Ok((raw, returned_session)) => {
850                        stream_session = returned_session;
851                        if !raw.is_empty() {
852                            queue_send(
853                                &out_tx,
854                                rewrap_length_prefixed_handler_response(&raw, correlation_id),
855                            )
856                            .await?;
857                        }
858                    }
859                    Err(error) => send_execution_error(&out_tx, correlation_id, error).await?,
860                }
861            }
862            MessageKind::BulkStreamCommit => {
863                let permit = match redwire_execution_permit(runtime.as_ref()).await {
864                    Ok(permit) => permit,
865                    Err(error) => {
866                        send_execution_error(&out_tx, frame.correlation_id, error).await?;
867                        continue;
868                    }
869                };
870                let task_runtime = Arc::clone(&runtime);
871                let role = session.role;
872                let correlation_id = frame.correlation_id;
873                let task_session = stream_session.take();
874                let result =
875                    redwire_spawn_blocking_with_permit(runtime.as_ref(), permit, move || {
876                        let mut task_session = task_session;
877                        let raw = execute_with_redwire_context(&operation_context, role, || {
878                            crate::wire::listener::handle_stream_commit(
879                                &task_runtime,
880                                &mut task_session,
881                            )
882                        });
883                        (raw, task_session)
884                    })
885                    .await;
886                match result {
887                    Ok((raw, returned_session)) => {
888                        stream_session = returned_session;
889                        queue_send(
890                            &out_tx,
891                            rewrap_length_prefixed_handler_response(&raw, correlation_id),
892                        )
893                        .await?;
894                    }
895                    Err(error) => send_execution_error(&out_tx, correlation_id, error).await?,
896                }
897            }
898            MessageKind::Prepare => {
899                let raw = execute_with_redwire_context(&operation_context, session.role, || {
900                    crate::wire::listener::handle_prepare(
901                        &runtime,
902                        &frame.payload,
903                        &mut prepared_stmts,
904                    )
905                });
906                queue_send(
907                    &out_tx,
908                    rewrap_length_prefixed_handler_response(&raw, frame.correlation_id),
909                )
910                .await?;
911            }
912            MessageKind::Get => {
913                let task_runtime = Arc::clone(&runtime);
914                let role = session.role;
915                let correlation_id = frame.correlation_id;
916                let result = redwire_spawn_blocking(runtime.as_ref(), move || {
917                    execute_with_redwire_context(&operation_context, role, || {
918                        run_get(&task_runtime, &frame)
919                    })
920                })
921                .await;
922                match result {
923                    Ok(response) => queue_send(&out_tx, response).await?,
924                    Err(error) => send_execution_error(&out_tx, correlation_id, error).await?,
925                }
926            }
927            MessageKind::Delete => {
928                let task_runtime = Arc::clone(&runtime);
929                let role = session.role;
930                let correlation_id = frame.correlation_id;
931                let result = redwire_spawn_blocking(runtime.as_ref(), move || {
932                    execute_with_redwire_context(&operation_context, role, || {
933                        run_delete(&task_runtime, &frame)
934                    })
935                })
936                .await;
937                match result {
938                    Ok(response) => queue_send(&out_tx, response).await?,
939                    Err(error) => send_execution_error(&out_tx, correlation_id, error).await?,
940                }
941            }
942            // Output-stream lifecycle (issue #762 / PRD #759 S3).
943            //
944            // OpenStream: parse payload, register the stream_id with
945            // the per-connection registry, and spawn a worker that
946            // emits OpenAck → StreamChunk* → StreamEnd through the
947            // shared outbound channel. The dispatch loop returns to
948            // reading immediately so concurrent streams interleave
949            // on the wire (AC #2).
950            MessageKind::OpenStream => {
951                use super::output_stream as os;
952                let frame_id = frame.correlation_id;
953                let sid = frame.stream_id;
954
955                // Input-stream open (issue #764 / S5). Distinguished by
956                // `direction: "in"` in the payload; the output path
957                // below (the default) keeps owning `sql`-bearing opens.
958                // Input streams commit chunks inline in this loop, so
959                // they are registered in the owned `input_registry`
960                // rather than spawning a worker.
961                if super::input_stream::open_stream_is_input(&frame.payload) {
962                    use super::input_stream as is;
963                    let req = match is::parse_open_input(&frame.payload) {
964                        Ok(r) => r,
965                        Err(e) => {
966                            let err = is::build_input_stream_error_frame(
967                                frame_id,
968                                sid,
969                                e.code(),
970                                e.message(),
971                                0,
972                                0,
973                            )?;
974                            queue_send(&out_tx, err).await?;
975                            continue;
976                        }
977                    };
978                    let in_tx = runtime.connection_in_transaction(connection.id());
979                    let config = match crate::server::output_stream::StreamConfig::load(&runtime) {
980                        Ok(config) => config,
981                        Err(error) => {
982                            let err = is::build_input_stream_error_frame(
983                                frame_id,
984                                sid,
985                                "stream_config_unavailable",
986                                &error.to_string(),
987                                0,
988                                runtime.cdc_current_lsn(),
989                            )?;
990                            queue_send(&out_tx, err).await?;
991                            continue;
992                        }
993                    };
994                    let snapshot_lsn = runtime.cdc_current_lsn();
995                    let clock = crate::server::output_stream::SystemClock;
996                    let lease = match is::open_input_lease(config, snapshot_lsn, in_tx, &clock) {
997                        Ok(l) => l,
998                        Err(e) => {
999                            let err = is::build_input_stream_error_frame(
1000                                frame_id,
1001                                sid,
1002                                e.code(),
1003                                e.message(),
1004                                0,
1005                                snapshot_lsn,
1006                            )?;
1007                            queue_send(&out_tx, err).await?;
1008                            continue;
1009                        }
1010                    };
1011                    let lease_id = lease.id;
1012                    let lease_snapshot = lease.snapshot_lsn;
1013                    let state = is::InputStreamState::new(lease, req.target, req.columns);
1014                    if let Err(e) = input_registry.register(sid, state) {
1015                        let err = is::build_input_stream_error_frame(
1016                            frame_id,
1017                            sid,
1018                            e.code(),
1019                            e.message(),
1020                            0,
1021                            snapshot_lsn,
1022                        )?;
1023                        queue_send(&out_tx, err).await?;
1024                        continue;
1025                    }
1026                    let ack =
1027                        os::build_open_ack_frame(frame_id, sid, lease_id, lease_snapshot, false)
1028                            .map_err(|e| io::Error::other(format!("build OpenAck: {e}")))?;
1029                    queue_send(&out_tx, ack).await?;
1030                    continue;
1031                }
1032
1033                let req = match os::parse_open_stream(&frame.payload) {
1034                    Ok(r) => r,
1035                    Err(e) => {
1036                        let err =
1037                            os::build_stream_error_frame(frame_id, sid, e.code(), e.message())?;
1038                        queue_send(&out_tx, err).await?;
1039                        continue;
1040                    }
1041                };
1042                let cancel_rx = match stream_registry.register(sid).await {
1043                    Ok(rx) => rx,
1044                    Err(e) => {
1045                        let err =
1046                            os::build_stream_error_frame(frame_id, sid, e.code(), e.message())?;
1047                        queue_send(&out_tx, err).await?;
1048                        continue;
1049                    }
1050                };
1051                let runtime_ref = Arc::clone(&runtime);
1052                let registry_ref = Arc::clone(&stream_registry);
1053                let send = out_tx.clone();
1054                let mut stream_context = operation_context.clone();
1055                let stream_role = session.role;
1056                let in_tx = runtime.connection_in_transaction(connection.id());
1057                // Streams execute in autocommit independently of a later BEGIN
1058                // on the session. The worker owns its ID until safe teardown;
1059                // the JoinSet aborts workers when the frame loop disconnects.
1060                let stream_connection = runtime
1061                    .acquire_wire_connection()
1062                    .map_err(|error| io::Error::other(error.to_string()))?;
1063                stream_context.connection_id = Some(stream_connection.id());
1064                output_stream_tasks.spawn(async move {
1065                    let _connection = stream_connection;
1066                    os::run_output_stream(
1067                        runtime_ref,
1068                        frame_id,
1069                        sid,
1070                        req,
1071                        in_tx,
1072                        cancel_rx,
1073                        send,
1074                        stream_context,
1075                        stream_role,
1076                    )
1077                    .await;
1078                    registry_ref.unregister(sid).await;
1079                });
1080            }
1081            // Live queue wait (issue #917 / PRD #915). Parse the open
1082            // request, then spawn a task that awaits the runtime's async
1083            // wait edge (parks on the registry's async wake head — no
1084            // blocking OS thread) and pushes a `QueueEventPush` the
1085            // instant a message becomes deliverable. The dispatch loop
1086            // returns to reading immediately so the wait multiplexes
1087            // with other frames on the connection.
1088            MessageKind::QueueWaitOpen => {
1089                use super::queue_wait as qw;
1090                let frame_id = frame.correlation_id;
1091                let sid = frame.stream_id;
1092                let req = match qw::parse_queue_wait_open(&frame.payload) {
1093                    Ok(r) => r,
1094                    Err(e) => {
1095                        let err =
1096                            qw::build_queue_wait_error_frame(frame_id, sid, e.code(), e.message())
1097                                .map_err(|e| {
1098                                    io::Error::other(format!("build queue-wait error: {e}"))
1099                                })?;
1100                        queue_send(&out_tx, err).await?;
1101                        continue;
1102                    }
1103                };
1104                // Server max-wait cap (issue #919, AC #3). Reject an
1105                // over-cap budget with an explicit error *before*
1106                // spawning the wait task — no waiter is registered and
1107                // the budget is never silently shortened.
1108                if let Err(msg) = runtime.redwire_queue_wait_cap_check(req.wait_ms) {
1109                    let err = qw::build_queue_wait_error_frame(
1110                        frame_id,
1111                        sid,
1112                        qw::WAIT_EXCEEDS_CAP_CODE,
1113                        &msg,
1114                    )
1115                    .map_err(|e| io::Error::other(format!("build queue-wait cap error: {e}")))?;
1116                    queue_send(&out_tx, err).await?;
1117                    continue;
1118                }
1119                let runtime_ref = Arc::clone(&runtime);
1120                let out = out_tx.clone();
1121                let queue_name = req.queue.clone();
1122                let wait_ms = req.wait_ms;
1123                let auth_identity = Some((session.username.clone(), session.role));
1124                let auth_principal = Some(crate::auth::UserId::from_parts(
1125                    session.tenant.as_deref(),
1126                    &session.username,
1127                ));
1128                let tenant = session.tenant.clone();
1129                // Owned by the connection-scoped `JoinSet` so a client
1130                // disconnect (frame loop return) aborts a still-parked
1131                // wait and releases its registry slot promptly (#920).
1132                queue_wait_tasks.spawn(async move {
1133                    use crate::runtime::RedwireWaitOutcome;
1134                    match runtime_ref
1135                        .redwire_queue_wait_json(
1136                            &req.queue,
1137                            req.group.as_deref(),
1138                            &req.consumer,
1139                            req.count,
1140                            req.wait_ms,
1141                            auth_identity,
1142                            auth_principal,
1143                            tenant,
1144                        )
1145                        .await
1146                    {
1147                        // Happy path: push each delivered message.
1148                        Ok(RedwireWaitOutcome::Delivered(messages)) => {
1149                            for message in messages {
1150                                match qw::build_event_push_frame(frame_id, sid, &message) {
1151                                    Ok(push) => {
1152                                        if queue_send(&out, push).await.is_err() {
1153                                            return;
1154                                        }
1155                                    }
1156                                    Err(_) => return,
1157                                }
1158                            }
1159                        }
1160                        // Deadline elapsed with nothing deliverable: a
1161                        // distinct timeout frame, not an empty push and
1162                        // not an error (AC #1 / AC #2).
1163                        Ok(RedwireWaitOutcome::TimedOut) => {
1164                            if let Ok(t) = qw::build_queue_wait_timeout_frame(
1165                                frame_id,
1166                                sid,
1167                                &queue_name,
1168                                wait_ms,
1169                            ) {
1170                                let _ = queue_send(&out, t).await;
1171                            }
1172                        }
1173                        // Server-side cancellation: a StreamError with
1174                        // the distinct cancellation code so the client
1175                        // never confuses it with a timeout (AC #2).
1176                        Ok(RedwireWaitOutcome::Cancelled) => {
1177                            if let Ok(ef) = qw::build_queue_wait_error_frame(
1178                                frame_id,
1179                                sid,
1180                                qw::WAIT_CANCELLED_CODE,
1181                                "queue wait cancelled by server",
1182                            ) {
1183                                let _ = queue_send(&out, ef).await;
1184                            }
1185                        }
1186                        // A genuine runtime failure. Server-shutdown
1187                        // cancellation is surfaced as the distinct
1188                        // `RedwireWaitOutcome::Cancelled` arm above, so an
1189                        // `Err` here is never a cancellation (#920 AC #2).
1190                        Err(err) => {
1191                            if let Ok(ef) = qw::build_queue_wait_error_frame(
1192                                frame_id,
1193                                sid,
1194                                qw::WAIT_FAILED_CODE,
1195                                &err.to_string(),
1196                            ) {
1197                                let _ = queue_send(&out, ef).await;
1198                            }
1199                        }
1200                    }
1201                });
1202            }
1203            // Input-stream chunk (issue #764 / S5). A `StreamChunk`
1204            // from the client carries a chunk of rows for an open
1205            // input stream. Each chunk commits synchronously and
1206            // atomically; success is silent (await the next chunk), a
1207            // `terminal: true` chunk closes the stream with a
1208            // `StreamEnd`, and a commit failure emits one `StreamError`
1209            // (carrying `recoverable_rid`) after which no further
1210            // frames are produced for this `stream_id` (AC #3).
1211            MessageKind::StreamChunk => {
1212                use super::input_stream as is;
1213                use crate::server::output_stream::{Clock, SystemClock};
1214                let frame_id = frame.correlation_id;
1215                let sid = frame.stream_id;
1216                if !input_registry.contains(sid) {
1217                    // No input stream for this id — protocol violation,
1218                    // surfaced as StreamError rather than a drop.
1219                    let err = is::build_input_stream_error_frame(
1220                        frame_id,
1221                        sid,
1222                        "unknown_stream",
1223                        "no active input stream for this stream_id",
1224                        0,
1225                        0,
1226                    )?;
1227                    queue_send(&out_tx, err).await?;
1228                    continue;
1229                }
1230                // BEGIN may arrive after OpenStream. Never report a chunk as
1231                // committed if it would instead join the session transaction.
1232                if runtime.connection_in_transaction(connection.id()) {
1233                    let state = input_registry.remove(sid).expect("stream presence checked");
1234                    let error = crate::server::output_stream::OpenStreamError::TransactionActive;
1235                    let frame = is::build_input_stream_error_frame(
1236                        frame_id,
1237                        sid,
1238                        error.code(),
1239                        error.message(),
1240                        state.chunk_count,
1241                        state.committed_rid,
1242                    )?;
1243                    queue_send(&out_tx, frame).await?;
1244                    continue;
1245                }
1246                let chunk = match is::parse_input_chunk(&frame.payload) {
1247                    Ok(c) => c,
1248                    Err(e) => {
1249                        let state = input_registry
1250                            .remove(sid)
1251                            .expect("stream presence checked above");
1252                        let err = is::build_input_stream_error_frame(
1253                            frame_id,
1254                            sid,
1255                            e.code(),
1256                            e.message(),
1257                            state.chunk_count,
1258                            state.committed_rid,
1259                        )?;
1260                        queue_send(&out_tx, err).await?;
1261                        continue;
1262                    }
1263                };
1264                let execution_permit = match redwire_execution_permit(runtime.as_ref()).await {
1265                    Ok(permit) => permit,
1266                    Err(error) => {
1267                        // StreamError is terminal for an input stream. Earlier
1268                        // chunks remain durable and recoverable_rid identifies
1269                        // the last successful commit.
1270                        let state = input_registry
1271                            .remove(sid)
1272                            .expect("stream presence checked above");
1273                        let err = is::build_input_stream_error_frame(
1274                            frame_id,
1275                            sid,
1276                            error.code(),
1277                            &error.client_message(),
1278                            state.chunk_count,
1279                            state.committed_rid,
1280                        )?;
1281                        queue_send(&out_tx, err).await?;
1282                        continue;
1283                    }
1284                };
1285                let commit_result = {
1286                    let _execution_permit = execution_permit;
1287                    let state = input_registry
1288                        .get_mut(sid)
1289                        .expect("stream presence checked above");
1290                    if state.lease.snapshot_expired(SystemClock.now_ms()) {
1291                        Err((
1292                            "snapshot_expired".to_string(),
1293                            "stream snapshot pin TTL elapsed".to_string(),
1294                        ))
1295                    } else {
1296                        run_redwire_blocking(|| {
1297                            execute_with_redwire_context(&operation_context, session.role, || {
1298                                state.commit_chunk(&runtime, &chunk.rows)
1299                            })
1300                        })
1301                    }
1302                };
1303                match commit_result {
1304                    Err((code, message)) => {
1305                        let state = input_registry
1306                            .remove(sid)
1307                            .expect("stream presence checked above");
1308                        let err = is::build_input_stream_error_frame(
1309                            frame_id,
1310                            sid,
1311                            &code,
1312                            &message,
1313                            state.chunk_count,
1314                            state.committed_rid,
1315                        )?;
1316                        queue_send(&out_tx, err).await?;
1317                    }
1318                    Ok(()) => {
1319                        if chunk.terminal {
1320                            let state = input_registry
1321                                .remove(sid)
1322                                .expect("stream presence checked above");
1323                            let end = is::build_input_stream_end_frame(
1324                                frame_id,
1325                                sid,
1326                                state.row_count,
1327                                state.chunk_count,
1328                                state.committed_rid,
1329                                state.snapshot_lsn,
1330                                false,
1331                            )?;
1332                            queue_send(&out_tx, end).await?;
1333                        }
1334                    }
1335                }
1336            }
1337            MessageKind::StreamCancel => {
1338                use super::input_stream as is;
1339                use super::output_stream as os;
1340                let sid = frame.stream_id;
1341                if stream_registry.cancel(sid).await {
1342                    // Output stream cancelled — its worker emits the
1343                    // terminal StreamEnd(cancelled=true) itself.
1344                } else if let Some(state) = input_registry.remove(sid) {
1345                    // AC #4 — input-stream cancel: the in-flight (not
1346                    // yet committed) chunk is discarded by dropping the
1347                    // state; prior per-chunk commits stay durable. Emit
1348                    // a terminal StreamEnd with cancelled=true so the
1349                    // client can drop its bookkeeping.
1350                    let end = is::build_input_stream_end_frame(
1351                        frame.correlation_id,
1352                        sid,
1353                        state.row_count,
1354                        state.chunk_count,
1355                        state.committed_rid,
1356                        state.snapshot_lsn,
1357                        true,
1358                    )?;
1359                    queue_send(&out_tx, end).await?;
1360                } else {
1361                    // AC #6: protocol violation surfaces as a
1362                    // StreamError envelope, not a connection drop.
1363                    let err = os::build_stream_error_frame(
1364                        frame.correlation_id,
1365                        sid,
1366                        "unknown_stream",
1367                        "no active stream for this stream_id",
1368                    )?;
1369                    queue_send(&out_tx, err).await?;
1370                }
1371            }
1372            other => {
1373                let err_frame = build_error_frame_lossy(
1374                    frame.correlation_id,
1375                    &format!("redwire: cannot dispatch {other:?} yet"),
1376                );
1377                queue_send(&out_tx, err_frame).await?;
1378            }
1379        }
1380    }
1381}
1382
1383/// Frames a connection may have queued for its socket writer before the
1384/// producers block. Bounded so a peer that stops reading cannot make the
1385/// server buffer an output stream without limit; the writer task drains it
1386/// as fast as the socket accepts bytes.
1387const OUTBOUND_QUEUE_FRAMES: usize = 256;
1388/// Frames decoded ahead of synchronous execution. This bounded reader pump is
1389/// what lets EOF cancel a running request without granting peers unbounded
1390/// buffering for pipelined frames.
1391const INBOUND_QUEUE_FRAMES: usize = 16;
1392
1393async fn queue_send(out_tx: &super::output_stream::FrameTx, frame: Frame) -> io::Result<()> {
1394    out_tx.send_frame(frame).await
1395}
1396
1397/// Run the handshake. Returns `Ok(None)` when the client disconnected
1398/// or the auth was refused (the failure frame is already on the wire).
1399async fn perform_handshake<S>(
1400    stream: &mut S,
1401    runtime: &RedDBRuntime,
1402    auth_store: Option<&Arc<AuthStore>>,
1403    oauth: Option<&crate::auth::oauth::OAuthValidator>,
1404) -> io::Result<Option<AuthedSession>>
1405where
1406    S: AsyncRead + AsyncWrite + Unpin + Send,
1407{
1408    // Step 1: read minor version byte.
1409    let mut minor_buf = [0u8; 1];
1410    stream.read_exact(&mut minor_buf).await?;
1411    let minor = minor_buf[0];
1412    if validate_minor_version(minor).is_err() {
1413        // Future client speaking a version we don't know — refuse
1414        // immediately. We do not send a frame because the client
1415        // hasn't agreed on the framing version yet.
1416        return Ok(None);
1417    }
1418
1419    // Step 2: read the Hello frame.
1420    let hello = read_frame(stream).await?;
1421    if hello.kind != MessageKind::Hello {
1422        let fail = encode_frame(&reply_frame_or_io_error(
1423            hello.correlation_id,
1424            MessageKind::AuthFail,
1425            build_auth_fail_payload("first frame after magic must be Hello"),
1426        )?);
1427        let _ = stream.write_all(&fail).await;
1428        return Ok(None);
1429    }
1430    let hello_msg = match Hello::from_payload(&hello.payload) {
1431        Ok(h) => h,
1432        Err(e) => {
1433            let fail = encode_frame(&reply_frame_or_io_error(
1434                hello.correlation_id,
1435                MessageKind::AuthFail,
1436                build_auth_fail_payload(&e),
1437            )?);
1438            let _ = stream.write_all(&fail).await;
1439            return Ok(None);
1440        }
1441    };
1442
1443    let Some(chosen_version) = choose_hello_minor_version(&hello_msg.versions) else {
1444        let fail = encode_frame(&reply_frame_or_io_error(
1445            hello.correlation_id,
1446            MessageKind::AuthFail,
1447            build_auth_fail_payload("no overlapping protocol version"),
1448        )?);
1449        let _ = stream.write_all(&fail).await;
1450        return Ok(None);
1451    };
1452
1453    let server_anon_ok = auth_store.map(|s| !s.is_enabled()).unwrap_or(true);
1454    let chosen = match pick_auth_method(&hello_msg.auth_methods, server_anon_ok) {
1455        Some(m) => m,
1456        None => {
1457            let fail = encode_frame(&reply_frame_or_io_error(
1458                hello.correlation_id,
1459                MessageKind::AuthFail,
1460                build_auth_fail_payload("no overlapping auth method"),
1461            )?);
1462            let _ = stream.write_all(&fail).await;
1463            return Ok(None);
1464        }
1465    };
1466
1467    // Step 3: HelloAck.
1468    //
1469    // HelloAck is sent before any AuthResponse arrives, so the
1470    // caller is unauthenticated at this point. The TopologyAdvertiser
1471    // collapses anonymous to primary-only per ADR 0008 §3 — that's
1472    // the correct payload for the bootstrap path. Authenticated
1473    // principals get the full replica list via the gRPC `Topology`
1474    // RPC after the connection is established.
1475    let server_features =
1476        FEATURE_PARAMS | reddb_wire::routing::FEATURE_TOPOLOGY | FEATURE_TYPED_MUTATIONS;
1477    let topology = build_topology_for_hello_ack(runtime);
1478    let ack_frame = build_hello_ack_frame(
1479        hello.correlation_id,
1480        chosen_version,
1481        chosen,
1482        server_features,
1483        topology.as_ref(),
1484    )
1485    .map_err(|e| io::Error::other(format!("build HelloAck: {e}")))?;
1486    let ack = encode_frame(&ack_frame);
1487    stream.write_all(&ack).await?;
1488
1489    // SCRAM is a 3-RTT challenge/response exchange. Branch off to
1490    // its own state machine before the 1-RTT bearer/anonymous
1491    // path runs.
1492    if chosen == "scram-sha-256" {
1493        return perform_scram_handshake(stream, auth_store, hello.correlation_id, server_features)
1494            .await;
1495    }
1496
1497    // Step 4: AuthResponse (no challenge for the 1-RTT methods —
1498    // bearer/anonymous send their proof in the first AuthResponse).
1499    let resp = read_frame(stream).await?;
1500    let auth_payload = match expect_auth_response_payload(resp.kind, &resp.payload, "AuthResponse")
1501    {
1502        Ok(payload) => payload,
1503        Err(err) => {
1504            let fail = encode_frame(&reply_frame_or_io_error(
1505                resp.correlation_id,
1506                MessageKind::AuthFail,
1507                build_auth_fail_payload(&err.to_string()),
1508            )?);
1509            let _ = stream.write_all(&fail).await;
1510            return Ok(None);
1511        }
1512    };
1513
1514    // OAuth-JWT branch. The `jwt` field carries either a browser access
1515    // JWT (the hybrid-token model, issue #936) or a federated IdP token
1516    // validated by the configured `OAuthValidator`. The browser access
1517    // token is tried *first* and independently of `oauth` being wired, so
1518    // a deployment that runs the browser credential layer without any
1519    // external OAuth IdP still authenticates. mTLS stays native-only
1520    // (ADR 0036) — the browser presents this access JWT and nothing else.
1521    if chosen == "oauth-jwt" {
1522        let raw = match parse_auth_response_oauth_jwt(auth_payload) {
1523            Ok(raw) if !raw.is_empty() => raw,
1524            _ => {
1525                let fail = encode_frame(&reply_frame_or_io_error(
1526                    resp.correlation_id,
1527                    MessageKind::AuthFail,
1528                    build_auth_fail_payload("oauth-jwt: AuthResponse missing 'jwt' string"),
1529                )?);
1530                let _ = stream.write_all(&fail).await;
1531                return Ok(None);
1532            }
1533        };
1534
1535        // 1. Browser hybrid-token access JWT (issue #936). A *valid*
1536        //    access token (correct issuer/audience/signature, `typ:
1537        //    access`, unexpired) authenticates the session directly.
1538        //    Anything else (expired, wrong type, or simply not one of our
1539        //    tokens — e.g. a foreign IdP RS256 token) falls through to the
1540        //    OAuth validator below; the net effect is "valid browser
1541        //    token accepted, expired/invalid rejected" (AC #2). The stream
1542        //    lease (ADR 0029) then decouples this token's expiry from any
1543        //    stream the session opens, so a later refresh never tears down
1544        //    in-flight work (AC #3).
1545        if let Some(authority) = runtime.browser_token_authority() {
1546            let now = std::time::SystemTime::now()
1547                .duration_since(std::time::UNIX_EPOCH)
1548                .map(|d| d.as_secs() as i64)
1549                .unwrap_or(0);
1550            if let Ok(identity) = authority.validate_access(&raw, now) {
1551                let lease = match acquire_local_connection_lease(
1552                    auth_store,
1553                    identity.tenant.as_deref(),
1554                    &identity.username,
1555                ) {
1556                    Ok(lease) => lease,
1557                    Err(reason) => {
1558                        send_auth_refusal(stream, resp.correlation_id, &reason).await?;
1559                        return Ok(None);
1560                    }
1561                };
1562                let session_id = super::auth::new_session_id_for_scram();
1563                let ok = encode_frame(&reply_frame_or_io_error(
1564                    resp.correlation_id,
1565                    MessageKind::AuthOk,
1566                    build_auth_ok(
1567                        &session_id,
1568                        &identity.username,
1569                        identity.role,
1570                        server_features,
1571                    ),
1572                )?);
1573                stream.write_all(&ok).await?;
1574                return Ok(Some(AuthedSession {
1575                    username: identity.username,
1576                    role: identity.role,
1577                    tenant: identity.tenant,
1578                    session_id,
1579                    _lease: lease,
1580                }));
1581            }
1582        }
1583
1584        // 2. Federated OAuth-JWT (RS256/ES256 against a configured IdP).
1585        let validator = match oauth {
1586            Some(v) => v,
1587            None => {
1588                let fail = encode_frame(&reply_frame_or_io_error(
1589                    resp.correlation_id,
1590                    MessageKind::AuthFail,
1591                    build_auth_fail_payload(
1592                        "oauth-jwt: token rejected (no browser-token authority or OAuth validator accepted it)",
1593                    ),
1594                )?);
1595                let _ = stream.write_all(&fail).await;
1596                return Ok(None);
1597            }
1598        };
1599        match super::auth::validate_oauth_jwt_full(validator, &raw) {
1600            Ok((tenant, username, role)) => {
1601                let lease = match acquire_local_connection_lease(
1602                    auth_store,
1603                    tenant.as_deref(),
1604                    &username,
1605                ) {
1606                    Ok(lease) => lease,
1607                    Err(reason) => {
1608                        send_auth_refusal(stream, resp.correlation_id, &reason).await?;
1609                        return Ok(None);
1610                    }
1611                };
1612                let session_id = super::auth::new_session_id_for_scram();
1613                let ok = encode_frame(&reply_frame_or_io_error(
1614                    resp.correlation_id,
1615                    MessageKind::AuthOk,
1616                    build_auth_ok(&session_id, &username, role, server_features),
1617                )?);
1618                stream.write_all(&ok).await?;
1619                return Ok(Some(AuthedSession {
1620                    username,
1621                    role,
1622                    tenant,
1623                    session_id,
1624                    _lease: lease,
1625                }));
1626            }
1627            Err(reason) => {
1628                let fail = encode_frame(&reply_frame_or_io_error(
1629                    resp.correlation_id,
1630                    MessageKind::AuthFail,
1631                    build_auth_fail_payload(&format!("oauth-jwt: {reason}")),
1632                )?);
1633                let _ = stream.write_all(&fail).await;
1634                return Ok(None);
1635            }
1636        }
1637    }
1638
1639    match validate_auth_response(chosen, auth_payload, auth_store.map(AsRef::as_ref)) {
1640        AuthOutcome::Authenticated {
1641            username,
1642            role,
1643            tenant,
1644            session_id,
1645        } => {
1646            let lease =
1647                match acquire_local_connection_lease(auth_store, tenant.as_deref(), &username) {
1648                    Ok(lease) => lease,
1649                    Err(reason) => {
1650                        send_auth_refusal(stream, resp.correlation_id, &reason).await?;
1651                        return Ok(None);
1652                    }
1653                };
1654            let ok_frame = build_auth_ok_frame_from_payload(
1655                resp.correlation_id,
1656                build_auth_ok(&session_id, &username, role, server_features),
1657            )
1658            .map_err(|e| io::Error::other(format!("build AuthOk: {e}")))?;
1659            let ok = encode_frame(&ok_frame);
1660            stream.write_all(&ok).await?;
1661            Ok(Some(AuthedSession {
1662                username,
1663                role,
1664                tenant,
1665                session_id,
1666                _lease: lease,
1667            }))
1668        }
1669        AuthOutcome::Refused(reason) => {
1670            let fail = encode_frame(&reply_frame_or_io_error(
1671                resp.correlation_id,
1672                MessageKind::AuthFail,
1673                build_auth_fail_payload(&reason),
1674            )?);
1675            let _ = stream.write_all(&fail).await;
1676            Ok(None)
1677        }
1678    }
1679}
1680
1681/// 3-RTT SCRAM-SHA-256 server handshake (RFC 5802 + RFC 7677).
1682///
1683/// ```text
1684/// C → S  AuthResponse(client-first-message)         (already received as client-first)
1685/// S → C  AuthRequest(server-first-message)
1686/// C → S  AuthResponse(client-final-message)
1687/// S → C  AuthOk(v=server-signature)
1688/// ```
1689async fn perform_scram_handshake<S>(
1690    stream: &mut S,
1691    auth_store: Option<&Arc<AuthStore>>,
1692    initial_correlation: u64,
1693    server_features: u32,
1694) -> io::Result<Option<AuthedSession>>
1695where
1696    S: AsyncRead + AsyncWrite + Unpin + Send,
1697{
1698    let store = match auth_store {
1699        Some(s) => s,
1700        None => {
1701            let fail = encode_frame(&reply_frame_or_io_error(
1702                initial_correlation,
1703                MessageKind::AuthFail,
1704                build_auth_fail_payload("scram-sha-256 requires an AuthStore"),
1705            )?);
1706            let _ = stream.write_all(&fail).await;
1707            return Ok(None);
1708        }
1709    };
1710
1711    let mut handshake = ScramServerHandshake::new(
1712        super::auth::new_server_nonce(),
1713        crate::auth::store::random_bytes(16),
1714    );
1715
1716    // The wire handshake doesn't yet learn
1717    // a tenant before the SCRAM exchange completes, so we resolve
1718    // against the platform tenant. Tenant-scoped users authenticate
1719    // through the JWT path (which carries the tenant claim) or a
1720    // future explicit `tenant` extension to the AuthRequest payload.
1721    let client_first = read_frame(stream).await?;
1722    let username = match handshake.step(ScramServerInput::ClientMessage {
1723        correlation_id: client_first.correlation_id,
1724        kind: client_first.kind,
1725        payload: client_first.payload,
1726    }) {
1727        ScramServerOutput::NeedVerifier { username } => username,
1728        ScramServerOutput::Failed {
1729            correlation_id,
1730            reason,
1731        } => {
1732            let fail = encode_frame(&reply_frame_or_io_error(
1733                correlation_id,
1734                MessageKind::AuthFail,
1735                build_auth_fail_payload(&reason),
1736            )?);
1737            let _ = stream.write_all(&fail).await;
1738            return Ok(None);
1739        }
1740        _ => unreachable!("client-first step must request a verifier or fail"),
1741    };
1742    let verifier = store.lookup_scram_verifier_global(&username);
1743    let (challenge_correlation_id, challenge_payload) =
1744        match handshake.step(ScramServerInput::Verifier(verifier)) {
1745            ScramServerOutput::Challenge {
1746                correlation_id,
1747                payload,
1748            } => (correlation_id, payload),
1749            _ => unreachable!("verifier step must produce a SCRAM challenge"),
1750        };
1751    let req = encode_frame(&reply_frame_or_io_error(
1752        challenge_correlation_id,
1753        MessageKind::AuthRequest,
1754        challenge_payload,
1755    )?);
1756    stream.write_all(&req).await?;
1757
1758    let client_final = read_frame(stream).await?;
1759    let (final_correlation_id, username, server_signature) =
1760        match handshake.step(ScramServerInput::ClientMessage {
1761            correlation_id: client_final.correlation_id,
1762            kind: client_final.kind,
1763            payload: client_final.payload,
1764        }) {
1765            ScramServerOutput::Authenticated {
1766                correlation_id,
1767                username,
1768                server_signature,
1769            } => (correlation_id, username, server_signature),
1770            ScramServerOutput::Failed {
1771                correlation_id,
1772                reason,
1773            } => {
1774                let fail = encode_frame(&reply_frame_or_io_error(
1775                    correlation_id,
1776                    MessageKind::AuthFail,
1777                    build_auth_fail_payload(&reason),
1778                )?);
1779                let _ = stream.write_all(&fail).await;
1780                return Ok(None);
1781            }
1782            _ => unreachable!("client-final step must authenticate or fail"),
1783        };
1784    // Bind the session to the same platform principal whose verifier was
1785    // checked above; a tenant-local namesake is a different identity.
1786    let user = store.get_user(None, &username);
1787    let role = user
1788        .as_ref()
1789        .map(|u| u.role)
1790        .unwrap_or(crate::auth::Role::Read);
1791    let lease = match acquire_local_connection_lease(auth_store, None, &username) {
1792        Ok(Some(lease)) => lease,
1793        Ok(None) | Err(_) => {
1794            send_auth_refusal(stream, final_correlation_id, "authentication refused").await?;
1795            return Ok(None);
1796        }
1797    };
1798    let session_id = super::auth::new_session_id_for_scram();
1799    let ok_payload = super::auth::build_scram_auth_ok(
1800        &session_id,
1801        &username,
1802        role,
1803        server_features,
1804        &server_signature,
1805    );
1806    let ok = encode_frame(&reply_frame_or_io_error(
1807        final_correlation_id,
1808        MessageKind::AuthOk,
1809        ok_payload,
1810    )?);
1811    stream.write_all(&ok).await?;
1812    Ok(Some(AuthedSession {
1813        username,
1814        role,
1815        tenant: user.and_then(|u| u.tenant_id),
1816        session_id,
1817        _lease: Some(lease),
1818    }))
1819}
1820
1821async fn read_frame<S>(stream: &mut S) -> io::Result<Frame>
1822where
1823    S: AsyncRead + Unpin + Send,
1824{
1825    read_frame_async(stream).await.map_err(redwire_io_err)
1826}
1827
1828fn redwire_io_err(err: reddb_wire::redwire::RedWireIoError) -> io::Error {
1829    match err {
1830        reddb_wire::redwire::RedWireIoError::Io(err) => err,
1831        reddb_wire::redwire::RedWireIoError::Frame(err) => {
1832            io::Error::other(format!("decode frame: {err}"))
1833        }
1834    }
1835}
1836
1837/// `Query` (0x01) answers with the pinned summary payload — statement type
1838/// plus affected rows — not the full result envelope. `QueryWithParams`
1839/// (0x28) is the frame that carries records back; clients pick the frame by
1840/// the reply shape they want.
1841fn run_query(runtime: &RedDBRuntime, prepared: &PreparedRegistry, frame: &Frame) -> Frame {
1842    let sql = match std::str::from_utf8(&frame.payload) {
1843        Ok(s) => s,
1844        Err(_) => {
1845            return build_error_frame_lossy(
1846                frame.correlation_id,
1847                "Query payload must be UTF-8 SQL",
1848            );
1849        }
1850    };
1851    let result =
1852        QueryRequestExecutor::new(runtime, prepared).execute(QueryRequest::sql(sql, Vec::new()));
1853    crate::presentation::query_result::summary_frame(
1854        frame.correlation_id,
1855        result
1856            .as_ref()
1857            .map(|result| &**result)
1858            .map_err(crate::api::client_facing_message),
1859    )
1860}
1861
1862fn run_query_with_params(
1863    runtime: &RedDBRuntime,
1864    prepared: &PreparedRegistry,
1865    frame: &Frame,
1866) -> Frame {
1867    let request = match decode_query_with_params_request(&frame.payload) {
1868        Ok(decoded) => decoded,
1869        Err(err) => return build_error_frame_lossy(frame.correlation_id, &err.to_string()),
1870    };
1871    let commit_policy = match parse_redwire_commit_policy(request.options.commit_policy.as_deref())
1872    {
1873        Ok(policy) => policy,
1874        Err(err) => return build_error_frame_lossy(frame.correlation_id, &err),
1875    };
1876    let params = request
1877        .params
1878        .into_iter()
1879        .map(param_to_request_value)
1880        .collect::<Vec<_>>();
1881    let mut query = QueryRequest::sql(request.sql, params);
1882    if let Some(policy) = commit_policy {
1883        query = query.with_commit_policy(policy);
1884    }
1885    let result = QueryRequestExecutor::new(runtime, prepared).execute(query);
1886    crate::presentation::query_result::envelope_frame(
1887        frame.correlation_id,
1888        result
1889            .as_ref()
1890            .map(|result| &**result)
1891            .map_err(crate::api::client_facing_message),
1892    )
1893}
1894
1895fn parse_redwire_commit_policy(
1896    value: Option<&str>,
1897) -> Result<Option<crate::replication::CommitPolicy>, String> {
1898    let Some(value) = value else {
1899        return Ok(None);
1900    };
1901    crate::replication::CommitPolicy::parse_strict(value)
1902        .map(Some)
1903        .ok_or_else(|| format!("invalid commit_policy value '{value}'"))
1904}
1905
1906fn param_to_request_value(value: RedWireParamValue) -> ParamValue {
1907    match value {
1908        RedWireParamValue::Null => ParamValue::Null,
1909        RedWireParamValue::Bool(value) => ParamValue::Bool(value),
1910        RedWireParamValue::Int(value) => ParamValue::Int64(value),
1911        RedWireParamValue::Float(value) => ParamValue::Float64(value),
1912        RedWireParamValue::Text(value) => ParamValue::Text(value),
1913        RedWireParamValue::Bytes(value) => ParamValue::Bytes(value),
1914        RedWireParamValue::Vector(value) => ParamValue::Vector(value),
1915        RedWireParamValue::Json(value) => ParamValue::Json(value),
1916        RedWireParamValue::Timestamp(value) => ParamValue::Timestamp(value),
1917        RedWireParamValue::Uuid(value) => ParamValue::Uuid(value),
1918    }
1919}
1920
1921fn run_typed_insert(runtime: &RedDBRuntime, frame: &Frame) -> Frame {
1922    let request = match decode_typed_insert(&frame.payload) {
1923        Ok(request) => request,
1924        Err(error) => return build_error_frame_lossy(frame.correlation_id, &error.to_string()),
1925    };
1926    let mut fields = Vec::with_capacity(request.fields.len());
1927    for field in request.fields {
1928        if let RedWireParamValue::Json(bytes) = &field.value {
1929            if let Err(error) = serde_json::from_slice::<JsonValue>(bytes) {
1930                return build_error_frame_lossy(
1931                    frame.correlation_id,
1932                    &format!("field '{}' contains invalid JSON: {error}", field.name),
1933                );
1934            }
1935        }
1936        fields.push((
1937            field.name,
1938            reddb_types::Value::from(param_to_request_value(field.value)),
1939        ));
1940    }
1941
1942    let input = crate::application::CreateRowInput {
1943        collection: request.collection,
1944        fields,
1945        metadata: Vec::new(),
1946        node_links: Vec::new(),
1947        vector_links: Vec::new(),
1948    };
1949    let output = match crate::application::EntityUseCases::new(runtime).create_row(input) {
1950        Ok(output) => output,
1951        Err(error) => {
1952            return build_error_frame_lossy(
1953                frame.correlation_id,
1954                &crate::api::client_facing_message(&error),
1955            )
1956        }
1957    };
1958
1959    // An explicit transaction is committed by the later COMMIT query. For
1960    // autocommit inserts, mirror the other wire mutation paths and enforce
1961    // the configured replication acknowledgement policy before replying.
1962    if runtime.current_xid().is_none() {
1963        let post_lsn = runtime.replication_commit_lsn();
1964        if let Err(error) = runtime.enforce_commit_policy(post_lsn) {
1965            return build_error_frame_lossy(frame.correlation_id, &error.to_string());
1966        }
1967    }
1968
1969    let id = format!("\"{}\"", output.id.raw());
1970    let payload = encode_bulk_ok_payload_from_json_id_literals(1, [id]);
1971    build_dispatch_reply_frame(frame.correlation_id, MessageKind::BulkOk, payload)
1972}
1973
1974/// Insert dispatch — handles single-row, bulk, and the analytics
1975/// batch shape off the same `BulkInsert` (0x04) frame:
1976///   - `{ "collection": "...", "payload": {...} }` → single insert
1977///   - `{ "collection": "...", "payloads": [...] }` → bulk insert
1978///   - `{ "collection": "...", "payloads": [...], "idempotency_key": "...",
1979///       "batch": true? }` → analytics `BatchInsertEndpoint`
1980///     (issue #587) — all-or-nothing commit with
1981///     `AnalyticsSchemaRegistry` validation up front and replay served
1982///     from the durable receipt shared with the HTTP (#582) and
1983///     gRPC (#585) mirrors. Either an `idempotency_key` OR `batch:
1984///     true` flips the dispatch — the literal idempotency key in the
1985///     frame is the canonical signal in the brief, the boolean lets a
1986///     client opt into the validation semantics without committing to
1987///     a cache window.
1988///
1989/// Mirrors the JSON-RPC `insert` / `bulk_insert` method shapes
1990/// from `rpc_stdio.rs` so both transports agree on the payload.
1991/// `INSERT … RETURNING rid` for one JSON row. A bare SQL INSERT result
1992/// carries only `affected_rows`; the engine-assigned id is exposed
1993/// through RETURNING, which is what `insert_result_to_json` reads to
1994/// fill the BulkOk `id`/`ids` keys.
1995fn insert_sql_returning_rid<'a, I>(collection: &str, fields: I) -> String
1996where
1997    I: Iterator<Item = (&'a String, &'a crate::json::Value)>,
1998{
1999    let mut sql = crate::rpc_stdio::build_insert_sql(collection, fields);
2000    sql.push_str(" RETURNING rid");
2001    sql
2002}
2003
2004fn run_insert_dispatch(runtime: &RedDBRuntime, frame: &Frame) -> Frame {
2005    let request = match decode_insert_dispatch_payload(&frame.payload) {
2006        Ok(request) => request,
2007        Err(err) => return build_error_frame_lossy(frame.correlation_id, &err.to_string()),
2008    };
2009    let collection = request.collection.as_str();
2010    if let Err(msg) = crate::rpc_stdio::ensure_sql_collection(collection) {
2011        return build_error_frame_lossy(frame.correlation_id, &msg);
2012    }
2013    let payload = request.payload.map(wire_json_to_server_json);
2014    let payloads = request.payloads.map(|rows| {
2015        rows.into_iter()
2016            .map(wire_json_to_server_json)
2017            .collect::<Vec<_>>()
2018    });
2019
2020    // Analytics batch-insert path (issue #587). Either field flips the
2021    // dispatch — the brief carries `idempotency_key` as the canonical
2022    // signal; the optional `batch: true` boolean exists for callers
2023    // that want the validation contract without committing to a
2024    // replay window.
2025    let idempotency_key = request.idempotency_key.as_deref();
2026    if idempotency_key.is_some() || request.batch {
2027        let items = match payloads.as_deref() {
2028            Some(rows) => rows,
2029            None => {
2030                return build_error_frame_lossy(
2031                    frame.correlation_id,
2032                    "BatchInsert: missing 'payloads' array",
2033                )
2034            }
2035        };
2036        let outcome = crate::server::handlers_entity::process_batch_insert(
2037            runtime,
2038            collection,
2039            items,
2040            idempotency_key,
2041        );
2042        // Mirror the HTTP transport's status convention: 2xx → BulkOk,
2043        // everything else → Error frame (the body carries the typed
2044        // code/row_index envelope so the client can decode it without
2045        // an out-of-band header).
2046        let kind = if (200..300).contains(&outcome.status) {
2047            MessageKind::BulkOk
2048        } else {
2049            MessageKind::Error
2050        };
2051        return build_dispatch_reply_frame(frame.correlation_id, kind, outcome.body);
2052    }
2053
2054    if let Some(rows) = payloads.as_ref() {
2055        let mut objects = Vec::with_capacity(rows.len());
2056        for entry in rows {
2057            objects.push(match entry.as_object() {
2058                Some(o) => o,
2059                None => {
2060                    return build_error_frame_lossy(
2061                        frame.correlation_id,
2062                        "Insert: each payload must be a JSON object",
2063                    )
2064                }
2065            });
2066        }
2067
2068        if crate::rpc_stdio::should_bulk_insert_graph(runtime, collection, &objects) {
2069            return match crate::rpc_stdio::bulk_insert_graph(runtime, collection, &objects) {
2070                Ok(body) => {
2071                    let payload = body.to_string_compact().into_bytes();
2072                    build_dispatch_reply_frame(frame.correlation_id, MessageKind::BulkOk, payload)
2073                }
2074                Err(err) => build_error_frame_lossy(frame.correlation_id, &err.to_string()),
2075            };
2076        }
2077
2078        let mut affected: u64 = 0;
2079        let mut ids = Vec::with_capacity(objects.len());
2080        for row in objects {
2081            let sql = insert_sql_returning_rid(collection, row.iter());
2082            match runtime.execute_query(&sql) {
2083                Ok(qr) => {
2084                    affected += qr.affected_rows;
2085                    if let Some(id) = crate::rpc_stdio::insert_result_to_json(&qr).get("id") {
2086                        ids.push(id.clone());
2087                    }
2088                }
2089                Err(err) => {
2090                    return build_error_frame_lossy(
2091                        frame.correlation_id,
2092                        &crate::api::client_facing_message(&err),
2093                    )
2094                }
2095            }
2096        }
2097        let payload = encode_bulk_ok_payload_from_json_id_literals(
2098            affected,
2099            ids.iter().map(|id| id.to_string()),
2100        );
2101        return build_dispatch_reply_frame(frame.correlation_id, MessageKind::BulkOk, payload);
2102    }
2103
2104    let row = match payload.as_ref().and_then(|x| x.as_object()) {
2105        Some(o) => o,
2106        None => {
2107            return build_error_frame_lossy(
2108                frame.correlation_id,
2109                "Insert: missing 'payload' object or 'payloads' array",
2110            )
2111        }
2112    };
2113    let sql = insert_sql_returning_rid(collection, row.iter());
2114    match runtime.execute_query(&sql) {
2115        Ok(qr) => {
2116            let body = crate::rpc_stdio::insert_result_to_json(&qr);
2117            let payload = body.to_string_compact().into_bytes();
2118            build_dispatch_reply_frame(frame.correlation_id, MessageKind::BulkOk, payload)
2119        }
2120        Err(err) => build_error_frame_lossy(
2121            frame.correlation_id,
2122            &crate::api::client_facing_message(&err),
2123        ),
2124    }
2125}
2126
2127/// Build the primary-only topology payload embedded in HelloAck
2128/// (issue #167). Threads an anonymous auth context through
2129/// `TopologyAdvertiser::advertise` because the principal is not yet
2130/// known at HelloAck time — ADR 0008 §3 collapses anonymous to a
2131/// primary-only payload, which is exactly the bootstrap shape we
2132/// want here.
2133///
2134/// Returns `None` for non-primary roles or when the engine is not
2135/// running with replication enabled. Old clients that don't
2136/// understand the `topology` JSON key ignore it cleanly (ADR §4),
2137/// so the absent-vs-present distinction is benign.
2138fn build_topology_for_hello_ack(runtime: &RedDBRuntime) -> Option<reddb_wire::topology::Topology> {
2139    use crate::auth::middleware::AuthResult;
2140    use crate::replication::{LagConfig, TopologyAdvertiser};
2141    use reddb_wire::topology::Endpoint;
2142
2143    let db = runtime.db();
2144    let primary_endpoint = Endpoint {
2145        addr: runtime.config_string("redwire.advertise_addr", ""),
2146        region: db.options().replication.region.clone(),
2147    };
2148    let (replicas, current_lsn, epoch) = match db.replication.as_ref() {
2149        Some(repl) => (
2150            repl.replica_snapshots(),
2151            repl.wal_buffer.current_lsn(),
2152            repl.topology_epoch(),
2153        ),
2154        None => (Vec::new(), 0u64, 0u64),
2155    };
2156    let lag = LagConfig::from_now();
2157    Some(TopologyAdvertiser::advertise(
2158        &replicas,
2159        &AuthResult::Anonymous,
2160        epoch,
2161        primary_endpoint,
2162        current_lsn,
2163        &lag,
2164    ))
2165}
2166
2167fn reply_frame_or_io_error(
2168    correlation_id: u64,
2169    kind: MessageKind,
2170    payload: Vec<u8>,
2171) -> io::Result<Frame> {
2172    build_reply_frame(correlation_id, kind, payload)
2173        .map_err(|e| io::Error::other(format!("build {kind:?}: {e}")))
2174}
2175
2176fn wire_json_to_server_json(value: impl std::fmt::Display) -> JsonValue {
2177    serde_json::from_str::<JsonValue>(&value.to_string()).unwrap_or(JsonValue::Null)
2178}
2179
2180/// Get payload shape: `{ "collection": "...", "id": "..." }`.
2181/// Bridges to `SELECT * FROM <coll> WHERE rid = <id> LIMIT 1`.
2182/// Reply: Result frame with the row, or empty `{}` when not found.
2183fn run_get(runtime: &RedDBRuntime, frame: &Frame) -> Frame {
2184    let request = match decode_get_payload(&frame.payload) {
2185        Ok(request) => request,
2186        Err(err) => return build_error_frame_lossy(frame.correlation_id, &err.to_string()),
2187    };
2188    let collection = request.collection.as_str();
2189    if let Err(msg) = crate::rpc_stdio::ensure_sql_collection(collection) {
2190        return build_error_frame_lossy(frame.correlation_id, &msg);
2191    }
2192    let Some(rid) = crate::rpc_stdio::rid_from_str(&request.id) else {
2193        let payload = encode_get_result_payload(false);
2194        return build_dispatch_reply_frame(frame.correlation_id, MessageKind::Result, payload);
2195    };
2196    let sql = format!("SELECT * FROM {collection} WHERE rid = {rid} LIMIT 1");
2197    match runtime.execute_query(&sql) {
2198        Ok(qr) => {
2199            // Preserve the existing Get envelope: presence only.
2200            let payload = encode_get_result_payload(!qr.result.records.is_empty());
2201            build_dispatch_reply_frame(frame.correlation_id, MessageKind::Result, payload)
2202        }
2203        Err(err) => build_error_frame_lossy(
2204            frame.correlation_id,
2205            &crate::api::client_facing_message(&err),
2206        ),
2207    }
2208}
2209
2210/// Delete payload shape: `{ "collection": "...", "id": "..." }`.
2211/// Bridges to `DELETE FROM <coll> WHERE rid = <id>`.
2212/// Reply: DeleteOk frame with `{ affected }`.
2213fn run_delete(runtime: &RedDBRuntime, frame: &Frame) -> Frame {
2214    let request = match decode_delete_payload(&frame.payload) {
2215        Ok(request) => request,
2216        Err(err) => return build_error_frame_lossy(frame.correlation_id, &err.to_string()),
2217    };
2218    let collection = request.collection.as_str();
2219    if let Err(msg) = crate::rpc_stdio::ensure_sql_collection(collection) {
2220        return build_error_frame_lossy(frame.correlation_id, &msg);
2221    }
2222    let Some(rid) = crate::rpc_stdio::rid_from_str(&request.id) else {
2223        let payload = encode_delete_ok_payload(0);
2224        return build_dispatch_reply_frame(frame.correlation_id, MessageKind::DeleteOk, payload);
2225    };
2226    let sql = format!("DELETE FROM {collection} WHERE rid = {rid}");
2227    match runtime.execute_query(&sql) {
2228        Ok(qr) => {
2229            let payload = encode_delete_ok_payload(qr.affected_rows);
2230            build_dispatch_reply_frame(frame.correlation_id, MessageKind::DeleteOk, payload)
2231        }
2232        Err(err) => build_error_frame_lossy(
2233            frame.correlation_id,
2234            &crate::api::client_facing_message(&err),
2235        ),
2236    }
2237}
2238
2239#[cfg(test)]
2240mod tests {
2241    use super::*;
2242
2243    use crate::runtime::RedDBRuntime;
2244    use std::cell::Cell;
2245    use std::sync::{Mutex, OnceLock};
2246    use tokio::io::{AsyncReadExt, AsyncWriteExt};
2247
2248    fn env_lock() -> &'static Mutex<()> {
2249        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
2250        LOCK.get_or_init(|| Mutex::new(()))
2251    }
2252
2253    fn all_message_kinds() -> Vec<MessageKind> {
2254        (u8::MIN..=u8::MAX)
2255            .filter_map(MessageKind::from_u8)
2256            .collect()
2257    }
2258
2259    #[tokio::test]
2260    async fn redwire_execution_refuses_when_shared_runtime_queue_is_full() {
2261        let runtime = RedDBRuntime::in_memory().expect("runtime");
2262        runtime.configure_execution_admission(1, 0, 100);
2263        let admission = runtime.execution_admission();
2264        let active = admission.acquire().await.expect("active slot");
2265
2266        let error = redwire_execution_permit(&runtime).await.unwrap_err();
2267        assert_eq!(error.code(), "execution_queue_full");
2268        drop(active);
2269    }
2270
2271    #[tokio::test]
2272    async fn redwire_execution_reports_queue_deadline_separately() {
2273        let runtime = RedDBRuntime::in_memory().expect("runtime");
2274        runtime.configure_execution_admission(1, 1, 1);
2275        let admission = runtime.execution_admission();
2276        let active = admission.acquire().await.expect("active slot");
2277
2278        let error = redwire_execution_permit(&runtime).await.unwrap_err();
2279        assert_eq!(error.code(), "execution_queue_timeout");
2280        drop(active);
2281    }
2282
2283    #[test]
2284    fn every_redwire_frame_kind_resolves_to_a_catalog_command() {
2285        let catalog = crate::server::discovered_route_catalog();
2286
2287        for kind in all_message_kinds() {
2288            let Some(command_id) = redwire_command_id(kind) else {
2289                continue;
2290            };
2291            assert!(
2292                catalog.command(command_id).is_some(),
2293                "{kind:?} maps to missing catalog command {command_id}"
2294            );
2295        }
2296    }
2297
2298    #[test]
2299    fn command_coverage_matrix_reports_redwire_bindings() {
2300        let matrix = crate::server::route_catalog::render_command_coverage_matrix(
2301            crate::server::discovered_route_catalog(),
2302        );
2303
2304        assert!(
2305            matrix.contains("| command | auth requirement | HTTP | gRPC | MCP | stdio | RedWire |")
2306        );
2307        // Pin this transport's binding column. The stdio column describes
2308        // individual local/remote method dispositions, covered by catalog tests.
2309        for (command, expected) in [
2310            ("query.execute", "served"),
2311            ("catalog.snapshot", "undeclared"),
2312        ] {
2313            let row = matrix
2314                .lines()
2315                .find(|line| line.starts_with(&format!("| {command} |")))
2316                .expect("catalog command has a coverage row");
2317            assert_eq!(
2318                row.rsplit('|').nth(1).map(str::trim),
2319                Some(expected),
2320                "RedWire coverage for {command}: {row}"
2321            );
2322        }
2323    }
2324
2325    struct DenyAndCountPolicy(Cell<usize>);
2326
2327    impl crate::server::route_catalog::CommandPolicyEngine for DenyAndCountPolicy {
2328        fn allows(
2329            &self,
2330            _ctx: &OperationContext,
2331            _command: &crate::server::route_catalog::CommandSpec,
2332        ) -> bool {
2333            self.0.set(self.0.get() + 1);
2334            false
2335        }
2336    }
2337
2338    #[test]
2339    fn redwire_dispatch_consults_catalog_authorization() {
2340        let policy = DenyAndCountPolicy(Cell::new(0));
2341        let ctx = OperationContext::read_only("redwire-auth-test").with_principal("reader");
2342
2343        let error = authorize_redwire_frame(&ctx, MessageKind::Query, &policy)
2344            .expect_err("denying policy must reject the frame");
2345
2346        assert_eq!(policy.0.get(), 1);
2347        assert_eq!(
2348            error,
2349            crate::server::route_catalog::CommandAuthorizationError::Denied {
2350                command_id: "query.execute"
2351            }
2352        );
2353    }
2354
2355    #[test]
2356    fn redwire_local_admission_enforces_expiry_and_connection_limit() {
2357        let store = Arc::new(AuthStore::new(crate::auth::AuthConfig {
2358            enabled: true,
2359            require_auth: true,
2360            ..crate::auth::AuthConfig::default()
2361        }));
2362        store
2363            .create_user("alice", "secret", Role::Read)
2364            .expect("user");
2365        let id = crate::auth::UserId::platform("alice");
2366        store
2367            .set_user_attributes(
2368                &id,
2369                crate::auth::UserAttributes {
2370                    valid_until: Some(1),
2371                    ..crate::auth::UserAttributes::default()
2372                },
2373            )
2374            .expect("expired attributes");
2375        assert!(acquire_local_connection_lease(Some(&store), None, "alice").is_err());
2376
2377        store
2378            .set_user_attributes(
2379                &id,
2380                crate::auth::UserAttributes {
2381                    connection_limit: Some(1),
2382                    ..crate::auth::UserAttributes::default()
2383                },
2384            )
2385            .expect("limited attributes");
2386        let first = acquire_local_connection_lease(Some(&store), None, "alice")
2387            .expect("first admission")
2388            .expect("local lease");
2389        assert!(acquire_local_connection_lease(Some(&store), None, "alice").is_err());
2390        drop(first);
2391        assert!(acquire_local_connection_lease(Some(&store), None, "alice")
2392            .expect("slot released")
2393            .is_some());
2394    }
2395
2396    #[test]
2397    fn redwire_query_uses_operation_context_tenant_for_rls() {
2398        crate::runtime::execution_context::clear_current_tenant();
2399        crate::runtime::execution_context::clear_current_auth_identity();
2400        let runtime = RedDBRuntime::in_memory().expect("runtime");
2401        let prepared = PreparedRegistry::new();
2402        runtime
2403            .execute_query("CREATE TABLE docs (id INT, tenant_id TEXT)")
2404            .expect("create table");
2405        runtime
2406            .execute_query(
2407                "INSERT INTO docs (id, tenant_id) VALUES \
2408                 (1, 'acme'), (2, 'acme'), (3, 'globex')",
2409            )
2410            .expect("seed rows");
2411        runtime
2412            .execute_query(
2413                "CREATE POLICY tenant_read ON docs FOR SELECT \
2414                 USING (tenant_id = CURRENT_TENANT())",
2415            )
2416            .expect("create policy");
2417        runtime
2418            .execute_query("ALTER TABLE docs ENABLE ROW LEVEL SECURITY")
2419            .expect("enable rls");
2420
2421        let payload =
2422            reddb_wire::query_with_params::encode_query_with_params("SELECT id FROM docs", &[])
2423                .expect("encode query");
2424        let frame = reddb_wire::redwire::build_query_with_params_frame(7, payload)
2425            .expect("build query frame");
2426
2427        let visible_rows = |tenant: &str| {
2428            let ctx = OperationContextFactory::build(OperationContextInput {
2429                request_id: Some(format!("redwire-rls-{tenant}")),
2430                principal: Some("reader".to_string()),
2431                tenant: Some(tenant.to_string()),
2432                ..OperationContextInput::default()
2433            });
2434            let reply = execute_with_redwire_context(&ctx, Role::Read, || {
2435                run_query_with_params(&runtime, &prepared, &frame)
2436            });
2437            assert_eq!(reply.kind, MessageKind::Result);
2438            let body: JsonValue = serde_json::from_slice(&reply.payload).expect("result envelope");
2439            body.get("result")
2440                .and_then(|result| result.get("records"))
2441                .and_then(JsonValue::as_array)
2442                .map_or(0, |records| records.len())
2443        };
2444
2445        assert_eq!(visible_rows("acme"), 2);
2446        assert_eq!(visible_rows("globex"), 1);
2447        assert!(crate::runtime::execution_context::current_tenant().is_none());
2448        assert!(crate::runtime::execution_context::current_auth_identity().is_none());
2449    }
2450
2451    struct EnvGuard {
2452        previous: Vec<(&'static str, Option<String>)>,
2453    }
2454
2455    impl EnvGuard {
2456        fn set(vars: &[(&'static str, &'static str)]) -> Self {
2457            let previous = vars
2458                .iter()
2459                .map(|(key, _)| (*key, std::env::var(key).ok()))
2460                .collect();
2461            for (key, value) in vars {
2462                std::env::set_var(key, value);
2463            }
2464            Self { previous }
2465        }
2466    }
2467
2468    impl Drop for EnvGuard {
2469        fn drop(&mut self) {
2470            for (key, value) in self.previous.iter().rev() {
2471                match value {
2472                    Some(value) => std::env::set_var(key, value),
2473                    None => std::env::remove_var(key),
2474                }
2475            }
2476        }
2477    }
2478
2479    fn temp_data_path(name: &str) -> std::path::PathBuf {
2480        let mut path = std::env::temp_dir();
2481        path.push(format!(
2482            "reddb-redwire-{name}-{}-{}.rdb",
2483            std::process::id(),
2484            crate::utils::now_unix_millis()
2485        ));
2486        let _ = std::fs::remove_file(&path);
2487        path
2488    }
2489
2490    fn bulk_insert_frame(correlation_id: u64, payload: Vec<u8>) -> Frame {
2491        reddb_wire::redwire::build_bulk_insert_frame(correlation_id, payload)
2492            .expect("build bulk insert frame")
2493    }
2494
2495    fn typed_insert_frame(
2496        correlation_id: u64,
2497        collection: &str,
2498        fields: Vec<(&str, RedWireParamValue)>,
2499    ) -> Frame {
2500        let request = reddb_wire::redwire::TypedInsertRequest {
2501            collection: collection.to_string(),
2502            fields: fields
2503                .into_iter()
2504                .map(|(name, value)| reddb_wire::redwire::TypedInsertField {
2505                    name: name.to_string(),
2506                    value,
2507                })
2508                .collect(),
2509        };
2510        let payload = reddb_wire::redwire::encode_typed_insert(&request).expect("typed payload");
2511        reddb_wire::redwire::build_request_frame(correlation_id, MessageKind::TypedInsert, payload)
2512            .expect("typed insert frame")
2513    }
2514
2515    #[test]
2516    fn redwire_typed_insert_preserves_types_and_contract_defaults() {
2517        let runtime = RedDBRuntime::in_memory().expect("runtime");
2518        runtime
2519            .execute_query(
2520                "CREATE TABLE redwire_typed_users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, active BOOLEAN DEFAULT = true)",
2521            )
2522            .expect("create typed table");
2523        let frame = typed_insert_frame(
2524            40,
2525            "redwire_typed_users",
2526            vec![
2527                ("id", RedWireParamValue::Int(7)),
2528                ("name", RedWireParamValue::Text("Ada".into())),
2529            ],
2530        );
2531
2532        let reply = run_typed_insert(&runtime, &frame);
2533        assert_eq!(reply.kind, MessageKind::BulkOk);
2534        let result = reddb_wire::redwire::decode_bulk_ok_payload(&reply.payload)
2535            .expect("typed insert result");
2536        assert_eq!(result.affected, 1);
2537        assert_eq!(result.rids.len(), 1);
2538
2539        let selected = runtime
2540            .execute_query("SELECT id, name, active FROM redwire_typed_users WHERE id = 7")
2541            .expect("select typed row");
2542        assert_eq!(selected.result.records.len(), 1);
2543        assert_eq!(
2544            selected.result.records[0].get("id"),
2545            Some(&reddb_types::Value::Integer(7))
2546        );
2547        assert_eq!(
2548            selected.result.records[0].get("name"),
2549            Some(&reddb_types::Value::text("Ada"))
2550        );
2551        assert_eq!(
2552            selected.result.records[0].get("active"),
2553            Some(&reddb_types::Value::Boolean(true))
2554        );
2555    }
2556
2557    #[test]
2558    fn redwire_typed_insert_rejects_invalid_json_before_write() {
2559        let runtime = RedDBRuntime::in_memory().expect("runtime");
2560        runtime
2561            .execute_query("CREATE TABLE redwire_typed_json (id INTEGER PRIMARY KEY, body JSON)")
2562            .expect("create typed table");
2563        let frame = typed_insert_frame(
2564            41,
2565            "redwire_typed_json",
2566            vec![
2567                ("id", RedWireParamValue::Int(1)),
2568                ("body", RedWireParamValue::Json(b"{".to_vec())),
2569            ],
2570        );
2571
2572        let reply = run_typed_insert(&runtime, &frame);
2573        assert_eq!(reply.kind, MessageKind::Error);
2574        assert!(String::from_utf8_lossy(&reply.payload).contains("invalid JSON"));
2575        let selected = runtime
2576            .execute_query("SELECT id FROM redwire_typed_json")
2577            .expect("select after rejected insert");
2578        assert!(selected.result.records.is_empty());
2579    }
2580
2581    #[test]
2582    fn redwire_typed_insert_participates_in_connection_transaction() {
2583        let runtime = RedDBRuntime::in_memory().expect("runtime");
2584        let prepared = PreparedRegistry::new();
2585        runtime
2586            .execute_query("CREATE TABLE redwire_typed_tx (id INTEGER PRIMARY KEY)")
2587            .expect("create typed table");
2588        let ctx = OperationContextFactory::build(OperationContextInput {
2589            request_id: Some("redwire-typed-tx".into()),
2590            connection_id: Some(77),
2591            principal: Some("anonymous".into()),
2592            ..OperationContextInput::default()
2593        });
2594
2595        let begin = reddb_wire::redwire::build_query_frame(42, "BEGIN").expect("begin frame");
2596        let insert = typed_insert_frame(
2597            43,
2598            "redwire_typed_tx",
2599            vec![("id", RedWireParamValue::Int(9))],
2600        );
2601        let rollback =
2602            reddb_wire::redwire::build_query_frame(44, "ROLLBACK").expect("rollback frame");
2603        execute_with_redwire_context(&ctx, Role::Read, || {
2604            assert_eq!(
2605                run_query(&runtime, &prepared, &begin).kind,
2606                MessageKind::Result
2607            );
2608        });
2609        execute_with_redwire_context(&ctx, Role::Read, || {
2610            assert_eq!(
2611                run_typed_insert(&runtime, &insert).kind,
2612                MessageKind::BulkOk
2613            );
2614        });
2615        execute_with_redwire_context(&ctx, Role::Read, || {
2616            assert_eq!(
2617                run_query(&runtime, &prepared, &rollback).kind,
2618                MessageKind::Result
2619            );
2620        });
2621
2622        let selected = runtime
2623            .execute_query("SELECT id FROM redwire_typed_tx")
2624            .expect("select after rollback");
2625        assert!(selected.result.records.is_empty());
2626    }
2627
2628    fn create_graph_collection(runtime: &RedDBRuntime, name: &str) {
2629        let db = runtime.db();
2630        db.store()
2631            .create_collection(name)
2632            .expect("create collection");
2633        let now = std::time::SystemTime::now()
2634            .duration_since(std::time::UNIX_EPOCH)
2635            .unwrap_or_default()
2636            .as_millis();
2637        db.save_collection_contract(crate::physical::CollectionContract {
2638            graph_contract: None,
2639            name: name.to_string(),
2640            description: None,
2641            description_generated: false,
2642            declared_model: crate::catalog::CollectionModel::Graph,
2643            schema_mode: crate::catalog::SchemaMode::Dynamic,
2644            origin: crate::physical::ContractOrigin::Explicit,
2645            version: 1,
2646            created_at_unix_ms: now,
2647            updated_at_unix_ms: now,
2648            default_ttl_ms: None,
2649            vector_dimension: None,
2650            vector_metric: None,
2651            context_index_fields: Vec::new(),
2652            declared_columns: Vec::new(),
2653            table_def: None,
2654            timestamps_enabled: false,
2655            context_index_enabled: false,
2656            metrics_raw_retention_ms: None,
2657            metrics_rollup_policies: Vec::new(),
2658            metrics_tenant_identity: None,
2659            metrics_namespace: None,
2660            append_only: false,
2661            subscriptions: Vec::new(),
2662            analytics_config: Vec::new(),
2663            session_key: None,
2664            session_gap_ms: None,
2665            retention_duration_ms: None,
2666            analytical_storage: None,
2667
2668            ai_policy: None,
2669        })
2670        .expect("save graph contract");
2671    }
2672
2673    #[test]
2674    fn magic_byte_is_0xfe() {
2675        assert_eq!(REDWIRE_MAGIC, 0xFE);
2676    }
2677
2678    #[test]
2679    fn redwire_bulk_insert_graph_rows_returns_ids() {
2680        let runtime = RedDBRuntime::in_memory().expect("runtime");
2681        create_graph_collection(&runtime, "network");
2682
2683        let nodes = bulk_insert_frame(
2684            7,
2685            br#"{"collection":"network","payloads":[{"label":"Host","name":"app"},{"label":"Host","name":"db"}]}"#.to_vec(),
2686        );
2687        let nodes_reply = run_insert_dispatch(&runtime, &nodes);
2688        assert_eq!(nodes_reply.kind, MessageKind::BulkOk);
2689        let node_body: JsonValue =
2690            serde_json::from_slice(&nodes_reply.payload).expect("nodes json");
2691        assert_eq!(
2692            node_body.get("affected").and_then(JsonValue::as_u64),
2693            Some(2)
2694        );
2695        let ids = node_body
2696            .get("ids")
2697            .and_then(JsonValue::as_array)
2698            .expect("node ids");
2699        assert_eq!(ids.len(), 2);
2700
2701        let from = ids[0].as_u64().expect("from id");
2702        let to = ids[1].as_u64().expect("to id");
2703        let edges = bulk_insert_frame(
2704            8,
2705            format!(
2706                r#"{{"collection":"network","payloads":[{{"label":"connects","from":{from},"to":{to},"role":"primary"}}]}}"#
2707            )
2708            .into_bytes(),
2709        );
2710        let edges_reply = run_insert_dispatch(&runtime, &edges);
2711        assert_eq!(edges_reply.kind, MessageKind::BulkOk);
2712        let edge_body: JsonValue =
2713            serde_json::from_slice(&edges_reply.payload).expect("edges json");
2714        assert_eq!(
2715            edge_body.get("affected").and_then(JsonValue::as_u64),
2716            Some(1)
2717        );
2718        assert_eq!(
2719            edge_body
2720                .get("ids")
2721                .and_then(JsonValue::as_array)
2722                .map(|ids| ids.len()),
2723            Some(1)
2724        );
2725    }
2726
2727    #[test]
2728    fn bulk_insert_dispatch_surfaces_row_ids() {
2729        let runtime = RedDBRuntime::in_memory().expect("runtime");
2730
2731        let single = bulk_insert_frame(
2732            9,
2733            br#"{"collection":"rows_rid","payload":{"name":"eve"}}"#.to_vec(),
2734        );
2735        let reply = run_insert_dispatch(&runtime, &single);
2736        assert_eq!(
2737            reply.kind,
2738            MessageKind::BulkOk,
2739            "body={:?}",
2740            String::from_utf8_lossy(&reply.payload)
2741        );
2742        let body: JsonValue = serde_json::from_slice(&reply.payload).expect("single json");
2743        assert_eq!(body.get("affected").and_then(JsonValue::as_u64), Some(1));
2744        assert!(
2745            body.get("id").and_then(JsonValue::as_u64).is_some(),
2746            "single insert must carry the assigned id: {body}"
2747        );
2748
2749        let batch = bulk_insert_frame(
2750            10,
2751            br#"{"collection":"rows_rid","payloads":[{"name":"a"},{"name":"b"}]}"#.to_vec(),
2752        );
2753        let reply = run_insert_dispatch(&runtime, &batch);
2754        assert_eq!(reply.kind, MessageKind::BulkOk);
2755        let body: JsonValue = serde_json::from_slice(&reply.payload).expect("batch json");
2756        assert_eq!(body.get("affected").and_then(JsonValue::as_u64), Some(2));
2757        let ids: Vec<u64> = body
2758            .get("ids")
2759            .and_then(JsonValue::as_array)
2760            .expect("ids array")
2761            .iter()
2762            .map(|id| id.as_u64().expect("numeric id"))
2763            .collect();
2764        assert_eq!(ids.len(), 2);
2765        assert_ne!(ids[0], ids[1], "ids must be distinct");
2766    }
2767
2768    #[test]
2769    fn get_and_delete_dispatch_address_rows_by_rid() {
2770        use reddb_wire::redwire::operations::{
2771            decode_delete_ok_affected, decode_get_result_payload, encode_key_payload,
2772        };
2773        use reddb_wire::redwire::{build_delete_frame, build_get_frame};
2774
2775        let runtime = RedDBRuntime::in_memory().expect("runtime");
2776        let insert = bulk_insert_frame(
2777            11,
2778            br#"{"collection":"rows_rid_del","payload":{"name":"k"}}"#.to_vec(),
2779        );
2780        let reply = run_insert_dispatch(&runtime, &insert);
2781        assert_eq!(reply.kind, MessageKind::BulkOk);
2782        let body: JsonValue = serde_json::from_slice(&reply.payload).expect("insert json");
2783        let rid = body
2784            .get("id")
2785            .and_then(JsonValue::as_u64)
2786            .expect("assigned id");
2787        let rid = rid.to_string();
2788
2789        let get = build_get_frame(12, encode_key_payload("rows_rid_del", &rid)).expect("get");
2790        let reply = run_get(&runtime, &get);
2791        assert_eq!(reply.kind, MessageKind::Result);
2792        let found = decode_get_result_payload(&reply.payload).expect("get payload");
2793        assert_eq!(found.get("found").and_then(|v| v.as_bool()), Some(true));
2794
2795        // A non-numeric id names no row: not found / 0 affected, and the
2796        // text is never spliced into SQL.
2797        for id in ["1 OR 1=1", "'1'", "rid_that_does_not_exist"] {
2798            let get = build_get_frame(13, encode_key_payload("rows_rid_del", id)).expect("get");
2799            let reply = run_get(&runtime, &get);
2800            assert_eq!(reply.kind, MessageKind::Result, "{id:?}");
2801            let found = decode_get_result_payload(&reply.payload).expect("get payload");
2802            assert_eq!(found.get("found").and_then(|v| v.as_bool()), Some(false));
2803
2804            let del = build_delete_frame(13, encode_key_payload("rows_rid_del", id)).expect("del");
2805            let reply = run_delete(&runtime, &del);
2806            assert_eq!(reply.kind, MessageKind::DeleteOk, "{id:?}");
2807            assert_eq!(
2808                decode_delete_ok_affected(&reply.payload).expect("affected"),
2809                0
2810            );
2811        }
2812        // A collection that is not a bare identifier is refused outright.
2813        let del = build_delete_frame(13, encode_key_payload("rows_rid_del WHERE 1=1 --", &rid))
2814            .expect("del");
2815        let reply = run_delete(&runtime, &del);
2816        assert_eq!(reply.kind, MessageKind::Error);
2817
2818        let del = build_delete_frame(14, encode_key_payload("rows_rid_del", &rid)).expect("del");
2819        let reply = run_delete(&runtime, &del);
2820        assert_eq!(reply.kind, MessageKind::DeleteOk);
2821        assert_eq!(
2822            decode_delete_ok_affected(&reply.payload).expect("affected"),
2823            1
2824        );
2825
2826        let reply = run_delete(&runtime, &del);
2827        assert_eq!(reply.kind, MessageKind::DeleteOk);
2828        assert_eq!(
2829            decode_delete_ok_affected(&reply.payload).expect("affected"),
2830            0
2831        );
2832    }
2833
2834    #[test]
2835    fn redwire_query_with_params_preserves_json_columns() {
2836        let runtime = RedDBRuntime::in_memory().expect("runtime");
2837        let prepared = PreparedRegistry::new();
2838        runtime
2839            .execute_query("KV PUT proj.a.b.c.d = 12")
2840            .expect("put nested number");
2841        runtime
2842            .execute_query("KV PUT proj.a.b.e = 'x'")
2843            .expect("put nested string");
2844
2845        let payload =
2846            reddb_wire::query_with_params::encode_query_with_params("LIST KV proj AS JSON", &[])
2847                .expect("encode query with params");
2848        let frame = reddb_wire::redwire::build_query_with_params_frame(99, payload)
2849            .expect("query-with-params frame");
2850        let reply = run_query_with_params(&runtime, &prepared, &frame);
2851
2852        assert_eq!(
2853            reply.kind,
2854            MessageKind::Result,
2855            "body={}",
2856            String::from_utf8_lossy(&reply.payload)
2857        );
2858        let body: JsonValue = serde_json::from_slice(&reply.payload).expect("result json");
2859        let value = body
2860            .get("result")
2861            .and_then(|result| result.get("records"))
2862            .and_then(JsonValue::as_array)
2863            .and_then(|records| records.first())
2864            .and_then(|record| record.get("values"))
2865            .and_then(|values| values.get("value"))
2866            .expect("json value column");
2867
2868        assert_eq!(
2869            value
2870                .get("a")
2871                .and_then(|a| a.get("b"))
2872                .and_then(|b| b.get("c"))
2873                .and_then(|c| c.get("d"))
2874                .and_then(JsonValue::as_f64),
2875            Some(12.0)
2876        );
2877        assert_eq!(
2878            value
2879                .get("a")
2880                .and_then(|a| a.get("b"))
2881                .and_then(|b| b.get("e"))
2882                .and_then(JsonValue::as_str),
2883            Some("x")
2884        );
2885    }
2886
2887    /// The two query frames answer with deliberately different shapes:
2888    /// `Query` (0x01) replies with the summary payload the protocol pins,
2889    /// `QueryWithParams` (0x28) with the full result envelope. Clients pick
2890    /// the frame by the reply they want, so neither may drift into the other.
2891    #[test]
2892    fn redwire_query_replies_summary_and_query_with_params_replies_full_envelope() {
2893        let runtime = RedDBRuntime::in_memory().expect("runtime");
2894        let prepared = PreparedRegistry::new();
2895
2896        let query =
2897            reddb_wire::redwire::build_query_frame(98, "SELECT 7 AS value").expect("query frame");
2898        let query_reply = run_query(&runtime, &prepared, &query);
2899        assert_eq!(query_reply.kind, MessageKind::Result);
2900        let summary =
2901            reddb_wire::redwire::operations::decode_query_result_payload(&query_reply.payload)
2902                .expect("Query replies with the summary payload");
2903        assert_eq!(
2904            summary.get("statement").and_then(|value| value.as_str()),
2905            Some("select")
2906        );
2907        assert_eq!(
2908            summary.get("affected").and_then(|value| value.as_u64()),
2909            Some(0),
2910            "affected is pinned even when it is 0, got {summary}"
2911        );
2912        assert!(
2913            summary.get("result").is_none(),
2914            "Query must not carry the full result envelope, got {summary}"
2915        );
2916
2917        let payload = reddb_wire::query_with_params::encode_query_with_params(
2918            "SELECT $1 AS value",
2919            &[reddb_wire::query_with_params::ParamValue::Int(7)],
2920        )
2921        .expect("encode query with params");
2922        let query_with_params = reddb_wire::redwire::build_query_with_params_frame(99, payload)
2923            .expect("query-with-params frame");
2924        let params_reply = run_query_with_params(&runtime, &prepared, &query_with_params);
2925        assert_eq!(params_reply.kind, MessageKind::Result);
2926        let body: JsonValue =
2927            serde_json::from_slice(&params_reply.payload).expect("full result envelope");
2928        assert_eq!(
2929            body.get("result")
2930                .and_then(|result| result.get("records"))
2931                .and_then(JsonValue::as_array)
2932                .and_then(|records| records.first())
2933                .and_then(|record| record.get("values"))
2934                .and_then(|values| values.get("value"))
2935                .and_then(JsonValue::as_f64),
2936            Some(7.0)
2937        );
2938    }
2939
2940    #[test]
2941    fn cancelled_redwire_query_releases_shared_query_capacity() {
2942        let _lock = env_lock().lock().expect("environment lock");
2943        let _env = EnvGuard::set(&[("RED_MAX_CONCURRENT_QUERIES", "1")]);
2944        let runtime = RedDBRuntime::in_memory().expect("runtime");
2945        let prepared = PreparedRegistry::new();
2946        let query = reddb_wire::redwire::build_query_frame(100, "SELECT 1 AS healthy")
2947            .expect("query frame");
2948
2949        let cancellation = crate::runtime::query_budget::RequestCancellation::new();
2950        let request_scope = cancellation.install();
2951        cancellation.cancel();
2952        let cancelled = run_query(&runtime, &prepared, &query);
2953        assert_eq!(cancelled.kind, MessageKind::Error);
2954        assert!(
2955            String::from_utf8_lossy(&cancelled.payload).contains("duration:query_cancelled"),
2956            "unexpected cancellation payload: {}",
2957            String::from_utf8_lossy(&cancelled.payload)
2958        );
2959        drop(request_scope);
2960
2961        let recovered = run_query(&runtime, &prepared, &query);
2962        assert_eq!(
2963            recovered.kind,
2964            MessageKind::Result,
2965            "cancelled query must release the only shared admission slot"
2966        );
2967    }
2968
2969    /// Issue #2139 AC1 — the prepared frames run on the connection's shared
2970    /// registry, so a prepared id is scoped to the connection that minted it,
2971    /// DDL invalidates the shape, and the kill switch closes both frames.
2972    /// Driven through the same handler + rewrap the session loop uses, so the
2973    /// legacy reply encodings are exercised too.
2974    #[test]
2975    fn redwire_prepared_requests_use_connection_registry_guards() {
2976        let runtime = RedDBRuntime::in_memory().expect("runtime");
2977        runtime
2978            .execute_query("CREATE TABLE redwire_prepared (id INTEGER)")
2979            .expect("create table");
2980        runtime
2981            .execute_query("INSERT INTO redwire_prepared (id) VALUES (7)")
2982            .expect("seed row");
2983        let mut first_connection = crate::wire::listener::PreparedStatements::default();
2984        let second_connection = crate::wire::listener::PreparedStatements::default();
2985
2986        let prepare_payload = reddb_wire::redwire::encode_prepare_payload(
2987            41,
2988            "SELECT * FROM redwire_prepared WHERE id = 7",
2989        )
2990        .expect("encode prepare");
2991        let prepared = rewrap_length_prefixed_handler_response(
2992            &crate::wire::listener::handle_prepare(
2993                &runtime,
2994                &prepare_payload,
2995                &mut first_connection,
2996            ),
2997            100,
2998        );
2999        assert_eq!(prepared.kind, MessageKind::PreparedOk);
3000        let parameter_count = u16::from_le_bytes([prepared.payload[4], prepared.payload[5]]);
3001        assert_eq!(
3002            parameter_count, 1,
3003            "the literal `7` is auto-parameterized into one bind"
3004        );
3005
3006        let execute_payload = reddb_wire::redwire::encode_execute_prepared_payload(
3007            41,
3008            &[reddb_wire::legacy::WireValue::I64(7)],
3009        )
3010        .expect("encode execute prepared");
3011        let executed = rewrap_length_prefixed_handler_response(
3012            &crate::wire::listener::handle_execute_prepared(
3013                &runtime,
3014                &execute_payload,
3015                &first_connection,
3016            ),
3017            101,
3018        );
3019        assert_eq!(executed.kind, MessageKind::Result);
3020
3021        let wrong_connection = rewrap_length_prefixed_handler_response(
3022            &crate::wire::listener::handle_execute_prepared(
3023                &runtime,
3024                &execute_payload,
3025                &second_connection,
3026            ),
3027            102,
3028        );
3029        assert_eq!(wrong_connection.kind, MessageKind::Error);
3030        assert!(
3031            String::from_utf8_lossy(&wrong_connection.payload).contains("unknown prepared stmt_id")
3032        );
3033
3034        runtime
3035            .execute_query("CREATE TABLE redwire_prepared_epoch (id INTEGER)")
3036            .expect("advance DDL epoch");
3037        let stale = rewrap_length_prefixed_handler_response(
3038            &crate::wire::listener::handle_execute_prepared(
3039                &runtime,
3040                &execute_payload,
3041                &first_connection,
3042            ),
3043            103,
3044        );
3045        assert_eq!(stale.kind, MessageKind::Error);
3046        assert_eq!(
3047            String::from_utf8_lossy(&stale.payload),
3048            "prepared_needs_replan"
3049        );
3050
3051        first_connection.registry().disable();
3052        let disabled = rewrap_length_prefixed_handler_response(
3053            &crate::wire::listener::handle_execute_prepared(
3054                &runtime,
3055                &execute_payload,
3056                &first_connection,
3057            ),
3058            104,
3059        );
3060        assert_eq!(disabled.kind, MessageKind::Error);
3061        assert_eq!(
3062            String::from_utf8_lossy(&disabled.payload),
3063            "prepared statements disabled"
3064        );
3065    }
3066
3067    #[test]
3068    fn redwire_query_with_params_request_policy_strengthens_to_ack_n() {
3069        let _env_lock = env_lock().lock().expect("env lock");
3070        let _env = EnvGuard::set(&[
3071            ("RED_PRIMARY_COMMIT_POLICY", "local"),
3072            ("RED_REPLICATION_ACK_TIMEOUT_MS", "20"),
3073            ("RED_COMMIT_FAIL_ON_TIMEOUT", "false"),
3074        ]);
3075        let data_path = temp_data_path("request-ack-n");
3076        let runtime = RedDBRuntime::with_options(
3077            crate::api::RedDBOptions::persistent(&data_path)
3078                .with_replication(crate::replication::ReplicationConfig::primary()),
3079        )
3080        .expect("runtime");
3081        let prepared = PreparedRegistry::new();
3082
3083        let payload = reddb_wire::query_with_params::encode_query_with_params_request(
3084            "INSERT INTO redwire_request_ack (id, name) VALUES (1, 'alpha')",
3085            &[],
3086            &reddb_wire::query_with_params::QueryWithParamsOptions {
3087                commit_policy: Some("ack_n=1".to_string()),
3088            },
3089        )
3090        .expect("encode query with request policy");
3091        let frame = reddb_wire::redwire::build_query_with_params_frame(100, payload)
3092            .expect("query-with-params frame");
3093        let reply = run_query_with_params(&runtime, &prepared, &frame);
3094
3095        assert_eq!(reply.kind, MessageKind::Error);
3096        let body = String::from_utf8_lossy(&reply.payload);
3097        assert!(
3098            body.contains("commit policy timed out") && body.contains("local commit is durable"),
3099            "request ack_n should wait for replica ack, got {body}"
3100        );
3101        let _ = std::fs::remove_file(data_path);
3102    }
3103
3104    #[test]
3105    fn redwire_query_with_params_rejects_request_policy_below_floor() {
3106        let _env_lock = env_lock().lock().expect("env lock");
3107        let _env = EnvGuard::set(&[("RED_PRIMARY_COMMIT_POLICY", "quorum")]);
3108        let runtime = RedDBRuntime::with_options(
3109            crate::api::RedDBOptions::in_memory().with_replication(
3110                crate::replication::ReplicationConfig::primary()
3111                    .with_quorum(crate::replication::QuorumConfig::sync(1)),
3112            ),
3113        )
3114        .expect("runtime");
3115        let prepared = PreparedRegistry::new();
3116        runtime
3117            .execute_query("CREATE TABLE redwire_request_floor (id INTEGER, name TEXT)")
3118            .expect("create table");
3119
3120        let payload = reddb_wire::query_with_params::encode_query_with_params_request(
3121            "INSERT INTO redwire_request_floor (id, name) VALUES (1, 'alpha')",
3122            &[],
3123            &reddb_wire::query_with_params::QueryWithParamsOptions {
3124                commit_policy: Some("local".to_string()),
3125            },
3126        )
3127        .expect("encode query with request policy");
3128        let frame = reddb_wire::redwire::build_query_with_params_frame(101, payload)
3129            .expect("query-with-params frame");
3130        let reply = run_query_with_params(&runtime, &prepared, &frame);
3131
3132        assert_eq!(reply.kind, MessageKind::Error);
3133        let body = String::from_utf8_lossy(&reply.payload);
3134        assert!(
3135            body.contains("COMMIT_POLICY_BELOW_FLOOR"),
3136            "typed floor violation should be surfaced, got {body}"
3137        );
3138
3139        // Ordering is observable, so pin it: the Request seam rejects a
3140        // below-floor policy *before* the write lands. RedWire used to run
3141        // the INSERT and then fail the policy check, leaving the row behind.
3142        let rows = runtime
3143            .execute_query("SELECT id FROM redwire_request_floor")
3144            .expect("read back the rejected write");
3145        assert!(
3146            rows.result.records.is_empty(),
3147            "a policy-rejected write must not be visible"
3148        );
3149    }
3150
3151    /// The pre-write policy check is for mutations only. A read carrying a
3152    /// below-floor policy still returns rows, exactly as it did before the
3153    /// Request seam existed.
3154    #[test]
3155    fn redwire_query_with_params_read_ignores_request_policy_below_floor() {
3156        let _env_lock = env_lock().lock().expect("env lock");
3157        let _env = EnvGuard::set(&[("RED_PRIMARY_COMMIT_POLICY", "quorum")]);
3158        let runtime = RedDBRuntime::with_options(
3159            crate::api::RedDBOptions::in_memory().with_replication(
3160                crate::replication::ReplicationConfig::primary()
3161                    .with_quorum(crate::replication::QuorumConfig::sync(1)),
3162            ),
3163        )
3164        .expect("runtime");
3165        let prepared = PreparedRegistry::new();
3166        runtime
3167            .execute_query("CREATE TABLE redwire_request_read (id INTEGER)")
3168            .expect("create table");
3169        runtime
3170            .execute_query("INSERT INTO redwire_request_read (id) VALUES (1)")
3171            .expect("seed row");
3172
3173        let payload = reddb_wire::query_with_params::encode_query_with_params_request(
3174            "SELECT id FROM redwire_request_read",
3175            &[],
3176            &reddb_wire::query_with_params::QueryWithParamsOptions {
3177                commit_policy: Some("local".to_string()),
3178            },
3179        )
3180        .expect("encode query with request policy");
3181        let frame = reddb_wire::redwire::build_query_with_params_frame(102, payload)
3182            .expect("query-with-params frame");
3183        let reply = run_query_with_params(&runtime, &prepared, &frame);
3184
3185        assert_eq!(
3186            reply.kind,
3187            MessageKind::Result,
3188            "body={}",
3189            String::from_utf8_lossy(&reply.payload)
3190        );
3191    }
3192
3193    // ── Issue #587 — BatchInsertEndpoint RedWire mirror ──────────────
3194    //
3195    // The brief carries the rows + idempotency key in the existing
3196    // `BulkInsert` (0x04) frame: the presence of `idempotency_key` in
3197    // the JSON payload flips the dispatch onto the analytics batch
3198    // path (all-or-nothing commit, AnalyticsSchemaRegistry validation,
3199    // durable receipt shared with HTTP #582 and gRPC #585). Each
3200    // test below maps to one acceptance bullet.
3201
3202    /// Bullet 1 — wire form: `BulkInsert` payload with
3203    /// `idempotency_key` routes to the batch path; success returns a
3204    /// `BulkOk` frame carrying `{"ok":true,"count":N}`. Bullet 5 —
3205    /// every row commits in submission order (we read them back and
3206    /// assert ascending storage order matches insertion order).
3207    #[test]
3208    fn redwire_batch_insert_happy_path_returns_bulkok_with_count() {
3209        let runtime = RedDBRuntime::in_memory().expect("runtime");
3210        runtime
3211            .execute_query("CREATE TABLE events_587_ok (id INTEGER, name TEXT)")
3212            .expect("create table");
3213
3214        let frame = bulk_insert_frame(
3215            100,
3216            br#"{
3217                "collection":"events_587_ok",
3218                "idempotency_key":"k-ok",
3219                "payloads":[
3220                    {"fields":{"id":1,"name":"a"}},
3221                    {"fields":{"id":2,"name":"b"}},
3222                    {"fields":{"id":3,"name":"c"}}
3223                ]
3224            }"#
3225            .to_vec(),
3226        );
3227        let reply = run_insert_dispatch(&runtime, &frame);
3228        assert_eq!(
3229            reply.kind,
3230            MessageKind::BulkOk,
3231            "body={:?}",
3232            String::from_utf8_lossy(&reply.payload)
3233        );
3234        let body: JsonValue = serde_json::from_slice(&reply.payload).expect("ok body json");
3235        assert_eq!(body.get("ok").and_then(JsonValue::as_bool), Some(true));
3236        assert_eq!(body.get("count").and_then(JsonValue::as_u64), Some(3));
3237
3238        // Submission-order commit — every row landed and the scan can
3239        // see them all. (CDC ordering is a property of
3240        // `create_rows_batch`, which the shared
3241        // `process_batch_insert` re-uses; we pin the user-observable
3242        // surface here.)
3243        let qr = runtime
3244            .execute_query("SELECT name FROM events_587_ok ORDER BY id ASC")
3245            .expect("scan");
3246        let names: Vec<String> = qr
3247            .result
3248            .records
3249            .iter()
3250            .filter_map(|record| match record.get("name") {
3251                Some(reddb_types::Value::Text(s)) => Some(s.to_string()),
3252                _ => None,
3253            })
3254            .collect();
3255        assert_eq!(names, vec!["a", "b", "c"]);
3256    }
3257
3258    /// Bullet 3 — row K's failure rolls back the whole batch; the
3259    /// reply is an `Error` frame whose JSON body carries the failing
3260    /// `row_index` so the client can pinpoint the broken row without
3261    /// re-uploading.
3262    #[test]
3263    fn redwire_batch_insert_row_failure_rolls_back_with_row_index() {
3264        let runtime = RedDBRuntime::in_memory().expect("runtime");
3265        runtime
3266            .execute_query("CREATE TABLE events_587_rollback (id INTEGER, name TEXT)")
3267            .expect("create table");
3268
3269        // Row index 1 omits the required `fields` envelope — the parse
3270        // step rejects before any commit fires.
3271        let frame = bulk_insert_frame(
3272            101,
3273            br#"{
3274                "collection":"events_587_rollback",
3275                "idempotency_key":"k-rollback",
3276                "payloads":[
3277                    {"fields":{"id":1,"name":"a"}},
3278                    {"not_fields":{"id":2}},
3279                    {"fields":{"id":3,"name":"c"}}
3280                ]
3281            }"#
3282            .to_vec(),
3283        );
3284        let reply = run_insert_dispatch(&runtime, &frame);
3285        assert_eq!(reply.kind, MessageKind::Error);
3286        let body: JsonValue = serde_json::from_slice(&reply.payload).expect("err body json");
3287        assert_eq!(body.get("ok").and_then(JsonValue::as_bool), Some(false));
3288        assert_eq!(
3289            body.get("code").and_then(JsonValue::as_str),
3290            Some("RowParseFailure")
3291        );
3292        assert_eq!(body.get("row_index").and_then(JsonValue::as_u64), Some(1));
3293
3294        // Storage untouched — row 0 was never committed even though
3295        // it would have parsed cleanly on its own.
3296        let qr = runtime
3297            .execute_query("SELECT name FROM events_587_rollback")
3298            .expect("scan");
3299        assert!(
3300            qr.result.records.is_empty(),
3301            "row 0 leaked despite row 1 rejection: {} rows present",
3302            qr.result.records.len()
3303        );
3304    }
3305
3306    /// Bullet 2 — `idempotency_key` carried in the frame; the
3307    /// durable receipt (shared with HTTP slice 4) replays a
3308    /// previous success byte-for-byte even when the retry's body
3309    /// differs from the original. The HTTP slice 4 already pins the
3310    /// cross-call behaviour at its boundary; this test pins the
3311    /// RedWire boundary plus the cross-transport sharing (a retry on
3312    /// the same key via HTTP returns the body RedWire just produced).
3313    #[test]
3314    fn redwire_batch_insert_idempotency_key_replays_committed_result() {
3315        let runtime = RedDBRuntime::in_memory().expect("runtime");
3316        runtime
3317            .execute_query("CREATE TABLE events_587_dedup (id INTEGER, name TEXT)")
3318            .expect("create table");
3319
3320        // Use a process-unique key so this test doesn't trample
3321        // (or get trampled by) the HTTP-side dedup test that shares
3322        // the global cache.
3323        let key = format!(
3324            "redwire-587-{}",
3325            std::time::SystemTime::now()
3326                .duration_since(std::time::UNIX_EPOCH)
3327                .unwrap()
3328                .as_nanos()
3329        );
3330
3331        let frame1 = bulk_insert_frame(
3332            200,
3333            format!(
3334                r#"{{
3335                    "collection":"events_587_dedup",
3336                    "idempotency_key":"{key}",
3337                    "payloads":[{{"fields":{{"id":1,"name":"first"}}}}]
3338                }}"#
3339            )
3340            .into_bytes(),
3341        );
3342        let reply1 = run_insert_dispatch(&runtime, &frame1);
3343        assert_eq!(reply1.kind, MessageKind::BulkOk);
3344        let body1 = reply1.payload.clone();
3345
3346        // Replay with the same key + DIFFERENT body — the cache
3347        // returns the original bytes verbatim and the second row is
3348        // not committed.
3349        let frame2 = bulk_insert_frame(
3350            201,
3351            format!(
3352                r#"{{
3353                    "collection":"events_587_dedup",
3354                    "idempotency_key":"{key}",
3355                    "payloads":[{{"fields":{{"id":2,"name":"second"}}}}]
3356                }}"#
3357            )
3358            .into_bytes(),
3359        );
3360        let reply2 = run_insert_dispatch(&runtime, &frame2);
3361        assert_eq!(reply2.kind, MessageKind::BulkOk);
3362        assert_eq!(
3363            reply2.payload, body1,
3364            "replay must return committed body byte-for-byte"
3365        );
3366
3367        let qr = runtime
3368            .execute_query("SELECT name FROM events_587_dedup")
3369            .expect("scan");
3370        assert_eq!(
3371            qr.result.records.len(),
3372            1,
3373            "replay re-executed and committed the second row"
3374        );
3375    }
3376
3377    /// Bullet 4 — schema-validation failure mirrors the other
3378    /// transports: a row that the `AnalyticsSchemaRegistry` rejects
3379    /// surfaces as `RowSchemaRejected` with the offending `row_index`,
3380    /// and the batch leaves the collection untouched.
3381    #[test]
3382    fn redwire_batch_insert_schema_validation_rejects_unknown_field() {
3383        use crate::runtime::analytics_schema_registry as reg;
3384
3385        let runtime = RedDBRuntime::in_memory().expect("runtime");
3386        runtime
3387            .execute_query("CREATE TABLE events_587_schema (event_name TEXT, payload TEXT)")
3388            .expect("create table");
3389
3390        let schema =
3391            r#"{"type":"object","properties":{"url":{"type":"string"}},"required":["url"]}"#;
3392        reg::register(runtime.db().store().as_ref(), "click_587", schema).expect("register schema");
3393
3394        let frame = bulk_insert_frame(
3395            400,
3396            br#"{
3397                "collection":"events_587_schema",
3398                "idempotency_key":"k-schema",
3399                "payloads":[
3400                    {"fields":{"event_name":"click_587","payload":"{\"url\":\"/a\"}"}},
3401                    {"fields":{"event_name":"click_587","payload":"{\"url\":\"/b\",\"extra\":1}"}}
3402                ]
3403            }"#
3404            .to_vec(),
3405        );
3406        let reply = run_insert_dispatch(&runtime, &frame);
3407        assert_eq!(reply.kind, MessageKind::Error);
3408        let body: JsonValue = serde_json::from_slice(&reply.payload).expect("err body json");
3409        assert_eq!(
3410            body.get("code").and_then(JsonValue::as_str),
3411            Some("RowSchemaRejected")
3412        );
3413        assert_eq!(body.get("row_index").and_then(JsonValue::as_u64), Some(1));
3414
3415        let qr = runtime
3416            .execute_query("SELECT event_name FROM events_587_schema")
3417            .expect("scan");
3418        assert!(
3419            qr.result.records.is_empty(),
3420            "row 0 leaked despite row 1 schema rejection"
3421        );
3422    }
3423
3424    /// Bullet 4 (cont.) — oversize fails with `BatchTooLarge` and a
3425    /// 413-equivalent status; the storage is never touched.
3426    ///
3427    /// Build one row past the default ceiling rather than mutating
3428    /// `RED_BATCH_MAX_ROWS`. The env var is process-wide and the
3429    /// `cargo test` runner schedules tests in parallel; a `set_var`
3430    /// here leaks into sibling tests in this crate (e.g. the
3431    /// row-failure case sees its 3-row batch flagged as oversize).
3432    /// The HTTP slice 4 test takes the same "build past the default"
3433    /// route for the same reason.
3434    #[test]
3435    fn redwire_batch_insert_oversize_returns_error_before_storage() {
3436        let runtime = RedDBRuntime::in_memory().expect("runtime");
3437        runtime
3438            .execute_query("CREATE TABLE events_587_oversize (id INTEGER, name TEXT)")
3439            .expect("create table");
3440
3441        // Default `red.batch.max_rows = 10_000`; submit one more.
3442        let max = 10_000usize;
3443        let mut payloads = String::with_capacity(max * 32);
3444        payloads.push('[');
3445        for i in 0..(max + 1) {
3446            if i > 0 {
3447                payloads.push(',');
3448            }
3449            payloads.push_str(&format!(r#"{{"fields":{{"id":{i},"name":"x"}}}}"#));
3450        }
3451        payloads.push(']');
3452        let frame_body = format!(
3453            r#"{{"collection":"events_587_oversize","idempotency_key":"k-oversize-587","payloads":{payloads}}}"#
3454        );
3455        let frame = bulk_insert_frame(500, frame_body.into_bytes());
3456        let reply = run_insert_dispatch(&runtime, &frame);
3457
3458        assert_eq!(reply.kind, MessageKind::Error);
3459        let body: JsonValue = serde_json::from_slice(&reply.payload).expect("err body json");
3460        assert_eq!(
3461            body.get("code").and_then(JsonValue::as_str),
3462            Some("BatchTooLarge")
3463        );
3464        let qr = runtime
3465            .execute_query("SELECT name FROM events_587_oversize")
3466            .expect("scan");
3467        assert!(
3468            qr.result.records.is_empty(),
3469            "oversize batch leaked rows into storage"
3470        );
3471    }
3472}
3473
3474#[cfg(test)]
3475mod session_bulk_stream_tests;