fireweed-dsl-postgres 0.36.0

PostgreSQL executor for Fireweed's data-plane DSL (API-008): DDL from schemas and plain SQL for each statement.
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
//! Each resolved statement as one SQL statement (API-008 §Statements).

use std::collections::{BTreeMap, BTreeSet};

use fireweed_dsl::check::{
    Agg, Column, Expr, Kind, Obj as DslObj, Output, QueueRow, RPatch, RSelect, RStatement,
    Selection,
};
use fireweed_dsl::{
    Expect, FieldType, LeasedPolicy, MergeRule, OnConflict, OnLimit, OnUnmet, Outcome as Settle,
    RejectReason,
};
use serde_json::{Value, json};
use tokio_postgres::types::Type;
use tokio_postgres::{Row, Transaction};

use crate::ddl::{queue_table, table_table};
use crate::lower::{NOW, Obj, Q, cast, merge_ok};
use crate::{Attempt, Space, Swept, rows};

pub enum Outcome {
    Done(Value),
    Rejected(RejectReason),
}

type R = std::result::Result<Outcome, Attempt>;

fn obj(sp: &Space, o: &DslObj) -> Obj {
    Obj::new(&sp.schema_name, &sp.schema, o, "o")
}

async fn query(tx: &Transaction<'_>, q: &Q) -> std::result::Result<Vec<Row>, Attempt> {
    Ok(rows(tx, q).await?)
}

fn parse(text: &str) -> std::result::Result<Value, Attempt> {
    serde_json::from_str(text)
        .map_err(|e| Attempt::Failed(fireweed_dsl::Error::Unavailable(e.to_string())))
}

/// The outcome of an unmet `expect`, if it is unmet: a rejection, or with
/// `on_unmet: report` a result saying so. A guarded write's SQL already
/// skipped its changes when the count missed.
fn unmet(expect: &Option<Expect>, matched: i64) -> Option<Outcome> {
    let e = expect.as_ref().filter(|e| !e.holds(matched as u64))?;
    Some(match e.on_unmet {
        OnUnmet::Reject => Outcome::Rejected(RejectReason::ExpectUnmet),
        OnUnmet::Report => Outcome::Done(json!({"matched": matched, "met": false})),
    })
}

/// Adds `met: true` to a result when the statement had an `expect`.
fn with_met(mut out: Value, expect: &Option<Expect>) -> Value {
    if expect.is_some() {
        out["met"] = json!(true);
    }
    out
}

/// `min <= count <= max` in SQL, for a count expression.
fn expect_sql(q: &mut Q, count: &str, e: &Option<Expect>) -> String {
    let Some(e) = e else { return "true".into() };
    let mut parts = vec!["true".to_string()];
    if let Some(m) = e.min {
        parts.push(format!("{count} >= {}", q.bind_i64(m as i64)));
    }
    if let Some(m) = e.max {
        parts.push(format!("{count} <= {}", q.bind_i64(m as i64)));
    }
    parts.join(" AND ")
}

