saddle-db 0.2.0-rc.19

Saddle managed asynchronous database access and transactions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
//! Production C6 contract for one statically generated optional query.
//!
//! Service hands one opaque admitted execution to this Database-owned,
//! same-task sqlx/Runtime finalizer state machine. Dynamic SQL, pool waiting,
//! Skill generation, write, transaction and multi-row APIs stay outside this
//! closed path.

use std::{
    any::TypeId, future::Future, marker::PhantomData, mem, panic::AssertUnwindSafe, pin::pin,
    task::Poll,
};

use saddle_admission::DbRequestPermit;
use saddle_runtime::db_finalizer::{
    DbQueryPoll, DbQueryTransition, DbTransitionRequest, drive_db_finalizer_with_transition,
};
use sqlx::{
    MySql, Row,
    mysql::{MySqlArguments, MySqlRow},
    query::Query,
};

use crate::Database;
use sealed::{ParameterShape as _, RowShape as _};

const MAX_STATIC_OPERATION_BYTES: usize = 128;
const MAX_STATIC_SQL_BYTES: usize = 65_536;

pub(crate) mod sealed {
    use sqlx::{MySql, mysql::MySqlArguments, query::Query};

    use super::MySqlRow;

    pub trait Field: Sized {
        fn bind<'q>(
            &'q self,
            query: Query<'q, MySql, MySqlArguments>,
        ) -> Query<'q, MySql, MySqlArguments>;

        fn decode(row: &MySqlRow, column: &mut usize) -> std::result::Result<Self, ()>;
    }

    pub trait ParameterShape {
        fn bind<'q>(
            &'q self,
            query: Query<'q, MySql, MySqlArguments>,
        ) -> Query<'q, MySql, MySqlArguments>;
    }

    pub trait RowShape: Sized {
        fn decode(row: &MySqlRow) -> std::result::Result<Self, ()>;
    }
}

/// Saddle-owned scalar fields accepted by the generated DB ABI.
pub trait ManagedDbField: sealed::Field + Send + Sync + 'static {}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[repr(transparent)]
pub struct DbU64(pub u64);

impl sealed::Field for DbU64 {
    fn bind<'q>(
        &'q self,
        query: Query<'q, MySql, MySqlArguments>,
    ) -> Query<'q, MySql, MySqlArguments> {
        query.bind(self.0)
    }

    fn decode(row: &MySqlRow, column: &mut usize) -> std::result::Result<Self, ()> {
        let value = row.try_get(*column).map_err(|_| ())?;
        *column += 1;
        Ok(Self(value))
    }
}
impl ManagedDbField for DbU64 {}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[repr(transparent)]
pub struct DbI64(pub i64);

impl sealed::Field for DbI64 {
    fn bind<'q>(
        &'q self,
        query: Query<'q, MySql, MySqlArguments>,
    ) -> Query<'q, MySql, MySqlArguments> {
        query.bind(self.0)
    }

    fn decode(row: &MySqlRow, column: &mut usize) -> std::result::Result<Self, ()> {
        let value = row.try_get(*column).map_err(|_| ())?;
        *column += 1;
        Ok(Self(value))
    }
}
impl ManagedDbField for DbI64 {}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[repr(transparent)]
pub struct DbBool(pub bool);

impl sealed::Field for DbBool {
    fn bind<'q>(
        &'q self,
        query: Query<'q, MySql, MySqlArguments>,
    ) -> Query<'q, MySql, MySqlArguments> {
        query.bind(self.0)
    }

    fn decode(row: &MySqlRow, column: &mut usize) -> std::result::Result<Self, ()> {
        let value = row.try_get(*column).map_err(|_| ())?;
        *column += 1;
        Ok(Self(value))
    }
}
impl ManagedDbField for DbBool {}

/// Inline bytes with a compile-time capacity. Construction never allocates.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FixedDbBytes<const N: usize> {
    bytes: [u8; N],
    length: usize,
}

impl<const N: usize> FixedDbBytes<N> {
    pub const fn empty() -> Self {
        Self {
            bytes: [0; N],
            length: 0,
        }
    }

    pub fn try_from_slice(value: &[u8]) -> Result<Self, QueryOptionalContractError> {
        if value.len() > N {
            return Err(QueryOptionalContractError::ValueTooLarge);
        }
        let mut output = Self::empty();
        output.bytes[..value.len()].copy_from_slice(value);
        output.length = value.len();
        Ok(output)
    }

    pub const fn capacity(&self) -> usize {
        N
    }

    pub const fn len(&self) -> usize {
        self.length
    }

    pub const fn is_empty(&self) -> bool {
        self.length == 0
    }

    pub fn as_slice(&self) -> &[u8] {
        &self.bytes[..self.length]
    }
}

impl<const N: usize> sealed::Field for FixedDbBytes<N> {
    fn bind<'q>(
        &'q self,
        query: Query<'q, MySql, MySqlArguments>,
    ) -> Query<'q, MySql, MySqlArguments> {
        query.bind(self.as_slice())
    }

    fn decode(row: &MySqlRow, column: &mut usize) -> std::result::Result<Self, ()> {
        let value: &[u8] = row.try_get(*column).map_err(|_| ())?;
        *column += 1;
        Self::try_from_slice(value).map_err(|_| ())
    }
}
impl<const N: usize> ManagedDbField for FixedDbBytes<N> {}

