fsqlite 0.2.0

Public API facade
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
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
#![cfg(all(feature = "async-api", not(target_arch = "wasm32")))]
// The raw Connection is intentionally !Send, and keeping its composed future
// on the requested 1 MiB thread is the contract this gate measures.
#![allow(clippy::future_not_send, clippy::large_futures)]

//! Physical-stack release gate for the shared trigger/FK and expression-depth
//! limits. Each release scenario runs in its own process because a native stack
//! overflow aborts the process rather than unwinding through the test harness.
//!
//! The raw-engine scenarios additionally run on an explicitly requested 1 MiB
//! stack. The actor scenario exercises the real dedicated worker owned by
//! `AsyncConnection`.
//!
//! This file also retains the bd-wymdl defect-4a diagnostic for manually
//! probing worker trigger depth.
//!
//! A stack overflow aborts the process, so the sweep drives this test
//! out-of-process, one depth per run:
//!
//! ```text
//! FSQLITE_PROBE_DEPTH=200 cargo test -p fsqlite --features async-api \
//!     --test trigger_depth_worker_probe -- --ignored --nocapture
//! ```

use asupersync::runtime::RuntimeBuilder;
use fsqlite::{AsyncConnection, Connection, FrankenError, Row, SqliteValue};
use fsqlite_core::connection::{
    hot_path_profile_snapshot, reset_hot_path_profile, set_hot_path_profile_enabled,
};
use fsqlite_types::cx::Cx;
use fsqlite_types::limits::{MAX_EXPR_DEPTH, MAX_TRIGGER_DEPTH};
use std::fmt::Write as _;
use std::io::Read as _;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

const STACK_GATE_SCENARIO_ENV: &str = "FSQLITE_STACK_GATE_SCENARIO";
const STACK_GATE_CHILD_ENV: &str = "FSQLITE_STACK_GATE_CHILD";
const RAW_STACK_BYTES: usize = 1024 * 1024;
const SCENARIO_DEADLINE: Duration = Duration::from_secs(180);
const GATE_DEADLINE: Duration = Duration::from_secs(600);
const CHILD_REAP_DEADLINE: Duration = Duration::from_secs(5);
const STACK_GATE_SCENARIOS: [&str; 7] = [
    "raw_fk",
    "raw_trigger",
    "raw_trigger_fk",
    "raw_fk_trigger_fk",
    "raw_expr_vdbe",
    "raw_expr_subquery",
    "actor",
];

fn trigger_depth_limit() -> usize {
    usize::try_from(MAX_TRIGGER_DEPTH).expect("MAX_TRIGGER_DEPTH must fit usize")
}

fn expression_depth_limit() -> usize {
    usize::try_from(MAX_EXPR_DEPTH).expect("MAX_EXPR_DEPTH must fit usize")
}

fn run_stack_gate_child(scenario: &str, deadline: Duration) {
    let executable = std::env::current_exe().expect("resolve current test executable");
    let mut child = Command::new(executable)
        .args([
            "--exact",
            "physical_stack_release_gate",
            "--nocapture",
            "--test-threads=1",
        ])
        .env(STACK_GATE_CHILD_ENV, "1")
        .env(STACK_GATE_SCENARIO_ENV, scenario)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap_or_else(|error| panic!("spawn stack-gate scenario {scenario}: {error}"));

    let mut stdout = child.stdout.take().expect("child stdout pipe");
    let mut stderr = child.stderr.take().expect("child stderr pipe");
    let stdout_reader = std::thread::spawn(move || {
        let mut bytes = Vec::new();
        stdout
            .read_to_end(&mut bytes)
            .expect("read stack-gate child stdout");
        bytes
    });
    let stderr_reader = std::thread::spawn(move || {
        let mut bytes = Vec::new();
        stderr
            .read_to_end(&mut bytes)
            .expect("read stack-gate child stderr");
        bytes
    });

    let started = Instant::now();
    let (status, timed_out) = 'wait_for_child: loop {
        if let Some(status) = child
            .try_wait()
            .unwrap_or_else(|error| panic!("poll stack-gate scenario {scenario}: {error}"))
        {
            break (status, false);
        }
        if started.elapsed() >= deadline {
            child
                .kill()
                .unwrap_or_else(|error| panic!("terminate timed-out scenario {scenario}: {error}"));
            let reap_started = Instant::now();
            loop {
                if let Some(status) = child
                    .try_wait()
                    .unwrap_or_else(|error| panic!("reap timed-out scenario {scenario}: {error}"))
                {
                    break 'wait_for_child (status, true);
                }
                assert!(
                    reap_started.elapsed() < CHILD_REAP_DEADLINE,
                    "terminated stack-gate scenario {scenario} was not reaped within {}s",
                    CHILD_REAP_DEADLINE.as_secs()
                );
                std::thread::sleep(Duration::from_millis(10));
            }
        }
        std::thread::sleep(Duration::from_millis(10));
    };

    let stdout = stdout_reader
        .join()
        .expect("stack-gate stdout reader must not panic");
    let stderr = stderr_reader
        .join()
        .expect("stack-gate stderr reader must not panic");
    let stdout = String::from_utf8_lossy(&stdout);
    let stderr = String::from_utf8_lossy(&stderr);

    assert!(
        !timed_out,
        "stack-gate scenario {scenario} exceeded {}s\nstdout:\n{stdout}\nstderr:\n{stderr}",
        deadline.as_secs()
    );
    assert!(
        status.success(),
        "stack-gate scenario {scenario} failed with {status}\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    let marker = format!("STACK_GATE_OK scenario={scenario}");
    assert!(
        stdout.lines().any(|line| line.contains(&marker)),
        "stack-gate scenario {scenario} exited successfully without `{marker}`\n\
         stdout:\n{stdout}\nstderr:\n{stderr}"
    );
}

#[test]
fn physical_stack_release_gate() {
    if std::env::var(STACK_GATE_CHILD_ENV).as_deref() == Ok("1")
        && let Ok(scenario) = std::env::var(STACK_GATE_SCENARIO_ENV)
    {
        run_stack_gate_scenario(&scenario);
        println!("STACK_GATE_OK scenario={scenario}");
        return;
    }

    let gate_started = Instant::now();
    for scenario in STACK_GATE_SCENARIOS {
        let remaining = GATE_DEADLINE.checked_sub(gate_started.elapsed()).unwrap_or_else(|| {
            panic!(
                "physical stack release gate exceeded its aggregate {}s deadline before scenario {scenario}",
                GATE_DEADLINE.as_secs()
            )
        });
        run_stack_gate_child(scenario, remaining.min(SCENARIO_DEADLINE));
    }
}