pub async fn statement(tx: &Transaction<'_>, sp: &Space, st: &RStatement) -> R {
    match st {
        RStatement::InsertQueue {
            obj: o,
            rows,
            on_conflict,
        } => insert_queue(tx, sp, o, rows, *on_conflict).await,
        RStatement::InsertTable {
            obj: o,
            rows,
            on_conflict,
        } => insert_table(tx, sp, o, rows, *on_conflict).await,
        RStatement::Claim {
            obj: o,
            limit,
            lease_ms,
            worker,
            filter,
            eligible_at,
        } => {
            let ob = obj(sp, o);
            let mut q = Q::default();
            let (elig, bound) = match eligible_at {
                Some(e) => {
                    let e = ob.operand(&mut q, e);
                    (e.clone(), format!("greatest({e}, {NOW})"))
                }
                None => (NOW.to_string(), NOW.to_string()),
            };
            let filter = filter
                .as_ref()
                .map(|p| format!(" AND {}", ob.pred(&mut q, p)))
                .unwrap_or_default();
            let queue = q.bind(Some(o.name.clone()));
            let desc = if sp.schema.queues[&o.name].priority == fireweed_dsl::PriorityOrder::Desc {
                " DESC"
            } else {
                ""
            };
            let worker = q.bind(Some(worker.clone()));
            let lease = q.duration(*lease_ms);
            let n = q.bind_i64(*limit as i64);
            let item = item_json(sp, &o.name, &ob);
            // Claim order is due time, then priority, then id: the claim
            // index's order, so the scan stops after `limit` claimable items
            // whether most items are due or most are sleeping.
            q.sql = format!(
                "WITH c AS (
                   SELECT o.id, o.due_at AS prev_due, o.priority FROM {t} o
                   WHERE o.state IN ('pending', 'leased') AND o.due_at <= {bound}
                     AND ((o.state = 'pending' AND o.due_at <= {elig})
                          OR (o.state = 'leased' AND o.due_at <= {NOW} AND NOT ({exhausted}))){filter}
                     AND NOT EXISTS (SELECT 1 FROM \"{s}\".fw_queue_state p WHERE p.queue = {queue} AND p.paused)
                   ORDER BY o.due_at, o.priority{desc}, o.id
                   LIMIT {n}
                   FOR UPDATE SKIP LOCKED),
                 u AS (
                   UPDATE {t} o SET state = 'leased', lease_token = gen_random_uuid()::text, lease_owner = {worker},
                     due_at = {NOW} + {lease}, attempts = o.attempts + 1, version = {ver}, updated_at = {NOW}
                   FROM c WHERE o.id = c.id
                   RETURNING c.prev_due, c.priority, o.id, {item} AS j)
                 SELECT j::text FROM u ORDER BY prev_due, priority{desc}, id",
                t = ob.table,
                s = sp.schema_name,
                ver = ob.next_version(),
                exhausted = ob.exhausted("o"),
            );
            let items = query(tx, &q)
                .await?
                .iter()
                .map(|r| parse(r.get(0)))
                .collect::<Result<Vec<_>, _>>()?;
            Ok(Outcome::Done(Value::Array(items)))
        }
        RStatement::Settle {
            obj: o,
            outcome,
            items,
            after_ms,
            set,
            body,
            require_all,
        } => {
            let ob = obj(sp, o);
            let mut q = Q::default();
            let exhausted = ob.exhausted("o");
            let mut sets = match outcome {
                Settle::Complete => {
                    vec!["state = 'complete'".into(), format!("finished_at = {NOW}")]
                }
                Settle::Fail => vec!["state = 'failed'".into(), format!("finished_at = {NOW}")],
                Settle::Retry => vec![
                    format!("state = CASE WHEN {exhausted} THEN 'failed' ELSE 'pending' END"),
                    format!("finished_at = CASE WHEN {exhausted} THEN {NOW} END"),
                    format!("due_at = {NOW} + {}", q.duration(*after_ms)),
                ],
                Settle::Release => vec![
                    "state = 'pending'".into(),
                    format!("due_at = {NOW} + {}", q.duration(*after_ms)),
                    "attempts = greatest(o.attempts - 1, 0)".into(),
                ],
            };
            sets.push("lease_token = NULL".into());
            sets.push("lease_owner = NULL".into());
            lease_update(tx, &ob, q, sets, set, body, items, *require_all).await
        }
        RStatement::Renew {
            obj: o,
            items,
            lease_ms,
            require_all,
        } => {
            let ob = obj(sp, o);
            let mut q = Q::default();
            let sets = vec![format!("due_at = {NOW} + {}", q.duration(*lease_ms))];
            lease_update(tx, &ob, q, sets, &[], &[], items, *require_all).await
        }
        RStatement::Update {
            obj: o,
            sel,
            set,
            body,
            leased,
            limit,
            on_limit,
            expect,
            override_merge,
        } => {
            update(
                tx,
                sp,
                o,
                sel,
                set,
                body,
                *leased,
                *limit,
                *on_limit,
                expect,
                *override_merge,
            )
            .await
        }
        RStatement::Delete {
            obj: o,
            sel,
            limit,
            expect,
        } => {
            let ob = obj(sp, o);
            let mut q = Q::default();
            let cond = selection(&ob, &mut q, sel);
            let lim = q.bind_i64(*limit as i64);
            let lim1 = q.bind_i64(*limit as i64 + 1);
            let ok = expect_sql(&mut q, "(SELECT c FROM total)", expect);
            q.sql = format!(
                "WITH m AS (SELECT o.id FROM {t} o WHERE {cond} ORDER BY o.id LIMIT {lim1} FOR UPDATE),
                 total AS (SELECT count(*) AS c FROM m),
                 d AS (DELETE FROM {t} o USING m WHERE o.id = m.id AND (SELECT c FROM total) <= {lim} AND {ok} RETURNING 1)
                 SELECT (SELECT c FROM total), (SELECT count(*) FROM d)",
                t = ob.table
            );
            let total: i64 = query(tx, &q).await?[0].get(0);
            if total > *limit as i64 {
                return Ok(Outcome::Rejected(RejectReason::LimitExceeded));
            }
            if let Some(unmet) = unmet(expect, total) {
                return Ok(unmet);
            }
            Ok(Outcome::Done(with_met(json!({"matched": total}), expect)))
        }
        RStatement::Assert {
            obj: o,
            sel,
            expect,
        } => {
            let ob = obj(sp, o);
            let mut q = Q::default();
            let cond = selection(&ob, &mut q, sel);
            // Count only as far as the expectation needs. Matched rows stay
            // locked against change until commit.
            let cap =
                q.bind_i64(expect.max.map_or(expect.min.unwrap_or(0), |m| m + 1).max(1) as i64);
            q.sql = format!(
                "SELECT count(*) FROM (SELECT 1 FROM {} o WHERE {cond} LIMIT {cap} FOR SHARE) x",
                ob.table
            );
            let n: i64 = query(tx, &q).await?[0].get(0);
            let expect = Some(*expect);
            if let Some(unmet) = unmet(&expect, n) {
                return Ok(unmet);
            }
            Ok(Outcome::Done(with_met(json!({"matched": n}), &expect)))
        }
        RStatement::Select(s) => select(tx, sp, s).await,
        RStatement::SetPaused { obj: o, paused } => {
            let mut q = Q::default();
            let name = q.bind(Some(o.name.clone()));
            let p = q.bind(Some(paused.to_string()));
            q.sql = format!(
                "INSERT INTO \"{}\".fw_queue_state (queue, paused) VALUES ({name}, {p}::boolean)
                 ON CONFLICT (queue) DO UPDATE SET paused = EXCLUDED.paused",
                sp.schema_name
            );
            query(tx, &q).await?;
            Ok(Outcome::Done(json!({})))
        }
    }
}