/// Fixed-layout product used by generated parameter and row shapes.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct DbPair<A: ManagedDbField, B: ManagedDbField>(pub A, pub B);

impl<A: ManagedDbField, B: ManagedDbField> sealed::Field for DbPair<A, B> {
    fn bind<'q>(
        &'q self,
        query: Query<'q, MySql, MySqlArguments>,
    ) -> Query<'q, MySql, MySqlArguments> {
        self.1.bind(self.0.bind(query))
    }

    fn decode(row: &MySqlRow, column: &mut usize) -> std::result::Result<Self, ()> {
        Ok(Self(A::decode(row, column)?, B::decode(row, column)?))
    }
}
impl<A: ManagedDbField, B: ManagedDbField> ManagedDbField for DbPair<A, B> {}

/// A concrete generated parameter tuple. It contains no `String`, `Vec`,
/// dynamic SQL, driver value, or allocator handle.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[repr(transparent)]
pub struct ManagedQueryParameters<T: ManagedDbField>(pub T);

impl<T: ManagedDbField> sealed::ParameterShape for ManagedQueryParameters<T> {
    fn bind<'q>(
        &'q self,
        query: Query<'q, MySql, MySqlArguments>,
    ) -> Query<'q, MySql, MySqlArguments> {
        self.0.bind(query)
    }
}

pub trait QueryOptionalParameterShape:
    sealed::ParameterShape + Send + Sync + Sized + 'static
{
}

impl<T: ManagedDbField> QueryOptionalParameterShape for ManagedQueryParameters<T> {}

/// One concrete generated row. Column order and field types are in its Rust
/// type rather than discovered through a dynamic row accessor.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[repr(transparent)]
pub struct ManagedQueryRow<T: ManagedDbField>(pub T);

impl<T: ManagedDbField> sealed::RowShape for ManagedQueryRow<T> {
    fn decode(row: &MySqlRow) -> std::result::Result<Self, ()> {
        let mut column = 0;
        let value = T::decode(row, &mut column)?;
        if column != row.len() {
            return Err(());
        }
        Ok(Self(value))
    }
}

pub trait QueryOptionalRowShape: sealed::RowShape + Send + Sync + Sized + 'static {}

impl<T: ManagedDbField> QueryOptionalRowShape for ManagedQueryRow<T> {}

/// The only C6.1 result cardinality: zero or one concrete managed row.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[repr(transparent)]
pub struct ManagedOptionalRow<R: QueryOptionalRowShape>(pub Option<R>);

impl<R: QueryOptionalRowShape> ManagedOptionalRow<R> {
    pub const fn none() -> Self {
        Self(None)
    }

    pub const fn some(row: R) -> Self {
        Self(Some(row))
    }

    pub const fn as_ref(&self) -> Option<&R> {
        self.0.as_ref()
    }

    pub fn into_option(self) -> Option<R> {
        self.0
    }
}

/// Implemented only in generated artifact code for a statically known query.
///
/// `SQL` and `OPERATION` are startup/codegen facts. They are never supplied to
/// an admitted invocation.
pub trait StaticQueryOptionalOperation: Send + 'static {
    type Parameters: QueryOptionalParameterShape;
    type Row: QueryOptionalRowShape;

    const OPERATION: &'static str;
    const SQL: &'static str;
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum QueryOptionalContractError {
    InvalidOperation,
    InvalidSql,
    EmptyShape,
    SizeOverflow,
    ValueTooLarge,
}

/// Fixed-width production failures for the closed `query_optional` executor.
///
/// The 0.1 [`crate::SaddleError`] facade owns a `String` and therefore cannot
/// cross an admitted 0.2 query path. Generated Service code maps this closed
/// classification only after Database Finalizing has completed.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum QueryOptionalExecutionError {
    ConnectionUnavailable,
    QueryFailed,
    Cancelled,
    Shutdown,
    InvalidRow,
    FinalizerFailed,
}

impl QueryOptionalExecutionError {
    pub const fn code(self) -> &'static str {
        match self {
            Self::ConnectionUnavailable => "db.connection_unavailable",
            Self::QueryFailed => "db.query_failed",
            Self::Cancelled => "db.query_cancelled",
            Self::Shutdown => "db.query_shutdown",
            Self::InvalidRow => "db.invalid_column",
            Self::FinalizerFailed => "db.finalizer_failed",
        }
    }
}

/// Machine-readable physical finalization facts for generated profiles.
///
/// Cancel, shutdown and panic never await server I/O: the checked-out pool
/// connection is synchronously converted back into a pool size permit and its
/// poisoned raw socket is dropped in the same Finalizing poll. Normal query
/// completion may still use sqlx's explicit return-and-ping path and therefore
/// requires Runtime's independent termination bound.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct QueryOptionalFinalizationProof {
    cancel_external_io_awaits: u8,
    shutdown_external_io_awaits: u8,
    panic_external_io_awaits: u8,
    releases_pool_size_before_permit: bool,
    normal_return_requires_termination_bound: bool,
}