fn run_stack_gate_scenario(scenario: &str) {
    match scenario {
        "raw_fk" => run_on_raw_stack(raw_fk_worker),
        "raw_trigger" => run_on_raw_stack(raw_trigger_worker),
        "raw_trigger_fk" => run_on_raw_stack(raw_trigger_fk_worker),
        "raw_fk_trigger_fk" => run_on_raw_stack(raw_fk_trigger_fk_worker),
        "raw_expr_vdbe" => run_on_raw_stack(raw_expr_vdbe_worker),
        "raw_expr_subquery" => run_on_raw_stack(raw_expr_subquery_worker),
        "actor" => run_actor_scenario(),
        other => panic!("unknown stack-gate scenario `{other}`"),
    }
}

fn run_on_raw_stack(task: fn()) {
    let worker = std::thread::Builder::new()
        .stack_size(RAW_STACK_BYTES)
        .spawn(task)
        .expect("spawn requested 1 MiB raw-engine stack");
    if let Err(payload) = worker.join() {
        std::panic::resume_unwind(payload);
    }
}

fn raw_runtime() -> asupersync::runtime::Runtime {
    RuntimeBuilder::current_thread()
        .blocking_threads(1, 1)
        .build()
        .expect("raw stack-gate runtime should build")
}

fn raw_fk_worker() {
    raw_runtime().block_on(run_raw_fk());
}

fn raw_trigger_worker() {
    raw_runtime().block_on(run_raw_trigger());
}

fn raw_trigger_fk_worker() {
    raw_runtime().block_on(run_raw_trigger_fk());
}

fn raw_fk_trigger_fk_worker() {
    raw_runtime().block_on(run_raw_fk_trigger_fk());
}

fn raw_expr_vdbe_worker() {
    raw_runtime().block_on(run_raw_expr_vdbe());
}

fn raw_expr_subquery_worker() {
    raw_runtime().block_on(run_raw_expr_subquery());
}

fn chain_insert_sql(table: &str, max_id: usize) -> String {
    let mut sql = format!("INSERT INTO {table}(id, parent_id) VALUES (0, NULL)");
    for id in 1..=max_id {
        write!(&mut sql, ", ({id}, {})", id - 1).expect("write chain fixture SQL");
    }
    sql.push(';');
    sql
}

fn parameter_sum_sql(height: usize) -> String {
    assert!(height > 0, "parameter expression height must be non-zero");
    let mut sql = String::from("SELECT ");
    for index in 1..=height {
        if index > 1 {
            sql.push_str(" + ");
        }
        write!(&mut sql, "?{index}").expect("write numbered parameter expression");
    }
    sql.push(';');
    sql
}

fn fallback_expression_sql(height: usize) -> String {
    assert!(height > 0, "fallback expression height must be non-zero");
    let expression = format!(
        "{}1{}",
        "(SELECT ".repeat(height - 1),
        ")".repeat(height - 1)
    );
    format!(
        "SELECT {expression} AS value \
         FROM (SELECT 1 AS marker UNION ALL SELECT 2 AS marker) AS derived \
         WHERE marker = 1;"
    )
}

fn integer_at(row: &Row, column: usize, context: &str) -> i64 {
    match row.values().get(column) {
        Some(SqliteValue::Integer(value)) => *value,
        other => panic!("{context}: expected integer at column {column}, got {other:?}"),
    }
}

fn only_integer(rows: &[Row], column: usize, context: &str) -> i64 {
    assert_eq!(rows.len(), 1, "{context}: expected exactly one row");
    integer_at(&rows[0], column, context)
}

fn change_state(rows: &[Row], context: &str) -> (i64, i64) {
    assert_eq!(rows.len(), 1, "{context}: expected one change-state row");
    (
        integer_at(&rows[0], 0, context),
        integer_at(&rows[0], 1, context),
    )
}

fn txn_rollback_stats(rows: &[Row], context: &str) -> (i64, i64) {
    let metric = |wanted: &str| {
        rows.iter()
            .find_map(|row| match row.values() {
                [SqliteValue::Text(name), SqliteValue::Integer(value)]
                    if name.as_ref() == wanted =>
                {
                    Some(*value)
                }
                _ => None,
            })
            .unwrap_or_else(|| panic!("{context}: missing transaction metric `{wanted}`"))
    };
    (
        metric("rollback_count_active"),
        metric("rollback_count_total"),
    )
}

fn assert_exact_chain(rows: &[Row], max_id: usize, context: &str) {
    assert_eq!(
        rows.len(),
        max_id + 1,
        "{context}: unexpected chain cardinality"
    );
    for (id, row) in rows.iter().enumerate() {
        let expected_id = i64::try_from(id).expect("chain id must fit i64");
        assert_eq!(
            row.values().first(),
            Some(&SqliteValue::Integer(expected_id)),
            "{context}: wrong id at chain position {id}"
        );
        if id == 0 {
            assert_eq!(
                row.values().get(1),
                Some(&SqliteValue::Null),
                "{context}: root parent must be NULL"
            );
        } else {
            assert_eq!(
                row.values().get(1),
                Some(&SqliteValue::Integer(expected_id - 1)),
                "{context}: wrong parent at chain position {id}"
            );
        }
    }
}

fn assert_rows(rows: &[Row], expected: &[Vec<SqliteValue>], context: &str) {
    let actual = rows
        .iter()
        .map(|row| row.values().to_vec())
        .collect::<Vec<_>>();
    assert_eq!(actual.as_slice(), expected, "{context}: exact rows differ");
}

async fn raw_change_state(conn: &Connection, context: &str) -> (i64, i64) {
    let rows = conn
        .query("SELECT changes(), total_changes();")
        .await
        .unwrap_or_else(|error| panic!("{context}: query change state: {error}"));
    change_state(&rows, context)
}

async fn raw_txn_rollback_stats(conn: &Connection, context: &str) -> (i64, i64) {
    let rows = conn
        .query("PRAGMA fsqlite.txn_stats;")
        .await
        .unwrap_or_else(|error| panic!("{context}: query transaction stats: {error}"));
    txn_rollback_stats(&rows, context)
}

async fn assert_raw_failure_envelope(
    conn: &Connection,
    before_changes: (i64, i64),
    before_rollbacks: (i64, i64),
    context: &str,
) {
    assert!(
        conn.in_transaction(),
        "{context}: failed statement closed caller transaction"
    );
    let after_changes = raw_change_state(conn, context).await;
    assert_eq!(
        after_changes.0, 0,
        "{context}: failed statement must publish changes() = 0"
    );
    assert_eq!(
        after_changes.1, before_changes.1,
        "{context}: rolled-back work changed total_changes()"
    );
    let after_rollbacks = raw_txn_rollback_stats(conn, context).await;
    assert_eq!(
        after_rollbacks.0,
        before_rollbacks.0 + 1,
        "{context}: statement rollback counter did not advance exactly once"
    );
    assert_eq!(
        after_rollbacks.1,
        before_rollbacks.1 + 1,
        "{context}: total rollback counter did not advance exactly once"
    );
}