/// `set`, `body`, version and `updated_at` for rows aliased `o`.
fn common_sets(ob: &Obj, q: &mut Q, set: &[(Column, Expr)], body: &[RPatch]) -> Vec<String> {
    let mut sets: Vec<String> = set.iter().map(|(c, e)| ob.assign(q, c, e)).collect();
    sets.extend(ob.patches(q, body));
    sets.push(format!("version = {}", ob.next_version()));
    sets.push(format!("updated_at = {NOW}"));
    sets
}

/// Settle and renew: one `UPDATE` over the items whose token matches an
/// unexpired lease. Other items are reported `stale` (ADR-027 D6).
#[allow(clippy::too_many_arguments)]
async fn lease_update(
    tx: &Transaction<'_>,
    ob: &Obj,
    mut q: Q,
    mut sets: Vec<String>,
    set: &[(Column, Expr)],
    body: &[RPatch],
    items: &[(i64, String)],
    require_all: bool,
) -> R {
    sets.extend(common_sets(ob, &mut q, set, body));
    let list = Value::Array(
        items
            .iter()
            .map(|(id, t)| json!({"id": id, "token": t}))
            .collect(),
    );
    let items_p = q.bind_json(&list);
    q.sql = format!(
        "UPDATE {t} o SET {sets}
         FROM (SELECT DISTINCT * FROM jsonb_to_recordset({items_p}) AS i(id bigint, token text)) i
         WHERE o.id = i.id AND o.lease_token = i.token AND o.state = 'leased' AND o.due_at > {NOW}
         RETURNING o.id",
        t = ob.table,
        sets = sets.join(", "),
    );
    let done: BTreeSet<i64> = query(tx, &q).await?.iter().map(|r| r.get(0)).collect();
    if require_all && items.iter().any(|(id, _)| !done.contains(id)) {
        return Ok(Outcome::Rejected(RejectReason::StaleLease));
    }
    Ok(Outcome::Done(Value::Array(
        items
            .iter()
            .map(|(id, _)| json!({"id": id, "status": if done.contains(id) { "ok" } else { "stale" }}))
            .collect(),
    )))
}