impl QueryOptionalFinalizationProof {
    const PRODUCTION: Self = Self {
        cancel_external_io_awaits: 0,
        shutdown_external_io_awaits: 0,
        panic_external_io_awaits: 0,
        releases_pool_size_before_permit: true,
        normal_return_requires_termination_bound: true,
    };

    pub const fn cancel_external_io_awaits(self) -> u8 {
        self.cancel_external_io_awaits
    }

    pub const fn shutdown_external_io_awaits(self) -> u8 {
        self.shutdown_external_io_awaits
    }

    pub const fn panic_external_io_awaits(self) -> u8 {
        self.panic_external_io_awaits
    }

    pub const fn releases_pool_size_before_permit(self) -> bool {
        self.releases_pool_size_before_permit
    }

    pub const fn normal_return_requires_termination_bound(self) -> bool {
        self.normal_return_requires_termination_bound
    }
}

/// Returns the sealed proof consumed by generated Runtime profiles.
#[doc(hidden)]
pub const fn query_optional_finalization_proof() -> QueryOptionalFinalizationProof {
    QueryOptionalFinalizationProof::PRODUCTION
}

/// Domain demand contributed by one operation to a generated route plan.
///
/// The route generator combines dependencies with `max`, not by counting call
/// sites. Admission will later reserve this demand atomically; this slice does
/// not create a permit or queue.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct QueryOptionalCreditDemand {
    connections: u32,
    operations: u32,
}

impl QueryOptionalCreditDemand {
    const ONE: Self = Self {
        connections: 1,
        operations: 1,
    };

    pub const fn connections(self) -> u32 {
        self.connections
    }

    pub const fn operations(self) -> u32 {
        self.operations
    }

    pub const fn merge_route_max(self, other: Self) -> Self {
        Self {
            connections: if self.connections > other.connections {
                self.connections
            } else {
                other.connections
            },
            operations: if self.operations > other.operations {
                self.operations
            } else {
                other.operations
            },
        }
    }
}

/// Type-derived contribution to the immutable route resource plan.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct QueryOptionalLayout {
    operation: TypeId,
    parameter_bytes: usize,
    optional_row_bytes: usize,
    credits: QueryOptionalCreditDemand,
}

impl QueryOptionalLayout {
    pub const fn parameter_bytes(self) -> usize {
        self.parameter_bytes
    }

    pub const fn optional_row_bytes(self) -> usize {
        self.optional_row_bytes
    }

    pub const fn credits(self) -> QueryOptionalCreditDemand {
        self.credits
    }

    pub fn belongs_to<O: StaticQueryOptionalOperation>(self) -> bool {
        self.operation == TypeId::of::<O>()
    }
}

/// Statically typed proof for one generated operation.
///
/// There is no numeric, string, SQL, or identity constructor. Generated code
/// obtains it by binding the operation marker and its concrete ABI types.
#[derive(Clone, Copy, Debug)]
pub struct QueryOptionalOperationProof<O: StaticQueryOptionalOperation> {
    layout: QueryOptionalLayout,
    _operation: PhantomData<fn() -> O>,
}

impl<O: StaticQueryOptionalOperation> QueryOptionalOperationProof<O> {
    pub fn bind() -> Result<Self, QueryOptionalContractError> {
        validate_operation(O::OPERATION)?;
        validate_sql(O::SQL)?;
        let parameter_bytes = mem::size_of::<O::Parameters>();
        let optional_row_bytes = mem::size_of::<ManagedOptionalRow<O::Row>>();
        if parameter_bytes == 0 || optional_row_bytes == 0 {
            return Err(QueryOptionalContractError::EmptyShape);
        }
        parameter_bytes
            .checked_add(optional_row_bytes)
            .ok_or(QueryOptionalContractError::SizeOverflow)?;
        Ok(Self {
            layout: QueryOptionalLayout {
                operation: TypeId::of::<O>(),
                parameter_bytes,
                optional_row_bytes,
                credits: QueryOptionalCreditDemand::ONE,
            },
            _operation: PhantomData,
        })
    }

    pub const fn layout(&self) -> QueryOptionalLayout {
        self.layout
    }

    /// Binds concrete parameters to the same operation type as the proof.
    pub fn invocation(self, parameters: O::Parameters) -> QueryOptionalInvocation<O> {
        QueryOptionalInvocation {
            layout: self.layout,
            parameters,
            _operation: PhantomData,
        }
    }
}

/// Pre-execution value that cannot carry dynamic SQL or a mismatched ABI.
pub struct QueryOptionalInvocation<O: StaticQueryOptionalOperation> {
    layout: QueryOptionalLayout,
    parameters: O::Parameters,
    _operation: PhantomData<fn() -> O>,
}

impl<O: StaticQueryOptionalOperation> QueryOptionalInvocation<O> {
    pub const fn layout(&self) -> QueryOptionalLayout {
        self.layout
    }

    pub fn parameters(&self) -> &O::Parameters {
        &self.parameters
    }

    pub fn into_parameters(self) -> O::Parameters {
        self.parameters
    }
}

/// Linear, pre-execution ownership accepted by the future Database executor.
///
/// It exposes neither the admitted permit nor query inputs. Service's
/// generated compiled dispatcher is the only production constructor, and
/// Database consumes this whole value into its fixed query/finalizer state
/// machine.
pub struct QueryOptionalExecution<O: StaticQueryOptionalOperation> {
    permit: DbRequestPermit,
    invocation: QueryOptionalInvocation<O>,
}