async fn assert_raw_markers(conn: &Connection, context: &str) {
    let rows = conn
        .query("SELECT marker FROM gate_marker ORDER BY rowid;")
        .await
        .unwrap_or_else(|error| panic!("{context}: query reuse markers: {error}"));
    assert_rows(
        &rows,
        &[
            vec![SqliteValue::Text("before-failure".into())],
            vec![SqliteValue::Text("after-failure".into())],
        ],
        context,
    );
}

async fn run_raw_fk() {
    let depth = trigger_depth_limit();
    let conn = Connection::open(":memory:")
        .await
        .expect("raw FK connection should open");
    conn.execute_batch(
        "PRAGMA foreign_keys = ON;
         CREATE TABLE fk_ok (
             id INTEGER PRIMARY KEY,
             parent_id INTEGER REFERENCES fk_ok(id) ON DELETE CASCADE
         );
         CREATE TABLE fk_bad (
             id INTEGER PRIMARY KEY,
             parent_id INTEGER REFERENCES fk_bad(id) ON DELETE CASCADE
         );
         CREATE TABLE gate_marker (marker TEXT NOT NULL);",
    )
    .await
    .expect("create raw FK depth fixture");
    conn.execute(&chain_insert_sql("fk_ok", depth + 1))
        .await
        .expect("seed exact-depth FK chain");
    conn.execute(&chain_insert_sql("fk_bad", depth + 1))
        .await
        .expect("seed over-depth FK chain");

    conn.execute("BEGIN;").await.expect("begin raw FK gate");
    assert!(
        conn.in_transaction(),
        "raw FK BEGIN state was not published"
    );
    let before_success = raw_change_state(&conn, "raw FK before success").await;
    assert_eq!(
        conn.execute("DELETE FROM fk_ok WHERE id = 1;")
            .await
            .expect("D nested FK programs must succeed"),
        1
    );
    let after_success = raw_change_state(&conn, "raw FK exact success").await;
    assert_eq!(after_success.0, 1, "raw FK top-level changes() mismatch");
    assert_eq!(
        after_success.1 - before_success.1,
        i64::try_from(depth + 1).expect("FK success delta fits i64"),
        "raw FK total_changes() must include every cascaded row"
    );
    let rows = conn
        .query("SELECT id, parent_id FROM fk_ok ORDER BY id;")
        .await
        .expect("query exact-depth FK survivors");
    assert_exact_chain(&rows, 0, "raw FK exact-depth survivors");

    conn.execute("SAVEPOINT caller;")
        .await
        .expect("create raw FK caller savepoint");
    conn.execute("INSERT INTO gate_marker VALUES ('before-failure');")
        .await
        .expect("seed raw FK reuse marker");
    let before_failure = raw_change_state(&conn, "raw FK before failure").await;
    let before_rollbacks = raw_txn_rollback_stats(&conn, "raw FK before failure").await;
    let error = conn
        .execute("DELETE FROM fk_bad WHERE id = 0;")
        .await
        .expect_err("D+1 nested FK programs must be rejected");
    assert!(
        matches!(&error, FrankenError::TriggerRecursionDepthExceeded),
        "raw FK returned wrong over-depth error: {error:?}"
    );
    assert_raw_failure_envelope(&conn, before_failure, before_rollbacks, "raw FK over-depth").await;
    let rows = conn
        .query("SELECT id, parent_id FROM fk_bad ORDER BY id;")
        .await
        .expect("query rolled-back FK chain");
    assert_exact_chain(&rows, depth + 1, "raw FK rejected-statement rows");
    conn.execute("RELEASE SAVEPOINT caller;")
        .await
        .expect("failed raw FK statement must preserve caller savepoint");
    conn.execute("INSERT INTO gate_marker VALUES ('after-failure');")
        .await
        .expect("raw FK connection must be reusable after rejection");
    assert_raw_markers(&conn, "raw FK markers").await;
    conn.execute("COMMIT;").await.expect("commit raw FK gate");
    assert!(!conn.in_transaction(), "raw FK COMMIT state stayed active");
    conn.close().await.expect("close raw FK connection");
}

fn pure_trigger_schema_sql(depth: usize) -> String {
    let rejected_depth = depth
        .checked_add(1)
        .expect("trigger depth fixture must fit usize");
    format!(
        "PRAGMA recursive_triggers = ON;
         CREATE TABLE pure_ok (n INTEGER NOT NULL);
         CREATE TABLE pure_bad (n INTEGER NOT NULL);
         CREATE TABLE pure_audit (lane TEXT NOT NULL, n INTEGER NOT NULL);
         CREATE TABLE gate_marker (marker TEXT NOT NULL);
         INSERT INTO pure_ok VALUES (0);
         INSERT INTO pure_bad VALUES (0);
         CREATE TRIGGER pure_ok_au AFTER UPDATE ON pure_ok
         WHEN NEW.n < {depth}
         BEGIN
             INSERT INTO pure_audit VALUES ('ok', NEW.n);
             UPDATE pure_ok SET n = NEW.n + 1;
         END;
         CREATE TRIGGER pure_bad_au AFTER UPDATE ON pure_bad
         WHEN NEW.n < {rejected_depth}
         BEGIN
             INSERT INTO pure_audit VALUES ('bad', NEW.n);
             UPDATE pure_bad SET n = NEW.n + 1;
         END;"
    )
}