/// The `WHERE` condition for a selection, over rows aliased `o`.
fn selection(ob: &Obj, q: &mut Q, sel: &Selection) -> String {
    let mut conds = vec![ob.live()];
    if let Some(p) = &sel.filter {
        conds.push(ob.pred(q, p));
    }
    if let Some(ids) = &sel.ids {
        conds.push(format!("o.id = ANY({})", q.bind_ids(ids)));
    }
    if let Some(keys) = &sel.queue_keys {
        let p = q.bind_json(&Value::Array(keys.iter().map(|k| json!(k)).collect()));
        conds.push(format!(
            "o.key = ANY(ARRAY(SELECT jsonb_array_elements_text({p})))"
        ));
    }
    if let Some(keys) = &sel.table_keys {
        let tuples: Vec<String> = keys
            .iter()
            .map(|k| {
                format!(
                    "({})",
                    k.iter()
                        .map(|v| ob.operand(q, v))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            })
            .collect();
        let cols: Vec<String> = ob.key.iter().map(|k| format!("o.\"f_{k}\"")).collect();
        conds.push(format!("({}) IN ({})", cols.join(", "), tuples.join(", ")));
    }
    conds.join(" AND ")
}

/// One statement: lock up to `limit + 1` matching rows in id order, count
/// them, and update the first `limit` if the count allows it.
#[allow(clippy::too_many_arguments)]
async fn update(
    tx: &Transaction<'_>,
    sp: &Space,
    o: &DslObj,
    sel: &Selection,
    set: &[(Column, Expr)],
    body: &[RPatch],
    leased: LeasedPolicy,
    limit: u32,
    on_limit: OnLimit,
    expect: &Option<Expect>,
    override_merge: bool,
) -> R {
    let ob = obj(sp, o);
    let mut q = Q::default();
    let mut cond = selection(&ob, &mut q, sel);
    if ob.kind == Kind::Queue && leased == LeasedPolicy::Skip {
        cond.push_str(&format!(
            " AND NOT (o.state = 'leased' AND o.due_at > {NOW})"
        ));
    }
    // Fields with merge rules: their old values travel with the locked rows.
    let rules: Vec<(String, MergeRule)> = match (ob.kind, override_merge) {
        (Kind::Table, false) => {
            let decl = &sp.schema.tables[&o.name];
            set.iter()
                .filter_map(|(c, _)| {
                    decl.fields
                        .get(&c.name)
                        .and_then(|f| f.merge)
                        .map(|m| (Obj::col_name(c), m))
                })
                .collect()
        }
        _ => vec![],
    };
    let olds: String = rules
        .iter()
        .enumerate()
        .map(|(i, (c, _))| format!(", o.{c} AS old_{i}"))
        .collect();
    let mut checks: Vec<String> = rules
        .iter()
        .enumerate()
        .map(|(i, (c, m))| merge_ok(*m, &format!("old.old_{i}"), &format!("o.{c}")))
        .collect();
    checks.push("true".into());

    let mut sets = common_sets(&ob, &mut q, set, body);
    let sets_state = set.iter().any(|(c, _)| c.system && c.name == "state");
    let sets_due = set.iter().any(|(c, _)| c.system && c.name == "due_at");
    if sets_state {
        // `o.state` here is the old value; the new one decides finished_at.
        let new_state = set
            .iter()
            .find(|(c, _)| c.system && c.name == "state")
            .map(|(_, e)| e);
        if let Some(Expr::Operand(fireweed_dsl::check::Operand::Literal(Value::String(st), _))) =
            new_state
        {
            let fin = if st == "pending" {
                "NULL".to_string()
            } else {
                NOW.to_string()
            };
            sets.push(format!("finished_at = {fin}"));
        }
    }
    // Unless leases are preserved, no matched row keeps a lease: a live
    // lease is broken (`break`), and an expired one is written back as its
    // effective state, so its old token can never settle (ADR-027 D6).
    if ob.kind == Kind::Queue && leased != LeasedPolicy::Preserve {
        let exhausted = ob.exhausted("o");
        let lapsed = format!("(o.state = 'leased' AND o.due_at <= {NOW})");
        sets.push("lease_token = NULL".into());
        sets.push("lease_owner = NULL".into());
        if !sets_state {
            sets.push(format!(
                "state = CASE WHEN o.state <> 'leased' THEN o.state \
                 WHEN {lapsed} AND {exhausted} THEN 'failed' ELSE 'pending' END"
            ));
            sets.push(format!(
                "finished_at = CASE WHEN {lapsed} AND {exhausted} THEN o.due_at ELSE o.finished_at END"
            ));
        }
        if !sets_due {
            sets.push(format!(
                "due_at = CASE WHEN o.state = 'leased' AND o.due_at > {NOW} THEN {NOW} ELSE o.due_at END"
            ));
        }
    } else if sets_state {
        sets.push("lease_token = NULL".into());
        sets.push("lease_owner = NULL".into());
    }
    if ob.kind == Kind::Table
        && let Some(ttl) = sp.schema.tables[&o.name].expire_after_write
    {
        sets.push(format!("expires_at = {NOW} + {}", q.duration(ttl.0)));
    }
    let lim = q.bind_i64(limit as i64);
    let lim1 = q.bind_i64(limit as i64 + 1);
    let mut go = expect_sql(&mut q, "(SELECT c FROM total)", expect);
    if on_limit == OnLimit::Reject {
        go = format!("{go} AND (SELECT c FROM total) <= {lim}");
    }
    q.sql = format!(
        "WITH m AS (SELECT o.id{olds} FROM {t} o WHERE {cond} ORDER BY o.id LIMIT {lim1} FOR UPDATE),
         total AS (SELECT count(*) AS c FROM m),
         take AS (SELECT * FROM m ORDER BY id LIMIT {lim}),
         u AS (UPDATE {t} o SET {sets} FROM take old WHERE o.id = old.id AND {go} RETURNING {checks} AS ok)
         SELECT (SELECT c FROM total), (SELECT max(id) FROM take), coalesce((SELECT bool_and(ok) FROM u), true)",
        t = ob.table,
        sets = sets.join(", "),
        checks = checks.join(" AND "),
    );
    let r = &query(tx, &q).await?[0];
    let (total, last, ok): (i64, Option<i64>, bool) = (r.get(0), r.get(1), r.get(2));
    let over = total > limit as i64;
    if over && on_limit == OnLimit::Reject {
        return Ok(Outcome::Rejected(RejectReason::LimitExceeded));
    }
    if let Some(unmet) = unmet(expect, total) {
        return Ok(unmet);
    }
    if !ok {
        return Ok(Outcome::Rejected(RejectReason::MergeViolation));
    }
    let mut out = with_met(json!({"matched": total.min(limit as i64)}), expect);
    if on_limit == OnLimit::Step {
        out["last"] = json!(last);
        if over {
            out["more"] = json!(true);
        }
    }
    Ok(Outcome::Done(out))
}

/// The JSON a claim returns for a queue item, with its lease token.
fn item_json(sp: &Space, queue: &str, ob: &Obj) -> String {
    let mut cols: Vec<(String, String)> = ["id", "key", "attempts", "priority", "version", "body"]
        .iter()
        .map(|c| (c.to_string(), format!("o.{c}")))
        .collect();
    cols.push(("token".into(), "o.lease_token".into()));
    for f in sp.schema.queues[queue].fields.keys() {
        cols.push((f.clone(), format!("o.\"f_{f}\"")));
    }
    ob.json_of(&cols)
}

/// A select: one `SELECT`, with its grouping, order and limit. A sorted or
/// aggregating select reads every row its `where` matches; the statement
/// timeout bounds it.
async fn select(tx: &Transaction<'_>, sp: &Space, s: &RSelect) -> R {
    let ob = obj(sp, &s.obj);
    let mut q = Q::default();
    let mut cond = vec![ob.live()];
    if let Some(p) = &s.filter {
        cond.push(ob.pred(&mut q, p));
    }
    let (cols, group) = match &s.output {
        Output::Fields(cs) => (
            cs.iter()
                .map(|c| (c.name.clone(), ob.col(c)))
                .collect::<Vec<_>>(),
            String::new(),
        ),
        Output::Aggregate { aggs, group_by } => {
            let mut cols: Vec<(String, String)> = group_by
                .iter()
                .map(|c| (c.name.clone(), ob.col(c)))
                .collect();
            for (name, a) in aggs {
                let e = match a {
                    Agg::Count => "count(*)".to_string(),
                    Agg::Sum(c) => format!("sum({})", ob.col(c)),
                    Agg::Min(c) => format!("min({})", ob.col(c)),
                    Agg::Max(c) => format!("max({})", ob.col(c)),
                    Agg::Avg(c) => format!("avg({})", ob.col(c)),
                    Agg::Percentile(c, p) => format!(
                        "percentile_disc({}::double precision) WITHIN GROUP (ORDER BY {})",
                        q.bind(Some(p.to_string())),
                        ob.col(c)
                    ),
                };
                cols.push((name.clone(), e));
            }
            let group = if group_by.is_empty() {
                String::new()
            } else {
                format!(
                    " GROUP BY {}",
                    group_by
                        .iter()
                        .map(|c| ob.col(c))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            };
            (cols, group)
        }
    };
    let named: BTreeMap<String, String> = cols.iter().cloned().collect();
    let order = if s.order_by.is_empty() {
        String::new()
    } else {
        let keys: Vec<String> = s
            .order_by
            .iter()
            .map(|(n, desc)| format!("{}{}", named[n], if *desc { " DESC" } else { "" }))
            .collect();
        format!(" ORDER BY {}", keys.join(", "))
    };
    let n = q.bind_i64(s.limit as i64);
    q.sql = format!(
        "SELECT {}::text FROM {} o WHERE {}{group}{order} LIMIT {n}",
        ob.json_of(&cols),
        ob.table,
        cond.join(" AND ")
    );
    let rs = query(tx, &q).await?;
    let out = rs
        .iter()
        .map(|r| parse(r.get(0)))
        .collect::<Result<Vec<_>, _>>()?;
    Ok(Outcome::Done(Value::Array(out)))
}

/// How a field travels through `jsonb_to_recordset`.
fn record_type(t: FieldType) -> &'static str {
    match t {
        FieldType::TextSet => "jsonb",
        other => cast(other),
    }
}

fn record_value(e: &str, t: FieldType) -> String {
    match t {
        FieldType::TextSet => format!("fireweed.text_set({e})"),
        _ => e.to_string(),
    }
}

/// One statement: insert the rows; a key held by a finished item past
/// retention is taken over; other conflicts are reported `exists`.
async fn insert_queue(
    tx: &Transaction<'_>,
    sp: &Space,
    o: &DslObj,
    rows: &[QueueRow],
    on_conflict: OnConflict,
) -> R {
    let ob = obj(sp, o);
    let decl = &sp.schema.queues[&o.name];
    let mut q = Q::default();
    let recs: Vec<Value> = rows
        .iter()
        .enumerate()
        .map(|(i, r)| {
            let mut m = serde_json::Map::new();
            m.insert("ord".into(), json!(i + 1));
            m.insert("key".into(), json!(r.key));
            m.insert("priority".into(), json!(r.priority));
            m.insert("due".into(), json!(r.due));
            m.insert("after_ms".into(), json!(r.after_ms));
            m.insert("body".into(), r.body.clone().unwrap_or(Value::Null));
            for (k, v) in &r.fields {
                m.insert(format!("f_{k}"), v.clone());
            }
            Value::Object(m)
        })
        .collect();
    let recs_again = Value::Array(recs);
    let p = q.bind_json(&recs_again);
    let retention = q.duration(decl.retention.0);
    let mut defs: Vec<String> = [
        "ord bigint",
        "key text",
        "priority bigint",
        "due timestamptz",
        "after_ms bigint",
        "body jsonb",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();
    let mut cols = vec![];
    let mut vals = vec![];
    for (f, d) in &decl.fields {
        defs.push(format!("\"f_{f}\" {}", record_type(d.ty)));
        cols.push(format!("\"f_{f}\""));
        vals.push(record_value(&format!("r.\"f_{f}\""), d.ty));
    }
    let system = [
        "id",
        "state",
        "priority",
        "due_at",
        "attempts",
        "version",
        "lease_owner",
        "lease_token",
        "created_at",
        "updated_at",
        "finished_at",
        "body",
    ];
    let take_over: Vec<String> = system
        .iter()
        .map(|c| c.to_string())
        .chain(cols.iter().cloned())
        .map(|c| format!("{c} = EXCLUDED.{c}"))
        .collect();
    let cols: String = cols.iter().map(|c| format!(", {c}")).collect();
    let vals: String = vals.iter().map(|v| format!(", {v}")).collect();
    q.sql = format!(
        "WITH r AS (
           SELECT r.*, nextval(pg_get_serial_sequence('{t}', 'id')) AS new_id
           FROM jsonb_to_recordset({p}) AS r({defs})),
         ins AS (
           INSERT INTO {t} AS t (id, key, state, priority, due_at, attempts, version, lease_owner, lease_token, created_at, updated_at, finished_at, body{cols})
           SELECT r.new_id, r.key, 'pending', coalesce(r.priority, 0),
                  coalesce(r.due, {NOW} + coalesce(r.after_ms, 0) * interval '1 millisecond'),
                  0, {ver}, NULL, NULL, {NOW}, {NOW}, NULL, r.body{vals}
           FROM r ORDER BY r.ord
           ON CONFLICT (key) DO UPDATE SET {take_over}
             WHERE t.finished_at <= {NOW} - {retention}
           RETURNING t.id)
         SELECT r.key, coalesce(ins.id, e.id), ins.id IS NOT NULL
         FROM r LEFT JOIN ins ON ins.id = r.new_id LEFT JOIN {t} e ON e.key = r.key
         ORDER BY r.ord",
        t = ob.table,
        defs = defs.join(", "),
        take_over = take_over.join(", "),
        ver = ob.next_version(),
    );
    let mut out = vec![];
    for row in query(tx, &q).await? {
        let (key, id, inserted): (Option<String>, Option<i64>, bool) =
            (row.get(0), row.get(1), row.get(2));
        if !inserted && on_conflict == OnConflict::Reject {
            return Ok(Outcome::Rejected(RejectReason::KeyConflict));
        }
        out.push(
            json!({"id": id, "key": key, "status": if inserted { "inserted" } else { "exists" }}),
        );
    }
    refetch_ids(
        tx,
        &ob.table,
        &mut out,
        &recs_again,
        "ord bigint, key text",
        "e.key = r.key",
    )
    .await?;
    Ok(Outcome::Done(Value::Array(out)))
}

/// Ids of rows reported `exists` that the insert's own snapshot couldn't
/// see: a concurrent insert of the same key committed while the insert
/// waited on it. A second statement gets a fresh snapshot under READ
/// COMMITTED. It runs only when that race happened.
async fn refetch_ids(
    tx: &Transaction<'_>,
    table: &str,
    out: &mut [Value],
    recs: &Value,
    defs: &str,
    on: &str,
) -> std::result::Result<(), Attempt> {
    let missing: Vec<i64> = out
        .iter()
        .enumerate()
        .filter(|(_, e)| e["id"].is_null())
        .map(|(i, _)| i as i64 + 1)
        .collect();
    if missing.is_empty() {
        return Ok(());
    }
    let mut q = Q::default();
    let p = q.bind_json(recs);
    let ords = q.bind_ids(&missing);
    q.sql = format!(
        "SELECT r.ord, e.id FROM jsonb_to_recordset({p}) AS r({defs}) JOIN {table} e ON {on} WHERE r.ord = ANY({ords})"
    );
    for row in query(tx, &q).await? {
        let (ord, id): (i64, i64) = (row.get(0), row.get(1));
        out[ord as usize - 1]["id"] = json!(id);
    }
    Ok(())
}

/// One statement per insert. A row past its expiry gives up its key; with
/// `update`, a conflicting row takes the given fields under merge rules.
async fn insert_table(
    tx: &Transaction<'_>,
    sp: &Space,
    o: &DslObj,
    rows: &[BTreeMap<String, Value>],
    on_conflict: OnConflict,
) -> R {
    let ob = obj(sp, o);
    let decl = &sp.schema.tables[&o.name];
    let mut q = Q::default();
    let recs: Vec<Value> = rows
        .iter()
        .enumerate()
        .map(|(i, r)| {
            let mut m: serde_json::Map<String, Value> = r
                .iter()
                .map(|(k, v)| (format!("f_{k}"), v.clone()))
                .collect();
            m.insert("ord".into(), json!(i + 1));
            Value::Object(m)
        })
        .collect();
    let expires = match decl.expire_after_write {
        Some(d) => format!("{NOW} + {}", q.duration(d.0)),
        None => "NULL::timestamptz".into(),
    };
    let recs_again = Value::Array(recs);
    let p = q.bind_json(&recs_again);
    let t = &ob.table;
    let mut defs = vec!["ord bigint".to_string()];
    let mut cols = vec![];
    let mut vals = vec![];
    for (f, d) in &decl.fields {
        defs.push(format!("\"f_{f}\" {}", record_type(d.ty)));
        cols.push(format!("\"f_{f}\""));
        vals.push(record_value(&format!("r.\"f_{f}\""), d.ty));
    }
    let defs = defs.join(", ");
    if decl.sequenced {
        // The counter row is held to commit, so ids are gapless and in commit
        // order; the checker puts these inserts last in a program.
        let name = q.bind(Some(o.name.clone()));
        let n = q.bind_i64(rows.len() as i64);
        q.sql = format!(
            "WITH s AS (UPDATE \"{s}\".fw_sequences SET last = last + {n} WHERE tbl = {name} RETURNING last),
             r AS (SELECT * FROM jsonb_to_recordset({p}) AS r({defs}))
             INSERT INTO {t} (id, version, created_at, updated_at, expires_at, {cols})
             SELECT (SELECT last FROM s) - {n} + r.ord, {ver}, {NOW}, {NOW}, {expires}, {vals} FROM r ORDER BY r.ord
             RETURNING id",
            s = sp.schema_name,
            cols = cols.join(", "),
            vals = vals.join(", "),
            ver = ob.next_version(),
        );
        let mut ids: Vec<i64> = query(tx, &q).await?.iter().map(|r| r.get(0)).collect();
        ids.sort_unstable();
        return Ok(Outcome::Done(Value::Array(
            ids.into_iter()
                .map(|id| json!({"id": id, "status": "inserted"}))
                .collect(),
        )));
    }
    let expired = format!("coalesce(t.expires_at <= {NOW}, false)");
    let conflict = match on_conflict {
        OnConflict::Update => {
            let given: Vec<&String> = rows[0].keys().filter(|k| !decl.key.contains(*k)).collect();
            let mut sets: Vec<String> = given
                .iter()
                .map(|g| format!("\"f_{g}\" = EXCLUDED.\"f_{g}\""))
                .collect();
            if decl.expire_after_write.is_some() {
                // An expired row starts over: fields this insert doesn't give are cleared.
                for f in decl
                    .fields
                    .keys()
                    .filter(|f| !decl.key.contains(*f) && !given.contains(f))
                {
                    sets.push(format!(
                        "\"f_{f}\" = CASE WHEN {expired} THEN NULL ELSE t.\"f_{f}\" END"
                    ));
                }
            }
            sets.push("version = EXCLUDED.version".into());
            sets.push("updated_at = EXCLUDED.updated_at".into());
            sets.push("expires_at = EXCLUDED.expires_at".into());
            let rules: Vec<String> = given
                .iter()
                .filter_map(|g| {
                    decl.fields[*g].merge.map(|m| {
                        format!(
                            "({expired} OR {})",
                            merge_ok(m, &format!("t.\"f_{g}\""), &format!("EXCLUDED.\"f_{g}\""))
                        )
                    })
                })
                .collect();
            let guard = if rules.is_empty() {
                String::new()
            } else {
                format!(" WHERE {}", rules.join(" AND "))
            };
            format!("DO UPDATE SET {}{guard}", sets.join(", "))
        }
        _ if decl.expire_after_write.is_some() => {
            let take_over: Vec<String> =
                ["id", "version", "created_at", "updated_at", "expires_at"]
                    .iter()
                    .map(|c| c.to_string())
                    .chain(cols.iter().cloned())
                    .map(|c| format!("{c} = EXCLUDED.{c}"))
                    .collect();
            format!("DO UPDATE SET {} WHERE {expired}", take_over.join(", "))
        }
        _ => "DO NOTHING".into(),
    };
    let key: Vec<String> = decl.key.iter().map(|k| format!("\"f_{k}\"")).collect();
    let on = |a: &str| {
        decl.key
            .iter()
            .map(|k| format!("{a}.\"f_{k}\" = r.\"f_{k}\""))
            .collect::<Vec<_>>()
            .join(" AND ")
    };
    q.sql = format!(
        "WITH r AS (
           SELECT r.*, nextval(pg_get_serial_sequence('{t}', 'id')) AS new_id
           FROM jsonb_to_recordset({p}) AS r({defs})),
         ins AS (
           INSERT INTO {t} AS t (id, version, created_at, updated_at, expires_at, {cols})
           SELECT r.new_id, {ver}, {NOW}, {NOW}, {expires}, {vals} FROM r ORDER BY r.ord
           ON CONFLICT ({key}) {conflict}
           RETURNING t.id, t.xmax = 0 AS fresh, {key})
         SELECT coalesce(ins.id, e.id), ins.id IS NOT NULL, coalesce(ins.fresh, false)
         FROM r LEFT JOIN ins ON {on_ins} LEFT JOIN {t} e ON {on_e}
         ORDER BY r.ord",
        cols = cols.join(", "),
        vals = vals.join(", "),
        key = key.join(", "),
        ver = ob.next_version(),
        on_ins = on("ins"),
        on_e = on("e"),
    );
    let mut out = vec![];
    for row in query(tx, &q).await? {
        let (id, returned, fresh): (Option<i64>, bool, bool) = (row.get(0), row.get(1), row.get(2));
        let status = match (returned, on_conflict) {
            (true, OnConflict::Update) if !fresh => "updated",
            (true, _) => "inserted",
            (false, OnConflict::Update) => {
                return Ok(Outcome::Rejected(RejectReason::MergeViolation));
            }
            (false, OnConflict::Reject) => return Ok(Outcome::Rejected(RejectReason::KeyConflict)),
            (false, OnConflict::Skip) => "exists",
        };
        out.push(json!({"id": id, "status": status}));
    }
    let key_defs: Vec<String> = std::iter::once("ord bigint".to_string())
        .chain(
            decl.key
                .iter()
                .map(|k| format!("\"f_{k}\" {}", record_type(decl.fields[k].ty))),
        )
        .collect();
    refetch_ids(tx, t, &mut out, &recs_again, &key_defs.join(", "), &on("e")).await?;
    Ok(Outcome::Done(Value::Array(out)))
}