impl<O: StaticQueryOptionalOperation> QueryOptionalExecution<O> {
    /// Cross-crate internal constructor used only by Service's sealed,
    /// consuming handoff. It never exposes a raw permit.
    #[doc(hidden)]
    pub fn from_compiled_handoff(
        permit: DbRequestPermit,
        invocation: QueryOptionalInvocation<O>,
    ) -> Self {
        Self { permit, invocation }
    }

    fn into_parts(self) -> (DbRequestPermit, QueryOptionalInvocation<O>) {
        (self.permit, self.invocation)
    }
}

impl Database {
    /// Executes one generated, statically sealed zero-or-one-row query.
    ///
    /// The admitted permit and physical connection remain in this request
    /// Future until Runtime observes the owning return-to-pool Future finish.
    #[doc(hidden)]
    pub async fn execute_query_optional<O, C, S>(
        &self,
        execution: QueryOptionalExecution<O>,
        cancel: C,
        shutdown: S,
    ) -> Result<ManagedOptionalRow<O::Row>, QueryOptionalExecutionError>
    where
        O: StaticQueryOptionalOperation,
        C: Future + Unpin + Send + 'static,
        S: Future + Unpin + Send + 'static,
    {
        let pool = self.pool.clone();
        drive_db_finalizer_with_transition(cancel, shutdown, move |transition| {
            execute_with_transition(pool, execution, transition)
        })
        .await
        .map_err(|_| QueryOptionalExecutionError::FinalizerFailed)
        .and_then(|result| result)
    }
}

async fn execute_with_transition<O, C, S>(
    pool: sqlx::MySqlPool,
    execution: QueryOptionalExecution<O>,
    mut transition: DbQueryTransition<C, S>,
) -> std::result::Result<
    saddle_runtime::db_finalizer::DbFinalizingOutput<
        Result<ManagedOptionalRow<O::Row>, QueryOptionalExecutionError>,
        impl Future<Output = ()> + Send + 'static,
    >,
    saddle_admission::AdmissionError,