async fn run_raw_trigger() {
    let depth = trigger_depth_limit();
    let conn = Connection::open(":memory:")
        .await
        .expect("raw pure-trigger connection should open");
    conn.execute_batch(&pure_trigger_schema_sql(depth))
        .await
        .expect("create raw pure-trigger fixture");

    conn.execute("BEGIN;")
        .await
        .expect("begin raw pure-trigger gate");
    let before_success = raw_change_state(&conn, "raw pure trigger before success").await;
    assert_eq!(
        conn.execute("UPDATE pure_ok SET n = 1;")
            .await
            .expect("D nested trigger programs must succeed"),
        1
    );
    let after_success = raw_change_state(&conn, "raw pure trigger exact success").await;
    assert_eq!(
        after_success.1 - before_success.1,
        i64::try_from(depth.saturating_mul(2).saturating_sub(1))
            .expect("pure-trigger success delta fits i64"),
        "raw pure-trigger total_changes() must include nested updates and audit rows"
    );
    let rows = conn
        .query("SELECT n FROM pure_ok;")
        .await
        .expect("query pure-trigger final value");
    assert_eq!(
        only_integer(&rows, 0, "raw pure-trigger final value"),
        i64::try_from(depth).expect("trigger depth fits i64")
    );
    let rows = conn
        .query("SELECT COUNT(*) FROM pure_audit WHERE lane = 'ok';")
        .await
        .expect("query exact pure-trigger audit count");
    assert_eq!(
        only_integer(&rows, 0, "raw pure-trigger audit count"),
        i64::try_from(depth.saturating_sub(1)).expect("trigger audit count fits i64")
    );

    conn.execute("SAVEPOINT caller;")
        .await
        .expect("create raw pure-trigger caller savepoint");
    conn.execute("INSERT INTO gate_marker VALUES ('before-failure');")
        .await
        .expect("seed raw pure-trigger reuse marker");
    let before_failure = raw_change_state(&conn, "raw pure trigger before failure").await;
    let before_rollbacks = raw_txn_rollback_stats(&conn, "raw pure trigger before failure").await;
    let error = conn
        .execute("UPDATE pure_bad SET n = 1;")
        .await
        .expect_err("D+1 nested trigger programs must be rejected");
    assert!(
        matches!(&error, FrankenError::TriggerRecursionDepthExceeded),
        "raw pure trigger returned wrong over-depth error: {error:?}"
    );
    assert_raw_failure_envelope(
        &conn,
        before_failure,
        before_rollbacks,
        "raw pure trigger over-depth",
    )
    .await;
    let rows = conn
        .query("SELECT n FROM pure_bad;")
        .await
        .expect("query rolled-back pure-trigger row");
    assert_eq!(only_integer(&rows, 0, "raw pure-trigger rejected row"), 0);
    let rows = conn
        .query("SELECT COUNT(*) FROM pure_audit WHERE lane = 'bad';")
        .await
        .expect("query rolled-back pure-trigger audit count");
    assert_eq!(
        only_integer(&rows, 0, "raw pure-trigger rejected audit count"),
        0
    );
    conn.execute("RELEASE SAVEPOINT caller;")
        .await
        .expect("failed pure-trigger statement must preserve caller savepoint");
    conn.execute("INSERT INTO gate_marker VALUES ('after-failure');")
        .await
        .expect("raw pure-trigger connection must be reusable after rejection");
    assert_raw_markers(&conn, "raw pure-trigger markers").await;
    conn.execute("COMMIT;")
        .await
        .expect("commit raw pure-trigger gate");
    assert!(
        !conn.in_transaction(),
        "raw pure-trigger COMMIT state stayed active"
    );
    conn.close()
        .await
        .expect("close raw pure-trigger connection");
}

async fn run_raw_trigger_fk() {
    let depth = trigger_depth_limit();
    let conn = Connection::open(":memory:")
        .await
        .expect("raw trigger-FK connection should open");
    conn.execute_batch(
        "PRAGMA foreign_keys = ON;
         PRAGMA recursive_triggers = ON;
         CREATE TABLE tf_chain_ok (
             id INTEGER PRIMARY KEY,
             parent_id INTEGER REFERENCES tf_chain_ok(id) ON DELETE CASCADE
         );
         CREATE TABLE tf_chain_bad (
             id INTEGER PRIMARY KEY,
             parent_id INTEGER REFERENCES tf_chain_bad(id) ON DELETE CASCADE
         );
         CREATE TABLE tf_driver_ok (id INTEGER PRIMARY KEY, start_id INTEGER NOT NULL);
         CREATE TABLE tf_driver_bad (id INTEGER PRIMARY KEY, start_id INTEGER NOT NULL);
         CREATE TABLE tf_audit (lane TEXT NOT NULL, start_id INTEGER NOT NULL);
         CREATE TABLE gate_marker (marker TEXT NOT NULL);
         CREATE TRIGGER tf_driver_ok_ad AFTER DELETE ON tf_driver_ok BEGIN
             INSERT INTO tf_audit VALUES ('ok', OLD.start_id);
             DELETE FROM tf_chain_ok WHERE id = OLD.start_id;
         END;
         CREATE TRIGGER tf_driver_bad_ad AFTER DELETE ON tf_driver_bad BEGIN
             INSERT INTO tf_audit VALUES ('bad', OLD.start_id);
             DELETE FROM tf_chain_bad WHERE id = OLD.start_id;
         END;",
    )
    .await
    .expect("create raw trigger-FK fixture");
    conn.execute(&chain_insert_sql("tf_chain_ok", depth))
        .await
        .expect("seed exact trigger-FK chain");
    conn.execute(&chain_insert_sql("tf_chain_bad", depth))
        .await
        .expect("seed over-depth trigger-FK chain");
    conn.execute("INSERT INTO tf_driver_ok VALUES (1, 1);")
        .await
        .expect("seed exact trigger driver");
    conn.execute("INSERT INTO tf_driver_bad VALUES (1, 0);")
        .await
        .expect("seed over-depth trigger driver");

    conn.execute("BEGIN;")
        .await
        .expect("begin raw trigger-FK gate");
    assert!(
        conn.in_transaction(),
        "raw trigger-FK BEGIN state was not published"
    );
    let before_success = raw_change_state(&conn, "raw trigger-FK before success").await;
    assert_eq!(
        conn.execute("DELETE FROM tf_driver_ok WHERE id = 1;")
            .await
            .expect("one trigger plus D-1 FK programs must succeed"),
        1
    );
    let after_success = raw_change_state(&conn, "raw trigger-FK exact success").await;
    assert_eq!(
        after_success.0, 1,
        "raw trigger-FK top-level changes() mismatch"
    );
    assert_eq!(
        after_success.1 - before_success.1,
        i64::try_from(depth + 2).expect("trigger-FK success delta fits i64"),
        "raw trigger-FK total_changes() must include trigger and cascade writes"
    );
    let rows = conn
        .query("SELECT id, parent_id FROM tf_chain_ok ORDER BY id;")
        .await
        .expect("query exact trigger-FK survivors");
    assert_exact_chain(&rows, 0, "raw trigger-FK exact-depth survivors");

    conn.execute("SAVEPOINT caller;")
        .await
        .expect("create raw trigger-FK caller savepoint");
    conn.execute("INSERT INTO gate_marker VALUES ('before-failure');")
        .await
        .expect("seed raw trigger-FK reuse marker");
    let before_failure = raw_change_state(&conn, "raw trigger-FK before failure").await;
    let before_rollbacks = raw_txn_rollback_stats(&conn, "raw trigger-FK before failure").await;
    let error = conn
        .execute("DELETE FROM tf_driver_bad WHERE id = 1;")
        .await
        .expect_err("one trigger plus D FK programs must be rejected");
    assert!(
        matches!(&error, FrankenError::TriggerRecursionDepthExceeded),
        "raw trigger-FK returned wrong over-depth error: {error:?}"
    );
    assert_raw_failure_envelope(
        &conn,
        before_failure,
        before_rollbacks,
        "raw trigger-FK over-depth",
    )
    .await;
    let rows = conn
        .query("SELECT id, parent_id FROM tf_chain_bad ORDER BY id;")
        .await
        .expect("query rolled-back trigger-FK chain");
    assert_exact_chain(&rows, depth, "raw trigger-FK rejected-statement chain");
    let rows = conn
        .query("SELECT id, start_id FROM tf_driver_bad ORDER BY id;")
        .await
        .expect("query rolled-back trigger driver");
    assert_rows(
        &rows,
        &[vec![SqliteValue::Integer(1), SqliteValue::Integer(0)]],
        "raw trigger-FK rejected driver",
    );
    let rows = conn
        .query("SELECT lane, start_id FROM tf_audit ORDER BY rowid;")
        .await
        .expect("query trigger-FK audit");
    assert_rows(
        &rows,
        &[vec![
            SqliteValue::Text("ok".into()),
            SqliteValue::Integer(1),
        ]],
        "raw trigger-FK audit rollback",
    );
    conn.execute("RELEASE SAVEPOINT caller;")
        .await
        .expect("failed raw trigger-FK statement must preserve caller savepoint");
    conn.execute("INSERT INTO gate_marker VALUES ('after-failure');")
        .await
        .expect("raw trigger-FK connection must be reusable after rejection");
    assert_raw_markers(&conn, "raw trigger-FK markers").await;
    conn.execute("COMMIT;")
        .await
        .expect("commit raw trigger-FK gate");
    assert!(
        !conn.in_transaction(),
        "raw trigger-FK COMMIT state stayed active"
    );
    conn.close().await.expect("close raw trigger-FK connection");
}