/// Writes back expired leases and deletes what retention expired, at most
/// `batch` rows per object. Rows other transactions hold are skipped, and
/// each row's condition is checked again under its lock.
pub async fn sweep(
    tx: &Transaction<'_>,
    sp: &Space,
    batch: i64,
) -> std::result::Result<Swept, tokio_postgres::Error> {
    let mut out = Swept::default();
    // (counts as expired leases, SQL, the retention bound as $2 if any)
    let mut work: Vec<(bool, String, Option<i64>)> = vec![];
    let pick = |t: &str, cond: &str, id: &str| {
        format!(
            "(SELECT {id} FROM {t} o WHERE {cond} LIMIT $1::text::bigint FOR UPDATE SKIP LOCKED)"
        )
    };
    let aged =
        |col: &str| format!("o.{col} <= {NOW} - $2::text::bigint * interval '1 millisecond'");
    for (name, decl) in &sp.schema.queues {
        let t = queue_table(&sp.schema_name, name);
        let ob = obj(
            sp,
            &DslObj {
                name: name.clone(),
                kind: Kind::Queue,
            },
        );
        let exhausted = ob.exhausted("o");
        let expired = format!("o.state = 'leased' AND o.due_at <= {NOW}");
        work.push((
            true,
            format!(
                "UPDATE {t} o SET state = CASE WHEN {exhausted} THEN 'failed' ELSE 'pending' END,
                   finished_at = CASE WHEN {exhausted} THEN o.due_at END,
                   lease_token = NULL, lease_owner = NULL, version = {ver}
                 FROM {s} s WHERE o.id = s.id AND {expired}",
                s = pick(&t, &expired, "id"),
                ver = ob.next_version(),
            ),
            None,
        ));
        let done = aged("finished_at");
        work.push((
            false,
            format!(
                "DELETE FROM {t} o USING {s} s WHERE o.id = s.id AND {done}",
                s = pick(&t, &done, "id")
            ),
            Some(decl.retention.0),
        ));
    }
    for (name, decl) in &sp.schema.tables {
        if decl.expire_after_write.is_none() {
            continue;
        }
        let t = table_table(&sp.schema_name, name);
        let gone = format!("o.expires_at <= {NOW}");
        work.push((
            false,
            format!(
                "DELETE FROM {t} o USING {s} s WHERE o.id = s.id AND {gone}",
                s = pick(&t, &gone, "id")
            ),
            None,
        ));
    }
    // Request records go once the space's horizon passes their issue time.
    // The horizon only moves forward, and open_space refuses requests issued
    // before it, so no request runs twice (ADR-027 D61).
    tx.execute_typed(
        "UPDATE fireweed.spaces SET horizon = greatest(horizon, fireweed.now() - $2::text::bigint * interval '1 millisecond') \
         WHERE id = $1::text::bigint",
        &[
            (&sp.id.to_string(), Type::TEXT),
            (&sp.schema.request_retention.0.to_string(), Type::TEXT),
        ],
    )
    .await?;
    let r = format!("\"{}\".fw_requests", sp.schema_name);
    let old = format!(
        "o.issued_at < (SELECT horizon FROM fireweed.spaces WHERE id = {})",
        sp.id
    );
    work.push((
        false,
        format!(
            "DELETE FROM {r} o USING {s} s WHERE o.request_id = s.request_id AND {old}",
            s = pick(&r, &old, "request_id")
        ),
        None,
    ));
    for (leases, sql, bound) in work {
        let mut params = vec![Some(batch.to_string())];
        params.extend(bound.map(|b| Some(b.to_string())));
        let q = Q {
            sql: format!("WITH x AS ({sql} RETURNING 1) SELECT count(*) FROM x"),
            params,
        };
        let n = rows(tx, &q).await?[0].get::<_, i64>(0) as u64;
        if leases {
            out.expired_leases += n;
        } else {
            out.deleted += n;
        }
    }
    Ok(out)
}