>
where
    O: StaticQueryOptionalOperation,
    C: Future + Unpin + Send + 'static,
    S: Future + Unpin + Send + 'static,
{
    let (permit, invocation) = execution.into_parts();
    let mut connection = pool.try_acquire();
    let (value, physical) = if let Some(connection) = connection.as_mut() {
        let query = async {
            let result = invocation
                .parameters()
                .bind(sqlx::query::<MySql>(O::SQL))
                .fetch_optional(&mut **connection)
                .await;
            result
                .map_err(map_execution_error)
                .and_then(|row| decode_optional::<O>(row.as_ref()))
        };
        let mut query = pin!(query);
        let outcome = std::future::poll_fn(|context| {
            match std::panic::catch_unwind(AssertUnwindSafe(|| {
                transition.poll_query(&permit, query.as_mut(), context)
            })) {
                Ok(Poll::Ready(output)) => Poll::Ready(Ok(output)),
                Ok(Poll::Pending) => Poll::Pending,
                Err(panic) => Poll::Ready(Err(panic)),
            }
        })
        .await;
        match outcome {
            Ok(DbQueryPoll::Ready(result)) => {
                let physical = if result
                    .as_ref()
                    .is_err_and(|error| error.requires_poison_discard())
                {
                    PhysicalFinalization::PoisonDiscard
                } else {
                    PhysicalFinalization::ReturnToPool
                };
                (result, physical)
            }
            Ok(DbQueryPoll::Transition(DbTransitionRequest::Cancel)) => (
                Err(QueryOptionalExecutionError::Cancelled),
                PhysicalFinalization::PoisonDiscard,
            ),
            Ok(DbQueryPoll::Transition(DbTransitionRequest::Shutdown)) => (
                Err(QueryOptionalExecutionError::Shutdown),
                PhysicalFinalization::PoisonDiscard,
            ),
            Err(_) => (
                Err(QueryOptionalExecutionError::QueryFailed),
                PhysicalFinalization::PoisonDiscard,
            ),
        }
    } else {
        (
            Err(QueryOptionalExecutionError::ConnectionUnavailable),
            PhysicalFinalization::ReturnToPool,
        )
    };
    let return_to_pool = async move {
        if let Some(mut connection) = connection.take() {
            match physical {
                PhysicalFinalization::ReturnToPool => connection.return_to_pool().await,
                PhysicalFinalization::PoisonDiscard => {
                    // sqlx calls this an attached pool connection "detach".
                    // It is a synchronous ownership conversion, not a detached
                    // task: dropping the raw MySQL connection closes its socket
                    // and dropping sqlx's guard decrements pool size here.
                    drop(connection.detach());
                }
            }
        }
    };
    transition.begin_finalizing(value, permit, return_to_pool)
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PhysicalFinalization {
    ReturnToPool,
    PoisonDiscard,
}

fn decode_optional<O: StaticQueryOptionalOperation>(
    row: Option<&MySqlRow>,
) -> Result<ManagedOptionalRow<O::Row>, QueryOptionalExecutionError> {
    row.map(|row| O::Row::decode(row).map(ManagedOptionalRow::some))
        .transpose()
        .map(|row| row.unwrap_or_else(ManagedOptionalRow::none))
        .map_err(|_| QueryOptionalExecutionError::InvalidRow)
}

fn map_execution_error(error: sqlx::Error) -> QueryOptionalExecutionError {
    match error {
        sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed | sqlx::Error::Io(_) => {
            QueryOptionalExecutionError::ConnectionUnavailable
        }
        _ => QueryOptionalExecutionError::QueryFailed,
    }
}

impl QueryOptionalExecutionError {
    fn requires_poison_discard(self) -> bool {
        matches!(
            self,
            Self::ConnectionUnavailable | Self::QueryFailed | Self::Cancelled | Self::Shutdown
        )
    }
}

fn validate_operation(operation: &str) -> Result<(), QueryOptionalContractError> {
    if operation.is_empty()
        || operation.len() > MAX_STATIC_OPERATION_BYTES
        || !operation
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
    {
        return Err(QueryOptionalContractError::InvalidOperation);
    }
    Ok(())
}

fn validate_sql(sql: &str) -> Result<(), QueryOptionalContractError> {
    if sql.trim().is_empty() || sql.len() > MAX_STATIC_SQL_BYTES {
        return Err(QueryOptionalContractError::InvalidSql);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::{
        env, io,
        pin::Pin,
        process::Command,
        task::{Context, Poll},
        time::{Duration, Instant},
    };

    use saddle_admission::{
        AdmissionError, DbCreditProfile, DbRouteCreditDemand, DbRouteResources, EntryIoAuditPlan,
        EntryReadPoll, ManagedBytes, ManagedResponse, OfficialTokioEntryIoAttemptOutcome,
        OfficialTokioRegistrationProfile, ProcessLedger, RequestMemory, ResourceConfig,
        ResponseWritePoll,
    };
    use saddle_core::ComponentLifecycle;
    use saddle_observability::{Observer, ObserverConfig};
    use sqlx::{Connection, mysql::MySqlConnection};

    use super::*;

    struct FindUser;

    impl StaticQueryOptionalOperation for FindUser {
        type Parameters = ManagedQueryParameters<DbU64>;
        type Row = ManagedQueryRow<DbPair<DbU64, DbBool>>;

        const OPERATION: &'static str = "users.find";
        const SQL: &'static str = "SELECT id, active FROM users WHERE id = ?";
    }

    struct FindOrder;

    impl StaticQueryOptionalOperation for FindOrder {
        type Parameters = ManagedQueryParameters<DbU64>;
        type Row = ManagedQueryRow<DbU64>;

        const OPERATION: &'static str = "orders.find";
        const SQL: &'static str = "SELECT id FROM orders WHERE id = ?";
    }

    #[test]
    fn proof_is_bound_to_static_operation_and_concrete_shapes() {
        let proof = QueryOptionalOperationProof::<FindUser>::bind().unwrap();
        assert!(proof.layout().belongs_to::<FindUser>());
        assert!(!proof.layout().belongs_to::<FindOrder>());
        assert_eq!(proof.layout().parameter_bytes(), mem::size_of::<DbU64>());
        assert_eq!(
            proof.layout().optional_row_bytes(),
            mem::size_of::<ManagedOptionalRow<<FindUser as StaticQueryOptionalOperation>::Row>>()
        );
        assert_eq!(proof.layout().credits().connections(), 1);
        assert_eq!(proof.layout().credits().operations(), 1);

        let invocation = proof.invocation(ManagedQueryParameters(DbU64(7)));
        assert_eq!(invocation.parameters().0, DbU64(7));
    }

    #[test]
    fn route_credit_composition_uses_max_not_call_count() {
        let user = QueryOptionalOperationProof::<FindUser>::bind()
            .unwrap()
            .layout()
            .credits();
        let order = QueryOptionalOperationProof::<FindOrder>::bind()
            .unwrap()
            .layout()
            .credits();
        let route = user.merge_route_max(order).merge_route_max(user);
        assert_eq!(route.connections(), 1);
        assert_eq!(route.operations(), 1);
    }

    #[test]
    fn fixed_bytes_reject_growth_without_allocation() {
        let value = FixedDbBytes::<4>::try_from_slice(b"1234").unwrap();
        assert_eq!(value.as_slice(), b"1234");
        assert_eq!(
            FixedDbBytes::<4>::try_from_slice(b"12345"),
            Err(QueryOptionalContractError::ValueTooLarge)
        );
    }

    #[derive(Debug)]
    struct EmptySql;

    impl StaticQueryOptionalOperation for EmptySql {
        type Parameters = ManagedQueryParameters<DbU64>;
        type Row = ManagedQueryRow<DbU64>;

        const OPERATION: &'static str = "users.find";
        const SQL: &'static str = "";
    }

    #[test]
    fn invalid_generated_facts_fail_at_startup_binding() {
        assert_eq!(
            QueryOptionalOperationProof::<EmptySql>::bind().unwrap_err(),
            QueryOptionalContractError::InvalidSql
        );
    }

    struct ProductionSuccess;
    struct ProductionNone;
    struct ProductionError;
    struct ProductionSlow;
    struct ProductionPanic;
    struct ProductionLockWait;

    macro_rules! u64_operation {
        ($operation:ty, $name:literal, $sql:literal) => {
            impl StaticQueryOptionalOperation for $operation {
                type Parameters = ManagedQueryParameters<DbU64>;
                type Row = ManagedQueryRow<DbU64>;

                const OPERATION: &'static str = $name;
                const SQL: &'static str = $sql;
            }
        };
    }

    u64_operation!(
        ProductionSuccess,
        "production.success",
        "SELECT CAST(? AS UNSIGNED)"
    );
    u64_operation!(
        ProductionNone,
        "production.none",
        "SELECT CAST(? AS UNSIGNED) WHERE FALSE"
    );
    u64_operation!(
        ProductionError,
        "production.error",
        "SELECT id FROM saddle_c6_missing_table WHERE id = ?"
    );
    u64_operation!(
        ProductionSlow,
        "production.slow",
        "SELECT CAST(? AS UNSIGNED) FROM (SELECT SLEEP(0.05)) AS delayed"
    );
    u64_operation!(
        ProductionLockWait,
        "production.lock_wait",
        "SELECT id FROM saddle_c6_lock_wait WHERE id = ? FOR UPDATE"
    );

    struct PanicRow;

    impl sealed::RowShape for PanicRow {
        fn decode(_: &MySqlRow) -> std::result::Result<Self, ()> {
            panic!("generated row decode panic")
        }
    }

    impl QueryOptionalRowShape for PanicRow {}

    impl StaticQueryOptionalOperation for ProductionPanic {
        type Parameters = ManagedQueryParameters<DbU64>;
        type Row = PanicRow;

        const OPERATION: &'static str = "production.panic";
        const SQL: &'static str = "SELECT CAST(? AS UNSIGNED)";
    }

    struct EntryConnection;
    struct ReadyRead;
    struct ReadyWrite;

    impl EntryReadPoll<EntryConnection> for ReadyRead {
        fn poll_read(
            &mut self,
            _: &mut EntryConnection,
            memory: &RequestMemory,
            _: &mut Context<'_>,
        ) -> Poll<std::result::Result<ManagedBytes, AdmissionError>> {
            Poll::Ready(memory.try_bytes(&[]))
        }
    }

    impl ResponseWritePoll<EntryConnection> for ReadyWrite {
        fn poll_write(
            &mut self,
            _: &mut EntryConnection,
            response: &ManagedResponse,
            _: &mut Context<'_>,
        ) -> Poll<std::result::Result<(), AdmissionError>> {
            assert!(response.as_slice().is_empty());
            Poll::Ready(Ok(()))
        }
    }

    struct FixedSignal {
        polls_before_ready: Option<u8>,
    }

    impl FixedSignal {
        const fn pending() -> Self {
            Self {
                polls_before_ready: None,
            }
        }

        const fn after_pending_poll() -> Self {
            Self {
                polls_before_ready: Some(1),
            }
        }
    }

    impl Future for FixedSignal {
        type Output = ();

        fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<()> {
            match self.polls_before_ready {
                None => Poll::Pending,
                Some(0) => Poll::Ready(()),
                Some(remaining) => {
                    self.polls_before_ready = Some(remaining - 1);
                    context.waker().wake_by_ref();
                    Poll::Pending
                }
            }
        }
    }

    fn production_config(
        registration: OfficialTokioRegistrationProfile,
        task_reserve: usize,
    ) -> ResourceConfig {
        let process_state_reserve = ProcessLedger::minimum_process_state_reserve_with_waiters(1, 1)
            .unwrap()
            + ProcessLedger::official_tokio_state_reserve(registration).unwrap();
        ResourceConfig {
            managed_capacity: 4_096,
            entry_reserve: 64,
            framework_reserve: 1024 * 1024,
            task_reserve,
            process_state_reserve,
            system_estimate: 1024 * 1024,
            safety_margin: 1024 * 1024,
            process_limit: 4_096
                + 64
                + 1024 * 1024
                + task_reserve
                + process_state_reserve
                + 2 * 1024 * 1024,
            max_active_requests: 1,
        }
    }

    fn entry_plan() -> EntryIoAuditPlan {
        EntryIoAuditPlan::locked_linux_x86_64_tokio_1_53_1(64, 64, &[]).unwrap()
    }

    #[derive(Clone, Copy)]
    enum TestServerAction {
        Responsive,
        Stop(u32),
        Terminate(u32),
    }

    async fn run_production_mode<O, C, S>(
        url: &str,
        invocation: QueryOptionalInvocation<O>,
        cancel: C,
        shutdown: S,
        expected_code: Option<&'static str>,
        expected_row: bool,
    ) where
        O: StaticQueryOptionalOperation,
        O::Parameters: Unpin,
        C: Future<Output = ()> + Unpin + Send + 'static,
        S: Future<Output = ()> + Unpin + Send + 'static,
    {
        run_production_mode_with_server(
            url,
            invocation,
            cancel,
            shutdown,
            expected_code,
            expected_row,
            TestServerAction::Responsive,
        )
        .await;
    }

    #[allow(
        clippy::too_many_arguments,
        reason = "the fixture keeps every physical finalization outcome explicit"
    )]
    async fn run_production_mode_with_server<O, C, S>(
        url: &str,
        invocation: QueryOptionalInvocation<O>,
        cancel: C,
        shutdown: S,
        expected_code: Option<&'static str>,
        expected_row: bool,
        server_action: TestServerAction,
    ) where
        O: StaticQueryOptionalOperation,
        O::Parameters: Unpin,
        C: Future<Output = ()> + Unpin + Send + 'static,
        S: Future<Output = ()> + Unpin + Send + 'static,
    {
        let observer = Observer::with_writer(ObserverConfig::default(), io::sink()).unwrap();
        let database = Database::connect(
            crate::DatabaseConfig::new(url).max_connections(1),
            observer.clone(),
        )
        .await
        .unwrap();
        assert_eq!((database.pool.size(), database.pool.num_idle()), (1, 1));

        let registration = OfficialTokioRegistrationProfile {
            listener: 1,
            transport_connections: 1,
            runtime_fixed: 1,
        };
        let task_reserve = 1024 * 1024;
        let ledger =
            ProcessLedger::new_with_waiters(production_config(registration, task_reserve), 1)
                .unwrap();
        let runtime_domain = ledger.prepare_official_tokio_domain(registration).unwrap();
        let allocation = ledger
            .prepare_process_allocation_profile(usize::MAX)
            .unwrap();
        let db_domain = ledger
            .prepare_db_domain(DbCreditProfile {
                connections: 1,
                operations: 1,
            })
            .unwrap();
        let demand = DbRouteCreditDemand::new(1, 1).unwrap();
        let database_for_task = database.clone();

        let outcome = ledger.attempt_official_tokio_entry_io(
            &runtime_domain,
            DbRouteResources::required(&db_domain, demand),
            4_096,
            task_reserve,
            entry_plan(),
            entry_plan(),
            |_| (EntryConnection, ReadyRead, ReadyWrite),
            move |_, permit, memory| {
                let execution = QueryOptionalExecution::from_compiled_handoff(
                    permit.expect("DB route owns one permit"),
                    invocation,
                );
                let response = memory.try_response(&[]).unwrap();
                async move {
                    let result = database_for_task
                        .execute_query_optional(execution, cancel, shutdown)
                        .await;
                    match expected_code {
                        Some(code) => match result {
                            Ok(_) => panic!("query exit unexpectedly succeeded"),
                            Err(error) if code == "db.cancel_or_disconnect" => assert!(
                                matches!(
                                    error,
                                    QueryOptionalExecutionError::Cancelled
                                        | QueryOptionalExecutionError::ConnectionUnavailable
                                ),
                                "disconnect race returned unexpected error: {error:?}"
                            ),
                            Err(error) => assert_eq!(error.code(), code),
                        },
                        None => assert_eq!(result.unwrap().as_ref().is_some(), expected_row),
                    }
                    response
                }
            },
        );
        let envelope = match outcome {
            OfficialTokioEntryIoAttemptOutcome::Ready(envelope) => envelope,
            _ => panic!("fixed production DB resources must admit"),
        };
        let layout = (
            std::mem::size_of_val(&envelope),
            std::mem::align_of_val(&envelope),
        );
        assert!(layout.0 <= task_reserve);
        assert!(layout.1.is_power_of_two());
        eprintln!(
            "operation={} envelope_size={} envelope_align={} tested_reserve={}",
            O::OPERATION,
            layout.0,
            layout.1,
            task_reserve
        );
        match server_action {
            TestServerAction::Responsive => {}
            TestServerAction::Stop(pid) => {
                assert!(
                    Command::new("kill")
                        .args(["-STOP", &pid.to_string()])
                        .status()
                        .unwrap()
                        .success()
                );
            }
            TestServerAction::Terminate(pid) => {
                assert!(
                    Command::new("kill")
                        .args(["-TERM", &pid.to_string()])
                        .status()
                        .unwrap()
                        .success()
                );
            }
        }
        let finalization_started = Instant::now();
        let (envelope, task_slot) = envelope.into_runtime_parts();
        tokio::spawn(envelope).await.unwrap().unwrap();
        drop(task_slot);
        let finalization_elapsed = finalization_started.elapsed();
        if let TestServerAction::Stop(pid) = server_action {
            assert!(
                Command::new("kill")
                    .args(["-CONT", &pid.to_string()])
                    .status()
                    .unwrap()
                    .success()
            );
        }
        if !matches!(server_action, TestServerAction::Responsive) {
            assert!(
                finalization_elapsed < Duration::from_secs(1),
                "poison-discard exceeded the existing generated attempt bound: {finalization_elapsed:?}"
            );
        }

        assert_eq!(
            database.pool.num_idle(),
            database.pool.size() as usize,
            "physical return or close must precede request completion"
        );
        assert_eq!(database.pool.size(), u32::from(expected_code.is_none()));
        assert_eq!(db_domain.snapshot().unwrap().connections_in_use, 0);
        assert_eq!(db_domain.snapshot().unwrap().operations_in_use, 0);
        drop(db_domain);
        drop(runtime_domain);
        assert!(!allocation.finish().unwrap().breached);
        assert_eq!(ledger.try_shutdown().unwrap().active_accounts, 0);
        database.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn real_mariadb_production_query_optional_closes_six_exits() {
        let Ok(url) = env::var("SADDLE_TEST_DATABASE_URL") else {
            eprintln!("skipping production query_optional: SADDLE_TEST_DATABASE_URL is not set");
            return;
        };
        run_production_mode(
            &url,
            QueryOptionalOperationProof::<ProductionSuccess>::bind()
                .unwrap()
                .invocation(ManagedQueryParameters(DbU64(7))),
            FixedSignal::pending(),
            FixedSignal::pending(),
            None,
            true,
        )
        .await;
        run_production_mode(
            &url,
            QueryOptionalOperationProof::<ProductionNone>::bind()
                .unwrap()
                .invocation(ManagedQueryParameters(DbU64(7))),
            FixedSignal::pending(),
            FixedSignal::pending(),
            None,
            false,
        )
        .await;
        run_production_mode(
            &url,
            QueryOptionalOperationProof::<ProductionError>::bind()
                .unwrap()
                .invocation(ManagedQueryParameters(DbU64(7))),
            FixedSignal::pending(),
            FixedSignal::pending(),
            Some("db.query_failed"),
            false,
        )
        .await;
        run_production_mode(
            &url,
            QueryOptionalOperationProof::<ProductionPanic>::bind()
                .unwrap()
                .invocation(ManagedQueryParameters(DbU64(7))),
            FixedSignal::pending(),
            FixedSignal::pending(),
            Some("db.query_failed"),
            false,
        )
        .await;
        run_production_mode(
            &url,
            QueryOptionalOperationProof::<ProductionSlow>::bind()
                .unwrap()
                .invocation(ManagedQueryParameters(DbU64(7))),
            FixedSignal::after_pending_poll(),
            FixedSignal::pending(),
            Some("db.query_cancelled"),
            false,
        )
        .await;
        run_production_mode(
            &url,
            QueryOptionalOperationProof::<ProductionSlow>::bind()
                .unwrap()
                .invocation(ManagedQueryParameters(DbU64(7))),
            FixedSignal::pending(),
            FixedSignal::after_pending_poll(),
            Some("db.query_shutdown"),
            false,
        )
        .await;
    }

    #[tokio::test]
    async fn real_mariadb_cancel_discards_lock_wait_unresponsive_and_disconnected_sockets() {
        let Ok(url) = env::var("SADDLE_TEST_DATABASE_URL") else {
            eprintln!("skipping bounded DB finalization: SADDLE_TEST_DATABASE_URL is not set");
            return;
        };
        let server_pid = env::var("SADDLE_TEST_DATABASE_SERVER_PID")
            .expect("bounded finalization fixture requires the MariaDB PID")
            .parse::<u32>()
            .unwrap();

        let mut blocker = MySqlConnection::connect(&url).await.unwrap();
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS saddle_c6_lock_wait \
             (id BIGINT UNSIGNED PRIMARY KEY, value BIGINT UNSIGNED NOT NULL)",
        )
        .execute(&mut blocker)
        .await
        .unwrap();
        sqlx::query(
            "INSERT INTO saddle_c6_lock_wait VALUES (7, 1) \
             ON DUPLICATE KEY UPDATE value = VALUES(value)",
        )
        .execute(&mut blocker)
        .await
        .unwrap();
        sqlx::query("BEGIN").execute(&mut blocker).await.unwrap();
        sqlx::query("UPDATE saddle_c6_lock_wait SET value = value + 1 WHERE id = 7")
            .execute(&mut blocker)
            .await
            .unwrap();
        run_production_mode(
            &url,
            QueryOptionalOperationProof::<ProductionLockWait>::bind()
                .unwrap()
                .invocation(ManagedQueryParameters(DbU64(7))),
            FixedSignal::after_pending_poll(),
            FixedSignal::pending(),
            Some("db.query_cancelled"),
            false,
        )
        .await;
        sqlx::query("ROLLBACK").execute(&mut blocker).await.unwrap();

        sqlx::query("BEGIN").execute(&mut blocker).await.unwrap();
        sqlx::query("UPDATE saddle_c6_lock_wait SET value = value + 1 WHERE id = 7")
            .execute(&mut blocker)
            .await
            .unwrap();
        run_production_mode(
            &url,
            QueryOptionalOperationProof::<ProductionLockWait>::bind()
                .unwrap()
                .invocation(ManagedQueryParameters(DbU64(7))),
            FixedSignal::pending(),
            FixedSignal::after_pending_poll(),
            Some("db.query_shutdown"),
            false,
        )
        .await;
        sqlx::query("ROLLBACK").execute(&mut blocker).await.unwrap();
        blocker.close().await.unwrap();

        run_production_mode_with_server(
            &url,
            QueryOptionalOperationProof::<ProductionSlow>::bind()
                .unwrap()
                .invocation(ManagedQueryParameters(DbU64(7))),
            FixedSignal::after_pending_poll(),
            FixedSignal::pending(),
            Some("db.query_cancelled"),
            false,
            TestServerAction::Stop(server_pid),
        )
        .await;

        run_production_mode_with_server(
            &url,
            QueryOptionalOperationProof::<ProductionSlow>::bind()
                .unwrap()
                .invocation(ManagedQueryParameters(DbU64(7))),
            FixedSignal::after_pending_poll(),
            FixedSignal::pending(),
            Some("db.cancel_or_disconnect"),
            false,
            TestServerAction::Terminate(server_pid),
        )
        .await;
    }
}