const MIXED_SCHEMA: &str = "PRAGMA foreign_keys = ON;
     PRAGMA recursive_triggers = ON;
     CREATE TABLE mixed_root_ok (id INTEGER PRIMARY KEY);
     CREATE TABLE mixed_root_bad (id INTEGER PRIMARY KEY);
     CREATE TABLE mixed_bridge_ok (
         id INTEGER PRIMARY KEY,
         root_id INTEGER NOT NULL REFERENCES mixed_root_ok(id) ON DELETE CASCADE,
         tail_start INTEGER NOT NULL
     );
     CREATE TABLE mixed_bridge_bad (
         id INTEGER PRIMARY KEY,
         root_id INTEGER NOT NULL REFERENCES mixed_root_bad(id) ON DELETE CASCADE,
         tail_start INTEGER NOT NULL
     );
     CREATE TABLE mixed_tail_ok (
         id INTEGER PRIMARY KEY,
         parent_id INTEGER REFERENCES mixed_tail_ok(id) ON DELETE CASCADE
     );
     CREATE TABLE mixed_tail_bad (
         id INTEGER PRIMARY KEY,
         parent_id INTEGER REFERENCES mixed_tail_bad(id) ON DELETE CASCADE
     );
     CREATE TABLE mixed_audit (
         lane TEXT NOT NULL,
         bridge_id INTEGER NOT NULL,
         tail_start INTEGER NOT NULL
     );
     CREATE TABLE gate_marker (marker TEXT NOT NULL);
     CREATE TRIGGER mixed_bridge_ok_ad AFTER DELETE ON mixed_bridge_ok BEGIN
         INSERT INTO mixed_audit VALUES ('ok', OLD.id, OLD.tail_start);
         DELETE FROM mixed_tail_ok WHERE id = OLD.tail_start;
     END;
     CREATE TRIGGER mixed_bridge_bad_ad AFTER DELETE ON mixed_bridge_bad BEGIN
         INSERT INTO mixed_audit VALUES ('bad', OLD.id, OLD.tail_start);
         DELETE FROM mixed_tail_bad WHERE id = OLD.tail_start;
     END;";

async fn seed_raw_mixed(conn: &Connection, depth: usize) {
    conn.execute_batch(MIXED_SCHEMA)
        .await
        .expect("create raw mixed-depth fixture");
    conn.execute(&chain_insert_sql("mixed_tail_ok", depth - 1))
        .await
        .expect("seed exact mixed tail");
    conn.execute(&chain_insert_sql("mixed_tail_bad", depth - 1))
        .await
        .expect("seed over-depth mixed tail");
    conn.execute("INSERT INTO mixed_root_ok VALUES (1);")
        .await
        .expect("seed exact mixed root");
    conn.execute("INSERT INTO mixed_root_bad VALUES (1);")
        .await
        .expect("seed over-depth mixed root");
    conn.execute("INSERT INTO mixed_bridge_ok VALUES (10, 1, 1);")
        .await
        .expect("seed exact mixed bridge");
    conn.execute("INSERT INTO mixed_bridge_bad VALUES (20, 1, 0);")
        .await
        .expect("seed over-depth mixed bridge");
}