/// The response to record: claim results keep only ids and tokens, so a
/// record never copies item bodies (ADR-027 §5).
pub fn compact_claims(
    r: &fireweed_dsl::check::Resolved,
    resp: &fireweed_dsl::Response,
) -> fireweed_dsl::Response {
    let mut out = resp.clone();
    for (st, res) in r.statements.iter().zip(out.results.iter_mut()) {
        if matches!(st, RStatement::Claim { .. })
            && let Value::Array(items) = res
        {
            for it in items.iter_mut() {
                *it = json!({"id": it["id"], "token": it["token"]});
            }
        }
    }
    out
}

/// On replay, claim results are re-read: each item's current fields, with
/// the token the claim granted.
pub async fn rehydrate_claims(
    tx: &Transaction<'_>,
    sp: &Space,
    r: &fireweed_dsl::check::Resolved,
    resp: &mut fireweed_dsl::Response,
) -> std::result::Result<(), Attempt> {
    for (st, res) in r.statements.iter().zip(resp.results.iter_mut()) {
        let (RStatement::Claim { obj: o, .. }, Value::Array(items)) = (st, res) else {
            continue;
        };
        if items.is_empty() {
            continue;
        }
        let ob = obj(sp, o);
        let ids: Vec<i64> = items.iter().filter_map(|i| i["id"].as_i64()).collect();
        let mut q = Q::default();
        let p = q.bind_ids(&ids);
        let mut cols: Vec<(String, String)> =
            ["id", "key", "attempts", "priority", "version", "body"]
                .iter()
                .map(|c| (c.to_string(), format!("o.{c}")))
                .collect();
        for f in sp.schema.queues[&o.name].fields.keys() {
            cols.push((f.clone(), format!("o.\"f_{f}\"")));
        }
        q.sql = format!(
            "SELECT {}::text FROM {} o WHERE o.id = ANY({p})",
            ob.json_of(&cols),
            ob.table
        );
        let mut current: BTreeMap<i64, Value> = BTreeMap::new();
        for row in query(tx, &q).await? {
            let v = parse(row.get(0))?;
            current.insert(v["id"].as_i64().unwrap_or_default(), v);
        }
        for it in items.iter_mut() {
            if let Some(mut v) = it["id"].as_i64().and_then(|id| current.remove(&id)) {
                v["token"] = it["token"].clone();
                *it = v;
            }
        }
    }
    Ok(())
}