async fn run_raw_fk_trigger_fk() {
    let depth = trigger_depth_limit();
    assert!(
        depth >= 2,
        "mixed fixture requires trigger depth at least two"
    );
    let conn = Connection::open(":memory:")
        .await
        .expect("raw mixed connection should open");
    seed_raw_mixed(&conn, depth).await;

    conn.execute("BEGIN;").await.expect("begin raw mixed gate");
    assert!(
        conn.in_transaction(),
        "raw mixed BEGIN state was not published"
    );
    let before_success = raw_change_state(&conn, "raw mixed before success").await;
    assert_eq!(
        conn.execute("DELETE FROM mixed_root_ok WHERE id = 1;")
            .await
            .expect("one outer FK, one trigger, and D-2 tail FKs must succeed"),
        1
    );
    let after_success = raw_change_state(&conn, "raw mixed exact success").await;
    assert_eq!(after_success.0, 1, "raw mixed top-level changes() mismatch");
    assert_eq!(
        after_success.1 - before_success.1,
        i64::try_from(depth + 2).expect("mixed success delta fits i64"),
        "raw mixed total_changes() must include root, bridge, trigger, and tail writes"
    );
    let rows = conn
        .query("SELECT id, parent_id FROM mixed_tail_ok ORDER BY id;")
        .await
        .expect("query exact mixed survivors");
    assert_exact_chain(&rows, 0, "raw mixed exact-depth survivors");

    conn.execute("SAVEPOINT caller;")
        .await
        .expect("create raw mixed caller savepoint");
    conn.execute("INSERT INTO gate_marker VALUES ('before-failure');")
        .await
        .expect("seed raw mixed reuse marker");
    let before_failure = raw_change_state(&conn, "raw mixed before failure").await;
    let before_rollbacks = raw_txn_rollback_stats(&conn, "raw mixed before failure").await;
    let error = conn
        .execute("DELETE FROM mixed_root_bad WHERE id = 1;")
        .await
        .expect_err("one outer FK, one trigger, and D-1 tail FKs must be rejected");
    assert!(
        matches!(&error, FrankenError::TriggerRecursionDepthExceeded),
        "raw mixed returned wrong over-depth error: {error:?}"
    );
    assert_raw_failure_envelope(
        &conn,
        before_failure,
        before_rollbacks,
        "raw mixed over-depth",
    )
    .await;
    let rows = conn
        .query("SELECT id, parent_id FROM mixed_tail_bad ORDER BY id;")
        .await
        .expect("query rolled-back mixed tail");
    assert_exact_chain(&rows, depth - 1, "raw mixed rejected tail");
    let rows = conn
        .query("SELECT id FROM mixed_root_bad ORDER BY id;")
        .await
        .expect("query rolled-back mixed root");
    assert_rows(
        &rows,
        &[vec![SqliteValue::Integer(1)]],
        "raw mixed rejected root",
    );
    let rows = conn
        .query("SELECT id, root_id, tail_start FROM mixed_bridge_bad ORDER BY id;")
        .await
        .expect("query rolled-back mixed bridge");
    assert_rows(
        &rows,
        &[vec![
            SqliteValue::Integer(20),
            SqliteValue::Integer(1),
            SqliteValue::Integer(0),
        ]],
        "raw mixed rejected bridge",
    );
    let rows = conn
        .query("SELECT lane, bridge_id, tail_start FROM mixed_audit ORDER BY rowid;")
        .await
        .expect("query mixed audit");
    assert_rows(
        &rows,
        &[vec![
            SqliteValue::Text("ok".into()),
            SqliteValue::Integer(10),
            SqliteValue::Integer(1),
        ]],
        "raw mixed audit rollback",
    );
    conn.execute("RELEASE SAVEPOINT caller;")
        .await
        .expect("failed raw mixed statement must preserve caller savepoint");
    conn.execute("INSERT INTO gate_marker VALUES ('after-failure');")
        .await
        .expect("raw mixed connection must be reusable after rejection");
    assert_raw_markers(&conn, "raw mixed markers").await;
    conn.execute("COMMIT;")
        .await
        .expect("commit raw mixed gate");
    assert!(
        !conn.in_transaction(),
        "raw mixed COMMIT state stayed active"
    );
    conn.close().await.expect("close raw mixed connection");
}

struct VdbeProfileGuard;

impl VdbeProfileGuard {
    fn enable() -> Self {
        set_hot_path_profile_enabled(true);
        reset_hot_path_profile();
        Self
    }
}

impl Drop for VdbeProfileGuard {
    fn drop(&mut self) {
        set_hot_path_profile_enabled(false);
    }
}

fn assert_sum_result(rows: &[Row], expected: usize, context: &str) {
    assert_eq!(
        only_integer(rows, 0, context),
        i64::try_from(expected).expect("expression result fits i64"),
        "{context}: wrong parameter-sum result"
    );
}

async fn run_raw_expr_vdbe() {
    let depth = expression_depth_limit();
    let conn = Connection::open(":memory:")
        .await
        .expect("raw VDBE-expression connection should open");
    let exact_sql = parameter_sum_sql(depth);
    let over_sql = parameter_sum_sql(depth + 1);
    let exact_params = vec![SqliteValue::Integer(1); depth];
    let over_params = vec![SqliteValue::Integer(1); depth + 1];

    let profile = VdbeProfileGuard::enable();
    let rows = conn
        .query_with_params(&exact_sql, &exact_params)
        .await
        .expect("expression height E must execute through VDBE");
    assert_sum_result(&rows, depth, "raw VDBE expression exact depth");
    let evidence = hot_path_profile_snapshot().vdbe;
    assert!(
        evidence.opcodes_executed_total > 0,
        "raw VDBE expression recorded no executed opcodes"
    );
    assert!(
        evidence.statements_total > 0 && !evidence.opcode_execution_totals.is_empty(),
        "raw VDBE expression profiler lacks per-opcode statement evidence: {evidence:?}"
    );

    let error = conn
        .query_with_params(&over_sql, &over_params)
        .await
        .expect_err("expression height E+1 must fail closed");
    assert!(
        matches!(
            &error,
            FrankenError::ExpressionTooDeep { max } if *max == depth
        ),
        "raw VDBE expression returned wrong depth error: {error:?}"
    );
    assert!(
        !conn.in_transaction(),
        "raw VDBE expression error leaked transaction state"
    );
    let rows = conn
        .query_with_params(&exact_sql, &exact_params)
        .await
        .expect("raw VDBE expression marker must be reusable after rejection");
    assert_sum_result(&rows, depth, "raw VDBE expression reuse");
    drop(profile);
    conn.close()
        .await
        .expect("close raw VDBE-expression connection");
}

fn assert_fallback_result(rows: &[Row], context: &str) {
    assert_eq!(
        only_integer(rows, 0, context),
        1,
        "{context}: wrong nested scalar-subquery result"
    );
}

async fn run_raw_expr_subquery() {
    let depth = expression_depth_limit();
    let conn = Connection::open(":memory:")
        .await
        .expect("raw fallback-expression connection should open");
    let shallow_sql = fallback_expression_sql(2);
    let exact_sql = fallback_expression_sql(depth);
    let over_sql = fallback_expression_sql(depth + 1);

    conn.execute("PRAGMA fsqlite.parity_cert_strict = ON;")
        .await
        .expect("enable raw fallback strict parity");
    let strict_error = conn
        .query(&shallow_sql)
        .await
        .expect_err("strict parity must reject the derived-source fallback");
    let strict_error = strict_error.to_string();
    assert!(
        strict_error.contains("decision_reason=join_or_subquery_fallback"),
        "strict fallback rejection omitted its decision reason: {strict_error}"
    );
    assert!(
        !conn.in_transaction(),
        "raw strict fallback rejection leaked transaction state"
    );
    conn.execute("PRAGMA fsqlite.parity_cert_strict = OFF;")
        .await
        .expect("disable raw fallback strict parity");

    let rows = conn
        .query(&exact_sql)
        .await
        .expect("fallback expression height E must succeed");
    assert_fallback_result(&rows, "raw fallback expression exact depth");
    let error = conn
        .query(&over_sql)
        .await
        .expect_err("fallback expression height E+1 must fail closed");
    assert!(
        matches!(
            &error,
            FrankenError::ExpressionTooDeep { max } if *max == depth
        ),
        "raw fallback expression returned wrong depth error: {error:?}"
    );
    assert!(
        !conn.in_transaction(),
        "raw fallback expression error leaked transaction state"
    );
    let rows = conn
        .query(&exact_sql)
        .await
        .expect("raw fallback expression marker must be reusable after rejection");
    assert_fallback_result(&rows, "raw fallback expression reuse");
    conn.close()
        .await
        .expect("close raw fallback-expression connection");
}

fn actor_change_state(conn: &AsyncConnection, context: &str) -> (i64, i64) {
    let rows = conn
        .query_sync("SELECT changes(), total_changes();")
        .unwrap_or_else(|error| panic!("{context}: query actor change state: {error}"));
    change_state(&rows, context)
}

fn actor_txn_rollback_stats(conn: &AsyncConnection, context: &str) -> (i64, i64) {
    let rows = conn
        .query_sync("PRAGMA fsqlite.txn_stats;")
        .unwrap_or_else(|error| panic!("{context}: query actor transaction stats: {error}"));
    txn_rollback_stats(&rows, context)
}

fn assert_actor_markers(conn: &AsyncConnection, context: &str) {
    let rows = conn
        .query_sync("SELECT marker FROM gate_marker ORDER BY rowid;")
        .unwrap_or_else(|error| panic!("{context}: query actor reuse markers: {error}"));
    assert_rows(
        &rows,
        &[
            vec![SqliteValue::Text("before-failure".into())],
            vec![SqliteValue::Text("after-failure".into())],
        ],
        context,
    );
}

fn seed_actor_mixed(conn: &AsyncConnection, depth: usize) {
    conn.execute_batch_sync(MIXED_SCHEMA)
        .expect("create actor mixed-depth fixture");
    conn.execute_sync(&chain_insert_sql("mixed_tail_ok", depth - 1))
        .expect("seed actor exact mixed tail");
    conn.execute_sync(&chain_insert_sql("mixed_tail_bad", depth - 1))
        .expect("seed actor over-depth mixed tail");
    conn.execute_sync("INSERT INTO mixed_root_ok VALUES (1);")
        .expect("seed actor exact mixed root");
    conn.execute_sync("INSERT INTO mixed_root_bad VALUES (1);")
        .expect("seed actor over-depth mixed root");
    conn.execute_sync("INSERT INTO mixed_bridge_ok VALUES (10, 1, 1);")
        .expect("seed actor exact mixed bridge");
    conn.execute_sync("INSERT INTO mixed_bridge_bad VALUES (20, 1, 0);")
        .expect("seed actor over-depth mixed bridge");
}

fn run_actor_mixed(conn: &AsyncConnection) {
    let depth = trigger_depth_limit();
    assert!(
        depth >= 2,
        "actor mixed fixture requires depth at least two"
    );
    seed_actor_mixed(conn, depth);
    assert!(
        !conn.in_transaction(),
        "actor setup unexpectedly published a transaction"
    );

    conn.begin_transaction_sync()
        .expect("begin actor mixed gate");
    assert!(
        conn.in_transaction(),
        "actor BEGIN state was not immediately published"
    );
    let before_success = actor_change_state(conn, "actor mixed before success");
    assert_eq!(
        conn.execute_sync("DELETE FROM mixed_root_ok WHERE id = 1;")
            .expect("actor exact aggregate depth must succeed"),
        1
    );
    assert!(
        conn.in_transaction(),
        "actor successful statement lost published transaction state"
    );
    let after_success = actor_change_state(conn, "actor mixed exact success");
    assert_eq!(after_success.0, 1, "actor mixed top-level changes mismatch");
    assert_eq!(
        after_success.1 - before_success.1,
        i64::try_from(depth + 2).expect("actor mixed delta fits i64"),
        "actor mixed total_changes mismatch"
    );

    conn.execute_sync("SAVEPOINT caller;")
        .expect("create actor caller savepoint");
    conn.execute_sync("INSERT INTO gate_marker VALUES ('before-failure');")
        .expect("seed actor reuse marker");
    let before_failure = actor_change_state(conn, "actor mixed before failure");
    let before_rollbacks = actor_txn_rollback_stats(conn, "actor mixed before failure");
    let error = conn
        .execute_sync("DELETE FROM mixed_root_bad WHERE id = 1;")
        .expect_err("actor aggregate depth D+1 must be rejected");
    assert!(
        matches!(&error, FrankenError::TriggerRecursionDepthExceeded),
        "actor mixed returned wrong over-depth error: {error:?}"
    );
    assert!(
        conn.in_transaction(),
        "actor failure state was not immediately published as in-transaction"
    );
    let after_failure = actor_change_state(conn, "actor mixed over-depth");
    assert_eq!(
        after_failure.0, 0,
        "actor failed statement changes mismatch"
    );
    assert_eq!(
        after_failure.1, before_failure.1,
        "actor rolled-back work changed total_changes"
    );
    let after_rollbacks = actor_txn_rollback_stats(conn, "actor mixed over-depth");
    assert_eq!(
        after_rollbacks,
        (before_rollbacks.0 + 1, before_rollbacks.1 + 1),
        "actor statement rollback counters must advance exactly once"
    );
    let rows = conn
        .query_sync("SELECT id, parent_id FROM mixed_tail_bad ORDER BY id;")
        .expect("query actor rolled-back tail");
    assert_exact_chain(&rows, depth - 1, "actor mixed rejected tail");
    let rows = conn
        .query_sync("SELECT id FROM mixed_root_bad ORDER BY id;")
        .expect("query actor rolled-back root");
    assert_rows(
        &rows,
        &[vec![SqliteValue::Integer(1)]],
        "actor mixed rejected root",
    );
    let rows = conn
        .query_sync("SELECT id, root_id, tail_start FROM mixed_bridge_bad ORDER BY id;")
        .expect("query actor rolled-back bridge");
    assert_rows(
        &rows,
        &[vec![
            SqliteValue::Integer(20),
            SqliteValue::Integer(1),
            SqliteValue::Integer(0),
        ]],
        "actor mixed rejected bridge",
    );
    let rows = conn
        .query_sync("SELECT lane, bridge_id, tail_start FROM mixed_audit ORDER BY rowid;")
        .expect("query actor mixed audit");
    assert_rows(
        &rows,
        &[vec![
            SqliteValue::Text("ok".into()),
            SqliteValue::Integer(10),
            SqliteValue::Integer(1),
        ]],
        "actor mixed audit rollback",
    );
    conn.execute_sync("RELEASE SAVEPOINT caller;")
        .expect("actor failure must preserve caller savepoint");
    conn.execute_sync("INSERT INTO gate_marker VALUES ('after-failure');")
        .expect("actor connection must be reusable after depth rejection");
    assert_actor_markers(conn, "actor mixed markers");
    conn.commit_transaction_sync()
        .expect("commit actor mixed gate");
    assert!(
        !conn.in_transaction(),
        "actor COMMIT state was not immediately published"
    );
}

fn run_actor_expr_vdbe(conn: &AsyncConnection) {
    let depth = expression_depth_limit();
    let exact_sql = parameter_sum_sql(depth);
    let over_sql = parameter_sum_sql(depth + 1);
    let exact_params = vec![SqliteValue::Integer(1); depth];
    let over_params = vec![SqliteValue::Integer(1); depth + 1];
    let profile = VdbeProfileGuard::enable();

    let rows = conn
        .query_with_params_sync(&exact_sql, &exact_params)
        .expect("actor expression height E must execute through VDBE");
    assert_sum_result(&rows, depth, "actor VDBE expression exact depth");
    assert!(
        !conn.in_transaction(),
        "actor VDBE expression success published a transaction"
    );
    let evidence = hot_path_profile_snapshot().vdbe;
    assert!(
        evidence.opcodes_executed_total > 0
            && evidence.statements_total > 0
            && !evidence.opcode_execution_totals.is_empty(),
        "actor VDBE expression profiler lacks opcode evidence: {evidence:?}"
    );
    let error = conn
        .query_with_params_sync(&over_sql, &over_params)
        .expect_err("actor expression height E+1 must fail closed");
    assert!(
        matches!(
            &error,
            FrankenError::ExpressionTooDeep { max } if *max == depth
        ),
        "actor VDBE expression returned wrong depth error: {error:?}"
    );
    assert!(
        !conn.in_transaction(),
        "actor VDBE expression error state was not immediately idle"
    );
    let rows = conn
        .query_with_params_sync(&exact_sql, &exact_params)
        .expect("actor VDBE marker must be reusable after rejection");
    assert_sum_result(&rows, depth, "actor VDBE expression reuse");
    assert!(
        !conn.in_transaction(),
        "actor VDBE reuse state was not immediately idle"
    );
    drop(profile);
}

fn run_actor_expr_subquery(conn: &AsyncConnection) {
    let depth = expression_depth_limit();
    let shallow_sql = fallback_expression_sql(2);
    let exact_sql = fallback_expression_sql(depth);
    let over_sql = fallback_expression_sql(depth + 1);

    conn.execute_sync("PRAGMA fsqlite.parity_cert_strict = ON;")
        .expect("enable actor fallback strict parity");
    let strict_error = conn
        .query_sync(&shallow_sql)
        .expect_err("actor strict parity must reject derived-source fallback")
        .to_string();
    assert!(
        strict_error.contains("decision_reason=join_or_subquery_fallback"),
        "actor strict fallback rejection omitted decision reason: {strict_error}"
    );
    assert!(
        !conn.in_transaction(),
        "actor strict fallback state was not immediately idle"
    );
    conn.execute_sync("PRAGMA fsqlite.parity_cert_strict = OFF;")
        .expect("disable actor fallback strict parity");

    let rows = conn
        .query_sync(&exact_sql)
        .expect("actor fallback expression height E must succeed");
    assert_fallback_result(&rows, "actor fallback expression exact depth");
    assert!(
        !conn.in_transaction(),
        "actor fallback success state was not immediately idle"
    );
    let error = conn
        .query_sync(&over_sql)
        .expect_err("actor fallback expression height E+1 must fail closed");
    assert!(
        matches!(
            &error,
            FrankenError::ExpressionTooDeep { max } if *max == depth
        ),
        "actor fallback expression returned wrong depth error: {error:?}"
    );
    assert!(
        !conn.in_transaction(),
        "actor fallback error state was not immediately idle"
    );
    let rows = conn
        .query_sync(&exact_sql)
        .expect("actor fallback marker must be reusable after rejection");
    assert_fallback_result(&rows, "actor fallback expression reuse");
    assert!(
        !conn.in_transaction(),
        "actor fallback reuse state was not immediately idle"
    );
}

fn run_actor_scenario() {
    let mut conn = AsyncConnection::open_sync(":memory:")
        .expect("actor stack-gate connection should open on its real worker");
    assert!(
        !conn.in_transaction(),
        "new actor connection unexpectedly published a transaction"
    );
    run_actor_mixed(&conn);
    run_actor_expr_vdbe(&conn);
    run_actor_expr_subquery(&conn);
    conn.close_sync()
        .expect("actor stack-gate worker should close and join");
}

#[test]
#[ignore = "diagnostic measurement, not a regression assertion"]
fn diag_worker_trigger_depth_survival() {
    let depth: usize = std::env::var("FSQLITE_PROBE_DEPTH")
        .ok()
        .and_then(|value| value.parse().ok())
        .unwrap_or(8);

    let runtime = RuntimeBuilder::current_thread()
        .blocking_threads(1, 1)
        .build()
        .expect("test runtime should build");

    runtime.block_on(async {
        let cx = Cx::new();
        let connection = AsyncConnection::open(&cx, ":memory:".to_owned())
            .await
            .expect("in-memory async connection should open");

        for statement in [
            "PRAGMA recursive_triggers = ON;".to_owned(),
            "CREATE TABLE a (n INTEGER);".to_owned(),
            "CREATE TABLE b (n INTEGER);".to_owned(),
            "INSERT INTO a VALUES (0);".to_owned(),
            "INSERT INTO b VALUES (0);".to_owned(),
            format!(
                "CREATE TRIGGER trg_a AFTER UPDATE ON a WHEN NEW.n < {depth} \
                 BEGIN UPDATE b SET n = NEW.n + 1; END;"
            ),
            format!(
                "CREATE TRIGGER trg_b AFTER UPDATE ON b WHEN NEW.n < {depth} \
                 BEGIN UPDATE a SET n = NEW.n + 1; END;"
            ),
        ] {
            connection
                .execute(&cx, &statement)
                .await
                .unwrap_or_else(|error| panic!("setup statement failed: {statement}: {error}"));
        }

        let result = connection.execute(&cx, "UPDATE a SET n = 1;").await;
        match result {
            Ok(_) => println!("PROBE_SURVIVED worker depth={depth}"),
            Err(error) => println!("PROBE_ERROR worker depth={depth} error={error}"),
        }
    });
}