zc2 0.0.41

P2P compute broker with credit-based billing, WAL, and broker mesh support
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
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
//! Transaction flush buffer for batched API writes.
//!
//! Instead of writing each transaction to the dashboard API synchronously on the hot path,
//! completed transactions are queued here and flushed periodically (every 30s)
//! in a single batch. This removes the dashboard API call from the critical path when P2P mode
//! is enabled.

use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

use super::node_identity::now_secs;
use super::wal::{Wal, WalStatus};

/// Sentinel user id a broker assigns when it executes a job with no known
/// requester (local mode, no `X-Zakuro-User` header — see
/// `server::execute_prepare` and `deploy::serve::bill_served_request`, the
/// two sites that produce it). Local execution is single-node and free, and
/// the hub rejects this user by design (`User not found: anonymous`), so
/// there is nothing to settle and nothing to gain by buffering it.
pub const ANONYMOUS_USER: &str = "anonymous";

/// Number of failed flush attempts a transaction gets before it is
/// quarantined instead of re-queued. Bounds how long a permanently-rejected
/// transaction can block everything queued behind it in the same batch.
const MAX_FLUSH_ATTEMPTS: u32 = 5;

/// How many transactions go into one `batch-sync` POST.
///
/// The hub sits behind a proxy that refuses a request body over ~1 MiB with
/// `413`, and refusing it mid-upload is what the broker sees as
/// `io: Broken pipe (os error 32)` — it is still writing a body the far end
/// has already rejected. `flush_to_api` used to drain the WHOLE buffer into a
/// single POST, so one backlogged broker built a payload far past that limit:
/// 274,461 pending transactions is ~143 MB in one request. Every attempt then
/// failed identically, all five of them, and the entire backlog was
/// quarantined — 475 MB of `wal-rejected.jsonl` on one Mac, none of it ever
/// settled, while the hub itself was healthy and answering 200 (#330).
///
/// A transaction serializes to ~520 bytes, so 500 of them is ~260 KB — a
/// quarter of the limit, leaving room for long worker URIs and names. Pinned
/// by `a_full_batch_stays_under_the_hub_body_limit`.
const MAX_FLUSH_BATCH: usize = 500;

/// The serialized-size cap of one `batch-sync` POST body. Count alone is not
/// enough: a row carrying trust metadata (`sched::bill::MAX_TRUST_SAMPLES`
/// samples, ~106 B each) is several KB, so 500 of them would pass the hub's
/// 1 MiB limit and bring back #330. A chunk is closed before it would exceed
/// this; half the hub limit, so a long row cannot tip it over.
const MAX_FLUSH_BYTES: usize = 512 * 1024;

/// Pull the next chunk from a lazy `(item, serialized size)` source: at most
/// `MAX_FLUSH_BATCH` items and `MAX_FLUSH_BYTES` bytes of JSON array body. An
/// item that would overflow is parked in `carry` and opens the next chunk; a
/// single item larger than the cap travels alone (it cannot be split).
///
/// Lazy on purpose: only the chunk being filled (plus one carried item) is
/// ever materialized, so a #330-sized backlog does not hold every serialized
/// row in memory at once.
fn fill_chunk<T>(
    src: &mut impl Iterator<Item = (T, usize)>,
    carry: &mut Option<(T, usize)>,
) -> Vec<T> {
    let mut out = Vec::new();
    let mut bytes = 2usize; // the `[` and `]`
    while let Some((item, size)) = carry.take().or_else(|| src.next()) {
        let add = size + 1; // the row and its comma
        if !out.is_empty() && (out.len() >= MAX_FLUSH_BATCH || bytes + add > MAX_FLUSH_BYTES) {
            *carry = Some((item, size));
            break;
        }
        bytes += add;
        out.push(item);
    }
    out
}

/// The hub's body limit, and the reason `MAX_FLUSH_BATCH` is what it is.
/// Measured against the staging hub: 1 MiB is accepted, 2 MiB returns 413.
/// Settlement liveness: the signal that was missing when #341 happened.
/// The hub has this row: its WAL entry, if it has one, is no longer owed.
///
/// Every row a broker owes the hub -- an owner's `earn-` credit, a requester's
/// `commit` debit, a batch's settlement -- keeps a replayable WAL entry until
/// the flush that delivers it. Retiring an entry any earlier (in memory, at
/// commit time) is what lets a killed broker lose a debit it already
/// charged. Rows with no WAL entry are a no-op: `update_status` reports the
/// missing id and that is ignored.
fn retire_delivered(wal: &Wal, tx: &BufferedTransaction) {
    let _ = wal.update_status(
        &tx.request_id,
        WalStatus::Committed,
        Some(tx.amount),
        Some(tx.duration_ms),
    );
}

#[cfg(test)]
mod settlement_liveness_tests {
    use super::*;

    #[test]
    fn a_fresh_buffer_is_not_already_stale() {
        // Starting at 0 would make every broker look wedged for 56 years on
        // boot, and an alert that is always firing is an alert nobody reads.
        let buf = TransactionBuffer::new();
        assert!(buf.seconds_since_flush() < 5);
    }

    #[test]
    fn an_idle_broker_still_proves_the_flush_path_runs() {
        // The stamp is taken BEFORE the empty-buffer early return. Without
        // that, "nothing to send" and "the thread that sends is wedged" are
        // the same reading, which is exactly how #341 hid for eight hours.
        let buf = TransactionBuffer::new();
        let path = std::env::temp_dir().join(format!(
            "zc-liveness-{}.wal",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let _ = std::fs::remove_file(&path);
        let wal = Wal::open(&path).expect("open test WAL");
        buf.last_flush_at.store(0, Ordering::Relaxed);
        assert!(buf.seconds_since_flush() > 1000, "fixture must look stale");

        assert_eq!(buf.pending_count(), 0);
        buf.flush_to_api("http://127.0.0.1:1", "k", &wal);

        assert!(
            buf.seconds_since_flush() < 5,
            "an empty flush must still stamp liveness"
        );
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn pending_work_is_visible_before_it_is_ever_quarantined() {
        // `total_quarantined` only moves once a transaction has been GIVEN UP
        // on. A broker that never tries never quarantines anything, so
        // pending depth is the only thing that shows the backlog.
        let buf = TransactionBuffer::new();
        buf.push_transaction(BufferedTransaction {
            request_id: "r1".into(),
            user_id: "u1".into(),
            tx_type: "commit".into(),
            amount: 0.003,
            balance_after: 1.0,
            worker_id: "w1".into(),
            duration_ms: 1.0,
            source_node: None,
            worker_name: None,
            worker_uri: None,
            price_per_hour: 0.0,
            voucher_nonce: None,
        });
        assert_eq!(buf.pending_count(), 1);
        assert_eq!(buf.total_quarantined(), 0, "nothing failed — nothing ran");
    }

    #[test]
    fn metadata_for_a_transaction_that_was_never_queued_is_not_kept() {
        let buf = TransactionBuffer::new();
        buf.attach_metadata("never-queued", serde_json::json!({"tasks": []}));
        assert!(buf.metadata.is_empty());
        buf.push_transaction(BufferedTransaction {
            request_id: "r1".into(),
            user_id: "u1".into(),
            tx_type: "commit".into(),
            amount: 0.003,
            balance_after: 1.0,
            worker_id: "w1".into(),
            duration_ms: 1.0,
            source_node: None,
            worker_name: None,
            worker_uri: None,
            price_per_hour: 0.0,
            voucher_nonce: None,
        });
        buf.attach_metadata("r1", serde_json::json!({"tasks": []}));
        assert_eq!(buf.metadata.len(), 1);
    }
}

#[cfg(test)]
const HUB_MAX_BODY_BYTES: usize = 1024 * 1024;

/// A buffered transaction waiting to be flushed to the dashboard API.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BufferedTransaction {
    pub request_id: String,
    pub user_id: String,
    pub tx_type: String,
    pub amount: f64,
    pub balance_after: f64,
    pub worker_id: String,
    pub duration_ms: f64,
    /// Name of the broker node that processed this transaction (executor origin)
    pub source_node: Option<String>,
    /// Name of the worker that executed the job (executor destination)
    pub worker_name: Option<String>,
    /// Worker URI / address (destination endpoint)
    pub worker_uri: Option<String>,
    /// Worker price in credits per hour (zkcr/hr)
    pub price_per_hour: f64,
    /// Hub voucher `task_nonce` when the job was voucher-backed; sent on the
    /// `batch-sync` row (zc#400). `None` (and omitted) otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub voucher_nonce: Option<String>,
}

/// Accumulates completed transactions and balance snapshots for periodic API flush.
pub struct TransactionBuffer {
    /// Pending transactions keyed by request_id.
    pending: DashMap<String, BufferedTransaction>,
    /// Authoritative balance snapshots keyed by user_id (latest value wins).
    balance_snapshots: DashMap<String, f64>,
    /// Count of transactions flushed since start.
    total_flushed: AtomicU64,
    /// Count of transactions PERMANENTLY given up on since start. A broker
    /// whose settlement is failing looks identical to an idle one from the
    /// outside — `zc agent status`, `/health` and `zc bench` all read normal
    /// while nothing settles — so this is surfaced on `/health` (#330).
    total_quarantined: AtomicU64,
    /// Unix seconds when the flush path last RAN — not when it last had
    /// something to send. Quarantine counts the transactions a broker gave up
    /// on; this counts the case where it never tried, which is what #341 was:
    /// the flush shared a thread with blocking hub calls, one of them wedged
    /// for eight hours, and every transaction after that was charged to
    /// clients and buffered forever. `total_quarantined` stayed 0 the whole
    /// time, because nothing ever failed — nothing ever ran.
    last_flush_at: AtomicU64,
    /// Failed-flush attempt count per request_id. Kept alongside `pending`
    /// (not inside `BufferedTransaction`) so re-inserting a transaction on
    /// failure doesn't require touching every construction site. Survives
    /// re-insertion because it's keyed by `request_id`, not by the queue
    /// slot; cleared once a transaction is quarantined or durably flushed.
    attempts: DashMap<String, u32>,
    /// Real-job evidence per request_id (`sched::bill::trust_metadata`), sent as
    /// the row's `metadata`. A side map for the same reason as `attempts`.
    metadata: DashMap<String, serde_json::Value>,
    /// Set once the anonymous-sentinel skip has been logged, so a busy local
    /// broker logs it at most once per process instead of once per call.
    anonymous_warned: AtomicBool,
}

/// Internal `tx_type` → the dashboard's `transaction_type`. `credit` is how a
/// provider's peer earnings (`earn-{request_id}`) are booked, and the hub's
/// earnings query relies on it landing as `credit_purchase`.
pub(crate) fn dashboard_type(tx_type: &str) -> &str {
    match tx_type {
        "commit" | "cancel" => "job_execution",
        "credit" => "credit_purchase",
        other => other,
    }
}

/// Human-readable job name for a transaction, as sent to the dashboard and
/// as logged when a transaction is quarantined. Shared so the two stay in
/// sync (a quarantine log line matching the name the hub actually saw).
fn job_name_for(tx: &BufferedTransaction) -> String {
    match tx.tx_type.as_str() {
        "cancel" => format!(
            "Cancelled Job ({})",
            tx.worker_name.as_deref().unwrap_or(&tx.worker_id)
        ),
        _ => format!(
            "Compute Job ({})",
            tx.worker_name.as_deref().unwrap_or(&tx.worker_id)
        ),
    }
}

/// Summarize the hub's `errors[]` array (each entry keyed by job_name, not
/// request_id — see the call site) into one string suitable for every
/// per-item "failed" transaction quarantined from the same response.
fn summarize_item_errors(errors: &serde_json::Value) -> String {
    match errors.as_array() {
        Some(errors) if !errors.is_empty() => {
            let joined: Vec<String> = errors
                .iter()
                .take(3)
                .map(|e| {
                    format!(
                        "{}: {}",
                        e["job_name"].as_str().unwrap_or("?"),
                        e["error"].as_str().unwrap_or("unknown")
                    )
                })
                .collect();
            let mut summary = format!(
                "hub reported {} item failure(s): {}",
                errors.len(),
                joined.join("; ")
            );
            if errors.len() > 3 {
                summary.push_str(&format!(" … and {} more", errors.len() - 3));
            }
            summary
        }
        _ => "hub reported this item as failed (no error detail provided)".to_string(),
    }
}

impl TransactionBuffer {
    pub fn new() -> Self {
        Self {
            pending: DashMap::new(),
            balance_snapshots: DashMap::new(),
            total_flushed: AtomicU64::new(0),
            total_quarantined: AtomicU64::new(0),
            last_flush_at: AtomicU64::new(now_secs()),
            attempts: DashMap::new(),
            metadata: DashMap::new(),
            anonymous_warned: AtomicBool::new(false),
        }
    }

    /// Queue a completed transaction for the next flush.
    ///
    /// The anonymous sentinel (`ANONYMOUS_USER`) is refused here: the hub
    /// rejects it unconditionally, local execution has nothing to settle,
    /// and buffering it would just occupy a slot the batch would have to
    /// fail (or quarantine) on every flush. This is the single choke point —
    /// callers don't need to check the sentinel themselves.
    pub fn push_transaction(&self, tx: BufferedTransaction) {
        if tx.user_id == ANONYMOUS_USER {
            if !self.anonymous_warned.swap(true, Ordering::Relaxed) {
                eprintln!(
                    "  [FLUSH] Skipping hub sync for anonymous-user transaction {} \
                     (local execution; nothing to settle)",
                    tx.request_id
                );
            }
            return;
        }
        self.pending.insert(tx.request_id.clone(), tx);
    }

    /// Attach `metadata` to the PENDING transaction with this request_id; it is
    /// sent with the row and dropped once the row is delivered or quarantined.
    /// A no-op when no such transaction is queued (free batch, billing off, no
    /// task ran), so an entry can never outlive a row that will never flush.
    pub fn attach_metadata(&self, request_id: &str, metadata: serde_json::Value) {
        if self.pending.contains_key(request_id) {
            self.metadata.insert(request_id.to_string(), metadata);
        }
    }

    /// Record an authoritative balance snapshot for a user.
    pub fn snapshot_balance(&self, user_id: &str, balance: f64) {
        self.balance_snapshots.insert(user_id.to_string(), balance);
    }

    /// Number of pending transactions.
    pub fn pending_count(&self) -> usize {
        self.pending.len()
    }

    /// Total transactions flushed since start.
    pub fn total_flushed(&self) -> u64 {
        self.total_flushed.load(Ordering::Relaxed)
    }

    /// Transactions permanently given up on since start. Non-zero means money
    /// that was owed was never recorded, and nothing else says so.
    /// Seconds since the flush path last ran. Large and growing on a broker
    /// that is still answering `/execute` means it is charging for work it is
    /// not delivering.
    pub fn seconds_since_flush(&self) -> u64 {
        now_secs().saturating_sub(self.last_flush_at.load(Ordering::Relaxed))
    }

    pub fn total_quarantined(&self) -> u64 {
        self.total_quarantined.load(Ordering::Relaxed)
    }

    /// Pending transactions, cloned. Test-only: pins what `flush_to_api` will send.
    #[cfg(test)]
    pub(crate) fn pending_snapshot(&self) -> Vec<BufferedTransaction> {
        self.pending.iter().map(|e| e.value().clone()).collect()
    }

    /// Drain all pending items, returning them.
    fn drain(&self) -> (Vec<BufferedTransaction>, Vec<(String, f64)>) {
        // Drain transactions
        let mut txs = Vec::with_capacity(self.pending.len());
        let keys: Vec<String> = self.pending.iter().map(|e| e.key().clone()).collect();
        for key in keys {
            if let Some((_, tx)) = self.pending.remove(&key) {
                txs.push(tx);
            }
        }

        // Drain balance snapshots
        let mut balances = Vec::with_capacity(self.balance_snapshots.len());
        let bkeys: Vec<String> = self
            .balance_snapshots
            .iter()
            .map(|e| e.key().clone())
            .collect();
        for key in bkeys {
            if let Some((uid, bal)) = self.balance_snapshots.remove(&key) {
                balances.push((uid, bal));
            }
        }

        (txs, balances)
    }

    /// Sibling path of the WAL used for permanently-rejected transactions:
    /// same directory resolution as the WAL itself (`~/.zakuro/wal.jsonl` →
    /// `~/.zakuro/wal-rejected.jsonl`), so no separate config/env is needed.
    fn rejected_path(wal: &Wal) -> std::path::PathBuf {
        let wal_path = wal.path();
        let stem = wal_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("wal");
        let ext = wal_path
            .extension()
            .and_then(|s| s.to_str())
            .unwrap_or("jsonl");
        wal_path.with_file_name(format!("{stem}-rejected.{ext}"))
    }

    /// Largest a quarantine file may get before it is rotated.
    ///
    /// The file had no bound at all and reached 475 MB on one Mac — a single
    /// error repeated, written one line per permanently-failed transaction
    /// (#330). A broker is often a node someone is sharing, and filling its
    /// disk takes the whole node down, not just billing.
    const MAX_QUARANTINE_BYTES: u64 = 64 * 1024 * 1024;

    /// Rotate `wal-rejected.jsonl` to `.1` once it passes
    /// [`Self::MAX_QUARANTINE_BYTES`], keeping exactly one previous
    /// generation. Two files bound the space at 128 MB, and the newest
    /// failures — the ones worth reading — are always the ones kept.
    ///
    /// Best-effort throughout: quarantining must not fail because rotation
    /// did, so every error here is swallowed and the append proceeds.
    fn rotate_quarantine_if_full(path: &std::path::Path) {
        let too_big = std::fs::metadata(path)
            .map(|m| m.len() >= Self::MAX_QUARANTINE_BYTES)
            .unwrap_or(false);
        if !too_big {
            return;
        }
        let rotated = path.with_extension(match path.extension().and_then(|e| e.to_str()) {
            Some(ext) => format!("{ext}.1"),
            None => "1".to_string(),
        });
        if std::fs::rename(path, &rotated).is_ok() {
            eprintln!(
                "  [FLUSH] Quarantine file passed {} MB; rotated to {}",
                Self::MAX_QUARANTINE_BYTES / (1024 * 1024),
                rotated.display()
            );
        }
    }

    /// Append one permanently-rejected transaction to `wal-rejected.jsonl`
    /// and log a single line naming its request id, job name and error.
    /// Never panics and never drops the transaction silently: a write
    /// failure is logged, but the transaction is still gone from `pending`
    /// (matching the "never re-insert a quarantined item" requirement) —
    /// the alternative of re-queuing it would put it right back where it
    /// started (the whole point of quarantining is to stop that loop).
    fn quarantine(&self, tx: &BufferedTransaction, wal: &Wal, error: &str) {
        self.total_quarantined.fetch_add(1, Ordering::Relaxed);
        let job_name = job_name_for(tx);
        let path = Self::rejected_path(wal);
        let line = serde_json::json!({
            "request_id": tx.request_id,
            "user_id": tx.user_id,
            "job_name": job_name,
            "tx_type": tx.tx_type,
            "amount": tx.amount,
            "worker_id": tx.worker_id,
            "error": error,
            "quarantined_at": chrono::Utc::now().to_rfc3339(),
        });

        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        Self::rotate_quarantine_if_full(&path);
        let write_result = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&path)
            .and_then(|mut f| writeln!(f, "{}", line));
        if let Err(e) = write_result {
            eprintln!(
                "  [FLUSH] Failed to write quarantine file {}: {}",
                path.display(),
                e
            );
        }

        eprintln!(
            "  [FLUSH] Quarantined {} (job \"{}\"): {}",
            tx.request_id, job_name, error
        );
    }

    /// Record one failed flush attempt for a whole-request-level failure
    /// (transport error or non-200 response). Re-queues the transaction for
    /// the next flush unless it has now failed `MAX_FLUSH_ATTEMPTS` times, in
    /// which case it is quarantined instead so it stops blocking everything
    /// queued behind it.
    fn record_failure(&self, tx: BufferedTransaction, wal: &Wal, error: &str) {
        let attempts = {
            let mut entry = self.attempts.entry(tx.request_id.clone()).or_insert(0);
            *entry += 1;
            *entry
        };
        if attempts >= MAX_FLUSH_ATTEMPTS {
            self.attempts.remove(&tx.request_id);
            self.metadata.remove(&tx.request_id);
            self.quarantine(&tx, wal, error);
        } else {
            self.pending.insert(tx.request_id.clone(), tx);
        }
    }

    /// Clear any attempt count for a transaction that has now durably
    /// reached the hub, so a stray counter can't outlive its transaction.
    fn record_success(&self, request_id: &str) {
        self.attempts.remove(request_id);
        self.metadata.remove(request_id);
    }

    /// Flush all pending transactions to production dashboard via API.
    /// Returns the number of transactions flushed.
    ///
    /// `wal` is used to mark WAL-backed entries (currently: peer-earn credits,
    /// keyed `earn-{request_id}`) `Committed` once the batch has been durably
    /// delivered to the dashboard. This is the ONLY place earn WAL entries are
    /// marked Committed — until this succeeds they stay `Earned` (replay-eligible),
    /// so a crash before this point re-delivers the earn on restart, and a crash
    /// after it does not (the dashboard already has it, and dedups by
    /// request_id, so even a racing double-delivery is a harmless no-op).
    pub fn flush_to_api(&self, api_url: &str, api_key: &str, wal: &Wal) -> usize {
        // Stamped before the early return: an idle broker with nothing to send
        // must still show the path as alive, or "no transactions" and "not
        // flushing" would look identical from `/health`.
        self.last_flush_at.store(now_secs(), Ordering::Relaxed);
        let (txs, _balances) = self.drain();

        if txs.is_empty() {
            return 0;
        }

        // One POST per `MAX_FLUSH_BATCH`, never one POST for the whole buffer.
        // A chunk that fails is re-queued or quarantined on its own, so a
        // backlog can drain instead of failing whole and taking every
        // transaction behind it down with it (#330).
        // Chunked by serialized bytes as well as count (see `MAX_FLUSH_BYTES`),
        // building each row only when its chunk is filled and dropping the
        // chunk's rows once it is sent.
        let mut src = txs.into_iter().map(|tx| {
            let row = self.batch_row(&tx);
            let size = serde_json::to_string(&row).map_or(0, |s| s.len());
            ((tx, row), size)
        });
        let mut carry = None;
        let mut sent = 0;
        loop {
            let chunk = fill_chunk(&mut src, &mut carry);
            if chunk.is_empty() {
                break;
            }
            let (txs, rows): (Vec<_>, Vec<_>) = chunk.into_iter().unzip();
            sent += self.flush_chunk(api_url, api_key, wal, txs, rows);
        }
        sent
    }

    /// One transaction as a `batch-sync` row.
    fn batch_row(&self, tx: &BufferedTransaction) -> serde_json::Value {
        // Map internal tx_type to dashboard transaction_type
        let dashboard_type = dashboard_type(tx.tx_type.as_str());
        let job_name = job_name_for(tx);
        let (credits_amount, status) = match tx.tx_type.as_str() {
            "cancel" => (0.0f64, "failed"),
            _ => (tx.amount, "completed"),
        };
        let mut row = serde_json::json!({
            "request_id": tx.request_id,
            "zakuro_user_id": tx.user_id,
            "job_name": job_name,
            "transaction_type": dashboard_type,
            "credits_amount": credits_amount,
            "status": status,
            "duration_ms": if tx.duration_ms > 0.0 { serde_json::Value::Number(serde_json::Number::from_f64(tx.duration_ms).unwrap()) } else { serde_json::Value::Null },
            "worker_id": tx.worker_name,
            "source_node": tx.source_node,
            "compute_hours": if tx.duration_ms > 0.0 { Some(tx.duration_ms / 3_600_000.0) } else { None::<f64> },
            "executor": tx.worker_name,
            "destination": tx.worker_uri,
            "price_per_hour": if tx.price_per_hour > 0.0 { Some(tx.price_per_hour) } else { None::<f64> },
            "metadata": self.metadata.get(&tx.request_id).map(|m| m.value().clone())
        });
        super::ledger::attach_voucher_nonce(&mut row, tx.voucher_nonce.as_deref());
        row
    }

    /// Flush one bounded chunk. See [`MAX_FLUSH_BATCH`] and [`MAX_FLUSH_BYTES`]
    /// for why it is bounded. `payload[i]` is the row for `txs[i]`.
    fn flush_chunk(
        &self,
        api_url: &str,
        api_key: &str,
        wal: &Wal,
        txs: Vec<BufferedTransaction>,
        payload: Vec<serde_json::Value>,
    ) -> usize {
        let tx_count = txs.len();

        let endpoint = format!("{}/api/broker/batch-sync", api_url.trim_end_matches('/'));

        let payload_str = match serde_json::to_string(&payload) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("  [FLUSH] Failed to serialize payload: {}", e);
                // Return transactions to buffer on failure
                for tx in txs {
                    self.pending.insert(tx.request_id.clone(), tx);
                }
                return 0;
            }
        };

        match ureq::post(&endpoint)
            .config()
            .http_status_as_error(false)
            .build()
            .header("X-Broker-Api-Key", api_key)
            .header("Content-Type", "application/json")
            .send(payload_str.as_str())
        {
            Ok(resp) if resp.status().as_u16() == 200 => {
                let body = resp.into_body().read_to_string().unwrap_or_default();
                let parsed: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
                let inserted = parsed["inserted"].as_u64().unwrap_or(tx_count as u64);
                let failed = parsed["failed"].as_u64().unwrap_or(0);
                let success = parsed["success"].as_bool().unwrap_or(true);

                self.total_flushed.fetch_add(inserted, Ordering::Relaxed);

                // Honor per-item results when the dashboard provides them
                // (batch-sync isolates each item and reports applied/duplicate/
                // failed per request_id). Fall back to whole-batch-on-200
                // behavior only for older dashboards that omit `results[]`.
                match parsed["results"].as_array() {
                    Some(results) => {
                        // Build request_id → status map. Items with a null/absent
                        // request_id can't be matched to an earn WAL entry (and
                        // aren't earns), so they're irrelevant to WAL marking.
                        let mut item_status: std::collections::HashMap<&str, &str> =
                            std::collections::HashMap::new();
                        for r in results {
                            if let (Some(rid), Some(st)) =
                                (r["request_id"].as_str(), r["status"].as_str())
                            {
                                item_status.insert(rid, st);
                            }
                        }

                        // `results[]` keys per-item status by request_id, which is
                        // reliable. The hub's `errors[]` array, on the other hand,
                        // keys per-item detail by job_name — and job names are not
                        // unique (two concurrent jobs on the same worker share one),
                        // so an error entry can't be reliably matched back to a
                        // single failed request_id. Rather than guess that mapping,
                        // every item reported "failed" here carries the same
                        // aggregate summary of everything the hub reported.
                        let item_error_summary = summarize_item_errors(&parsed["errors"]);

                        for tx in &txs {
                            // Default to "applied" when the dashboard returned
                            // results but didn't mention this request_id (e.g.
                            // null request_id on a non-earn tx): it's not a
                            // reported failure, so treat as durable and drop.
                            let status = item_status
                                .get(tx.request_id.as_str())
                                .copied()
                                .unwrap_or("applied");
                            match status {
                                "failed" => {
                                    // batch-sync dedups by request_id (it checks
                                    // for an existing row before inserting), and
                                    // zc already sends request_id in the payload,
                                    // so retrying a per-item failure can't
                                    // double-book a balance. A per-row failure
                                    // can also be transient (e.g. a database
                                    // hiccup on the hub's side), so it gets the
                                    // same attempt-counted grace as a
                                    // whole-request failure rather than being
                                    // quarantined on the spot.
                                    self.record_failure(tx.clone(), wal, &item_error_summary);
                                }
                                // "applied" | "duplicate" | anything else durable
                                _ => {
                                    self.record_success(&tx.request_id);
                                    retire_delivered(wal, tx);
                                }
                            }
                        }
                    }
                    None => {
                        // Back-compat: older dashboard without per-item results.
                        // HTTP 200 → treat the whole batch as durable and mark
                        // every earn WAL entry Committed.
                        for tx in &txs {
                            self.record_success(&tx.request_id);
                            retire_delivered(wal, tx);
                        }
                    }
                }

                if !success || failed > 0 {
                    eprintln!(
                        "  [FLUSH] Partial sync to {}: {} inserted, {} failed",
                        api_url, inserted, failed
                    );
                    if let Some(errors) = parsed["errors"].as_array() {
                        for e in errors.iter().take(3) {
                            eprintln!(
                                "  [FLUSH]   → {}: {}",
                                e["job_name"].as_str().unwrap_or("?"),
                                e["error"].as_str().unwrap_or("unknown")
                            );
                        }
                        if errors.len() > 3 {
                            eprintln!("  [FLUSH]   … and {} more errors", errors.len() - 3);
                        }
                    }
                } else {
                    println!(
                        "  [FLUSH] Synced {} transactions to {} via API",
                        inserted, api_url
                    );
                }
                inserted as usize
            }
            Ok(resp) => {
                let status = resp.status();
                eprintln!("  [FLUSH] API sync failed: status {}", status);
                let error = format!("status {}", status);
                // Requeue each transaction unless it has now hit
                // MAX_FLUSH_ATTEMPTS, in which case it's quarantined instead
                // of blocking everything else in the batch forever.
                for tx in txs {
                    self.record_failure(tx, wal, &error);
                }
                0
            }
            Err(e) => {
                eprintln!("  [FLUSH] API sync failed: {}", e);
                let error = e.to_string();
                // A transport error counts as a failed attempt too.
                for tx in txs {
                    self.record_failure(tx, wal, &error);
                }
                0
            }
        }
    }
}

impl std::fmt::Debug for TransactionBuffer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TransactionBuffer")
            .field("pending", &self.pending.len())
            .field("balance_snapshots", &self.balance_snapshots.len())
            .field("total_flushed", &self.total_flushed())
            .finish()
    }
}

/// The hub's earnings query depends on `flush_to_api` actually sending
/// `credit` transactions as `transaction_type: "credit_purchase"` in the
/// batch-sync payload — not just on `dashboard_type` returning the right
/// string in isolation (pinned separately in
/// `server::earn_prefix_contract_tests::dashboard_types_are_stable`).
/// The size contract behind `MAX_FLUSH_BATCH` (#330).
#[cfg(test)]
mod flush_batch_size_tests {
    use super::*;

    /// A transaction with every optional field populated and generously long,
    /// so the guard measures a worst case rather than an empty struct.
    fn fat_tx(i: usize) -> BufferedTransaction {
        BufferedTransaction {
            request_id: format!("earn-{}-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", i),
            user_id: "5492316032".into(),
            tx_type: "credit".into(),
            amount: 0.012112875187777778,
            balance_after: 19998.863504120014,
            worker_id: "a59edb75-a8e0-4822-a344-bbffcd791718".into(),
            duration_ms: 2340.5812345,
            source_node: Some("zc://node-6188100f5daf463e".into()),
            worker_name: Some("worker-zc-worker-cloudcompute-larger-name-1".into()),
            worker_uri: Some("http://10.13.13.20:3960/execute".into()),
            price_per_hour: 3.6,
            voucher_nonce: None,
        }
    }

    /// One full batch must fit well inside the body the hub will accept.
    ///
    /// The hub refuses over ~1 MiB with 413, and refusing mid-upload is what
    /// the broker reported as `io: Broken pipe`. This is the guard that keeps
    /// a raised `MAX_FLUSH_BATCH` from quietly reintroducing that.
    #[test]
    fn a_full_batch_stays_under_the_hub_body_limit() {
        let txs: Vec<_> = (0..MAX_FLUSH_BATCH).map(fat_tx).collect();
        let payload: Vec<serde_json::Value> = txs
            .iter()
            .map(|tx| {
                serde_json::json!({
                    "request_id": tx.request_id,
                    "zakuro_user_id": tx.user_id,
                    "job_name": job_name_for(tx),
                    "transaction_type": dashboard_type(tx.tx_type.as_str()),
                    "credits_amount": tx.amount,
                    "status": "completed",
                    "duration_ms": tx.duration_ms,
                    "worker_id": tx.worker_name,
                    "source_node": tx.source_node,
                    "compute_hours": tx.duration_ms / 3_600_000.0,
                    "executor": tx.worker_name,
                    "destination": tx.worker_uri,
                    "price_per_hour": tx.price_per_hour,
                    "metadata": null
                })
            })
            .collect();
        let bytes = serde_json::to_string(&payload).expect("serializes").len();
        assert!(
            bytes < HUB_MAX_BODY_BYTES / 2,
            "a full batch is {bytes} bytes; the hub 413s over {HUB_MAX_BODY_BYTES} \
             and the broker sees that as a broken pipe (#330)"
        );
    }

    /// 500 batch-earn rows, each with the most trust metadata a batch can carry:
    /// every POST body stays under half the hub limit, and no row is lost.
    #[test]
    fn chunks_of_metadata_rows_stay_under_the_byte_cap() {
        for samples in [crate::sched::bill::MAX_TRUST_SAMPLES, 200] {
            let buf = TransactionBuffer::new();
            let payloads: Vec<Vec<u8>> = (0..samples as u32)
                .map(|i| i.to_le_bytes().to_vec())
                .collect();
            for i in 0..MAX_FLUSH_BATCH {
                let tx = fat_tx(i);
                let rid = tx.request_id.clone();
                buf.push_transaction(tx);
                buf.attach_metadata(
                    &rid,
                    crate::sched::bill::trust_metadata(
                        payloads.iter().map(|p| (p.as_slice(), 123456.0)),
                    ),
                );
            }
            let mut src = buf.pending_snapshot().into_iter().map(|t| {
                let row = buf.batch_row(&t);
                let size = serde_json::to_string(&row).unwrap().len();
                (row, size)
            });
            let mut carry = None;
            let (mut n_chunks, mut covered) = (0, 0);
            loop {
                let chunk = fill_chunk(&mut src, &mut carry);
                if chunk.is_empty() {
                    break;
                }
                n_chunks += 1;
                covered += chunk.len();
                let body = serde_json::to_string(&chunk).unwrap().len();
                assert!(
                    body <= MAX_FLUSH_BYTES && chunk.len() <= MAX_FLUSH_BATCH,
                    "{samples} samples: a chunk body is {body} bytes / {} rows",
                    chunk.len()
                );
            }
            assert!(n_chunks > 1, "{samples} samples: must split by bytes");
            assert_eq!(covered, MAX_FLUSH_BATCH, "every row lands in a chunk");
        }
    }

    /// Drive `fill_chunk` over sizes; returns each chunk's item indices.
    fn chunk_all(sizes: &[usize]) -> Vec<Vec<usize>> {
        let mut src = sizes.iter().copied().enumerate();
        let mut carry = None;
        let mut out = Vec::new();
        loop {
            let c = fill_chunk(&mut src, &mut carry);
            if c.is_empty() {
                return out;
            }
            out.push(c);
        }
    }

    #[test]
    fn chunking_edges() {
        assert!(chunk_all(&[]).is_empty());
        assert_eq!(chunk_all(&[10, 10]), vec![vec![0, 1]]);
        // An oversized row travels alone rather than being dropped or looping.
        let big = MAX_FLUSH_BYTES * 2;
        assert_eq!(chunk_all(&[10, big, 10]), vec![vec![0], vec![1], vec![2]]);
        // The count cap still applies to tiny rows.
        assert_eq!(chunk_all(&vec![1; MAX_FLUSH_BATCH + 1]).len(), 2);
    }

    /// A huge backlog is never materialized up front: while a chunk is
    /// filled the source has been pulled at most one item past it.
    #[test]
    fn at_most_one_chunk_of_rows_is_alive_at_a_time() {
        let pulled = std::cell::Cell::new(0usize);
        let mut src = (0..50_000usize).map(|i| {
            pulled.set(pulled.get() + 1);
            (i, 4_000) // ~128 rows per 512 KiB chunk
        });
        let mut carry = None;
        let mut emitted = 0;
        let mut chunks = 0;
        loop {
            let chunk = fill_chunk(&mut src, &mut carry);
            if chunk.is_empty() {
                break;
            }
            emitted += chunk.len();
            chunks += 1;
            assert!(chunk.len() < MAX_FLUSH_BATCH);
            assert!(
                pulled.get() <= emitted + 1,
                "pulled {} rows but only {emitted} are in sent chunks",
                pulled.get()
            );
        }
        assert_eq!(emitted, 50_000);
        assert!(chunks > 300);
    }

    /// The quarantine file is bounded: it reached 475 MB unbounded (#330), and
    /// filling a shared node's disk takes the node down, not just billing.
    #[test]
    fn a_full_quarantine_file_is_rotated_not_grown_forever() {
        let dir = std::env::temp_dir().join(format!("zc-quarantine-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("tmpdir");
        let path = dir.join("wal-rejected.jsonl");

        // Under the cap: left alone.
        std::fs::write(&path, b"small\n").expect("write");
        TransactionBuffer::rotate_quarantine_if_full(&path);
        assert!(path.exists(), "a small file is not rotated");
        assert!(
            !dir.join("wal-rejected.jsonl.1").exists(),
            "nothing rotated yet"
        );

        // Over the cap: moved aside, and a fresh file starts empty.
        let big = vec![b'x'; TransactionBuffer::MAX_QUARANTINE_BYTES as usize + 1];
        std::fs::write(&path, &big).expect("write big");
        TransactionBuffer::rotate_quarantine_if_full(&path);
        assert!(!path.exists(), "the full file was moved aside");
        let rotated = dir.join("wal-rejected.jsonl.1");
        assert!(rotated.exists(), "one previous generation is kept");
        assert_eq!(
            std::fs::metadata(&rotated).expect("rotated").len(),
            big.len() as u64,
            "the rotated file keeps its contents"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The whole point: a backlog is split, never sent as one request.
    #[test]
    fn a_backlog_is_split_into_bounded_requests() {
        let backlog = 274_461; // what one Mac actually accumulated
        let chunks = (0..backlog)
            .collect::<Vec<_>>()
            .chunks(MAX_FLUSH_BATCH)
            .len();
        assert!(chunks > 1, "a backlog must not be one request");
        assert!(
            chunks * MAX_FLUSH_BATCH >= backlog,
            "every transaction must land in some chunk"
        );
    }
}

#[cfg(test)]
mod earn_credit_purchase_payload_tests {
    use super::*;

    /// A hub that captures the batch-sync request body and replies success.
    /// Built on the shared `bind_loopback_http` rather than a new hand-rolled
    /// `tiny_http` server, the same pattern as
    /// `server::billing_price_pin_tests::mock_sync_hub`.
    fn capturing_hub() -> (String, std::sync::mpsc::Receiver<String>) {
        let (server, port) = crate::integration_tests::integration::bind_loopback_http();
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            for mut req in server.incoming_requests() {
                let mut body = String::new();
                let _ = std::io::Read::read_to_string(req.as_reader(), &mut body);
                let _ = tx.send(body);
                let _ = req.respond(tiny_http::Response::from_string(
                    r#"{"success":true,"inserted":1,"failed":0}"#,
                ));
            }
        });
        (format!("http://127.0.0.1:{port}"), rx)
    }

    #[test]
    fn flush_sends_a_credit_transaction_as_credit_purchase() {
        let path = format!(
            "/tmp/zc_test_flush_dashboard_type_{}_{}.jsonl",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let _ = std::fs::remove_file(&path);
        let wal = Wal::open(&path).expect("open test WAL");

        let buf = TransactionBuffer::new();
        buf.push_transaction(BufferedTransaction {
            request_id: "earn-r1".to_string(),
            user_id: "owner".to_string(),
            tx_type: "credit".to_string(),
            amount: 1.5,
            balance_after: 1.5,
            worker_id: "w0".to_string(),
            duration_ms: 10.0,
            source_node: None,
            worker_name: Some("w0".to_string()),
            worker_uri: None,
            price_per_hour: 0.0,
            voucher_nonce: None,
        });

        let (hub, bodies) = capturing_hub();
        assert_eq!(buf.flush_to_api(&hub, "key", &wal), 1);

        let sent: serde_json::Value = serde_json::from_str(&bodies.recv().unwrap()).unwrap();
        assert_eq!(
            sent[0]["request_id"], "earn-r1",
            "the earn row must be the one sent"
        );
        assert_eq!(
            sent[0]["transaction_type"], "credit_purchase",
            "a `credit` tx must be sent to the hub as `credit_purchase`, or the \
             earnings summary silently drops it"
        );

        let _ = std::fs::remove_file(&path);
    }
}

/// Fault 1 (whole-request failure retried forever) and Fault 2 (per-item
/// rejections silently dropped) and Fault 3 (buffering the anonymous
/// sentinel) all quarantine/skip via this module's helpers, on the same
/// `bind_loopback_http` fake-hub pattern as `earn_credit_purchase_payload_tests`.
#[cfg(test)]
mod quarantine_tests {
    use super::*;

    fn test_wal(name: &str) -> (std::path::PathBuf, Wal) {
        let path = std::path::PathBuf::from(format!(
            "/tmp/zc_test_flush_quarantine_{}_{}_{}.jsonl",
            name,
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let _ = std::fs::remove_file(&path);
        let wal = Wal::open(&path).expect("open test WAL");
        (path, wal)
    }

    fn cleanup(wal_path: &std::path::Path, wal: &Wal) {
        let _ = std::fs::remove_file(wal_path);
        let _ = std::fs::remove_file(TransactionBuffer::rejected_path(wal));
    }

    fn tx(request_id: &str, user_id: &str) -> BufferedTransaction {
        BufferedTransaction {
            request_id: request_id.to_string(),
            user_id: user_id.to_string(),
            tx_type: "commit".to_string(),
            amount: 1.0,
            balance_after: 1.0,
            worker_id: "w0".to_string(),
            duration_ms: 10.0,
            source_node: None,
            worker_name: Some("w0".to_string()),
            worker_uri: None,
            price_per_hour: 0.0,
            voucher_nonce: None,
        }
    }

    fn read_rejected_lines(wal: &Wal) -> Vec<serde_json::Value> {
        let path = TransactionBuffer::rejected_path(wal);
        match std::fs::read_to_string(&path) {
            Ok(contents) => contents
                .lines()
                .filter(|l| !l.trim().is_empty())
                .map(|l| serde_json::from_str(l).expect("quarantine line must be valid JSON"))
                .collect(),
            Err(_) => Vec::new(),
        }
    }

    /// A hub that always answers every request with the given HTTP status
    /// (used for the whole-request-failure tests).
    fn hub_always(status: u16) -> String {
        let (server, port) = crate::integration_tests::integration::bind_loopback_http();
        std::thread::spawn(move || {
            for mut req in server.incoming_requests() {
                let mut body = String::new();
                let _ = std::io::Read::read_to_string(req.as_reader(), &mut body);
                let _ = req.respond(tiny_http::Response::from_string("").with_status_code(status));
            }
        });
        format!("http://127.0.0.1:{port}")
    }

    /// A hub reachable at bind time but not actually listening — every send
    /// fails as a transport error (connection refused), not an HTTP status.
    fn dead_hub() -> String {
        let (server, port) = crate::integration_tests::integration::bind_loopback_http();
        drop(server); // closes the listening socket; nothing answers `port`
        format!("http://127.0.0.1:{port}")
    }

    /// A hub that returns `status` for the first `fail_times` requests, then
    /// a plain success for every request after that.
    fn hub_fail_then_succeed(fail_times: usize, status: u16) -> String {
        let (server, port) = crate::integration_tests::integration::bind_loopback_http();
        std::thread::spawn(move || {
            let mut seen = 0usize;
            for mut req in server.incoming_requests() {
                let mut body = String::new();
                let _ = std::io::Read::read_to_string(req.as_reader(), &mut body);
                seen += 1;
                if seen <= fail_times {
                    let _ =
                        req.respond(tiny_http::Response::from_string("").with_status_code(status));
                } else {
                    let _ = req.respond(tiny_http::Response::from_string(
                        r#"{"success":true,"inserted":1,"failed":0}"#,
                    ));
                }
            }
        });
        format!("http://127.0.0.1:{port}")
    }

    /// A hub that answers 200 but reports `bad_rid` failed (via `results[]`
    /// and `errors[]`) on every request, while everything else applies.
    fn hub_with_item_failure(bad_rid: &'static str) -> String {
        hub_with_item_failure_then_succeed(bad_rid, usize::MAX)
    }

    /// A hub that answers 200 and reports `bad_rid` failed (via `results[]`
    /// and `errors[]`) for the first `fail_times` requests, then reports it
    /// (and everything else) applied from then on.
    fn hub_with_item_failure_then_succeed(bad_rid: &'static str, fail_times: usize) -> String {
        let (server, port) = crate::integration_tests::integration::bind_loopback_http();
        std::thread::spawn(move || {
            let mut seen = 0usize;
            for mut req in server.incoming_requests() {
                let mut body = String::new();
                let _ = std::io::Read::read_to_string(req.as_reader(), &mut body);
                seen += 1;
                let bad_still_fails = seen <= fail_times;
                let parsed: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
                let items = parsed.as_array().cloned().unwrap_or_default();
                let results: Vec<serde_json::Value> = items
                    .iter()
                    .map(|item| {
                        let rid = item["request_id"].as_str().unwrap_or("");
                        let status = if rid == bad_rid && bad_still_fails {
                            "failed"
                        } else {
                            "applied"
                        };
                        serde_json::json!({"request_id": rid, "status": status})
                    })
                    .collect();
                let failed = results.iter().filter(|r| r["status"] == "failed").count();
                let inserted = results.len() - failed;
                let resp_body = serde_json::json!({
                    "success": failed == 0,
                    "inserted": inserted,
                    "failed": failed,
                    "results": results,
                    "errors": if failed > 0 {
                        serde_json::json!([{"job_name": "Compute Job (w0)", "error": "User not found: anonymous"}])
                    } else {
                        serde_json::json!([])
                    },
                })
                .to_string();
                let _ = req.respond(tiny_http::Response::from_string(resp_body));
            }
        });
        format!("http://127.0.0.1:{port}")
    }

    fn executed(request_id: &str) -> crate::broker::wal::WalEntry {
        crate::broker::wal::WalEntry {
            request_id: request_id.to_string(),
            user_id: "alice".to_string(),
            reservation_id: format!("res-{request_id}"),
            estimated_cost: 1.0,
            actual_cost: Some(1.0),
            worker_id: "w0".to_string(),
            worker_name: Some("w0".to_string()),
            duration_ms: Some(10.0),
            timestamp: chrono::Utc::now(),
            status: WalStatus::Executed,
            voucher_nonce: None,
        }
    }

    fn still_owed(wal: &Wal, request_id: &str) -> bool {
        wal.read_uncommitted()
            .unwrap()
            .iter()
            .any(|e| e.request_id == request_id)
    }

    /// A requester's debit is owed until the hub has it. Its WAL entry must
    /// stay replayable until the flush that delivers it, and be retired by
    /// that flush -- the same contract `earn-` rows already had. Before this,
    /// only earns were retired here, and `/execute` marked its own entry
    /// Committed the moment it committed in memory, so a broker killed with
    /// the debit still queued lost it while the owner's earn was replayed
    /// (zc-worker-i9-2, 2026-10-02: 0.010565 zkcr).
    #[test]
    fn a_delivered_debit_retires_its_wal_entry() {
        let (path, wal) = test_wal("debit_retired");
        wal.append(&executed("r-debit")).unwrap();
        let buf = TransactionBuffer::new();
        buf.push_transaction(tx("r-debit", "alice"));
        assert!(still_owed(&wal, "r-debit"), "owed until delivered");

        let hub = hub_with_item_failure("nobody");
        assert_eq!(buf.flush_to_api(&hub, "key", &wal), 1);
        assert!(
            !still_owed(&wal, "r-debit"),
            "delivered, so no longer replayed"
        );
        cleanup(&path, &wal);
    }

    /// Same contract against a hub too old to report per-item results.
    #[test]
    fn a_delivered_debit_retires_its_wal_entry_on_an_older_hub() {
        let (path, wal) = test_wal("debit_retired_legacy");
        wal.append(&executed("r-old")).unwrap();
        let buf = TransactionBuffer::new();
        buf.push_transaction(tx("r-old", "alice"));
        let hub = hub_fail_then_succeed(0, 200);
        buf.flush_to_api(&hub, "key", &wal);
        assert!(!still_owed(&wal, "r-old"));
        cleanup(&path, &wal);
    }

    /// A debit the hub rejected is still owed: its entry stays replayable.
    #[test]
    fn a_rejected_debit_stays_owed() {
        let (path, wal) = test_wal("debit_rejected");
        wal.append(&executed("r-bad")).unwrap();
        let buf = TransactionBuffer::new();
        buf.push_transaction(tx("r-bad", "alice"));
        let hub = hub_with_item_failure("r-bad");
        buf.flush_to_api(&hub, "key", &wal);
        assert!(still_owed(&wal, "r-bad"));
        cleanup(&path, &wal);
    }

    /// Test 1: a hub that always 500s never gets a transaction accepted.
    /// After MAX_FLUSH_ATTEMPTS flushes it must be gone from `pending` and
    /// present (exactly once — the quarantine event fires only on the attempt
    /// that crosses the threshold) in the quarantine file.
    #[test]
    fn whole_request_failure_quarantines_after_max_attempts() {
        let (path, wal) = test_wal("always_500");
        let buf = TransactionBuffer::new();
        buf.push_transaction(tx("r-bad", "alice"));

        let hub = hub_always(500);
        for _ in 0..MAX_FLUSH_ATTEMPTS {
            assert_eq!(buf.pending_count(), 1, "not yet quarantined");
            let flushed = buf.flush_to_api(&hub, "key", &wal);
            assert_eq!(flushed, 0);
        }

        assert_eq!(buf.pending_count(), 0, "must be gone from pending");
        let rejected = read_rejected_lines(&wal);
        assert_eq!(
            rejected.len(),
            1,
            "the quarantine event (and its one warning) must fire exactly once, \
             not once per attempt"
        );
        assert_eq!(rejected[0]["request_id"], "r-bad");

        cleanup(&path, &wal);
    }

    /// Test 2: a transaction added after the bad one has been quarantined
    /// must still reach an accepting hub — the earlier failure does not
    /// keep blocking the queue forever.
    #[test]
    fn quarantined_entry_does_not_block_later_transactions() {
        let (path, wal) = test_wal("unblocks_queue");
        let buf = TransactionBuffer::new();
        buf.push_transaction(tx("r-bad", "alice"));

        let bad_hub = hub_always(500);
        for _ in 0..MAX_FLUSH_ATTEMPTS {
            buf.flush_to_api(&bad_hub, "key", &wal);
        }
        assert_eq!(buf.pending_count(), 0, "bad tx quarantined out of pending");

        buf.push_transaction(tx("r-good", "bob"));
        let good_hub_url = {
            let (server, port) = crate::integration_tests::integration::bind_loopback_http();
            std::thread::spawn(move || {
                for mut req in server.incoming_requests() {
                    let mut body = String::new();
                    let _ = std::io::Read::read_to_string(req.as_reader(), &mut body);
                    let _ = req.respond(tiny_http::Response::from_string(
                        r#"{"success":true,"inserted":1,"failed":0}"#,
                    ));
                }
            });
            format!("http://127.0.0.1:{port}")
        };

        let flushed = buf.flush_to_api(&good_hub_url, "key", &wal);
        assert_eq!(flushed, 1, "the later transaction must reach the hub");
        assert_eq!(buf.pending_count(), 0);

        cleanup(&path, &wal);
    }

    /// Test 3: a transport error (nothing listening) counts as a failed
    /// attempt too, and quarantines at the same threshold as an HTTP failure.
    #[test]
    fn transport_error_counts_as_an_attempt_and_quarantines() {
        let (path, wal) = test_wal("transport_error");
        let buf = TransactionBuffer::new();
        buf.push_transaction(tx("r-unreachable", "alice"));

        let hub = dead_hub();
        for _ in 0..MAX_FLUSH_ATTEMPTS {
            buf.flush_to_api(&hub, "key", &wal);
        }

        assert_eq!(buf.pending_count(), 0);
        let rejected = read_rejected_lines(&wal);
        assert_eq!(rejected.len(), 1);
        assert_eq!(rejected[0]["request_id"], "r-unreachable");

        cleanup(&path, &wal);
    }

    /// Test 4: a 200 response with a per-item failure gets the same
    /// attempt-counted grace as a whole-request failure — batch-sync dedups
    /// by request_id, so retrying a per-item rejection can't double-book a
    /// balance, and a per-row failure can be transient (e.g. a database
    /// hiccup on the hub's side). It's requeued (not quarantined) on each of
    /// the first `MAX_FLUSH_ATTEMPTS - 1` flushes, and only quarantined once
    /// it has failed `MAX_FLUSH_ATTEMPTS` times. Other items in the same
    /// batch keep flushing normally throughout.
    #[test]
    fn per_item_rejection_inside_200_gets_the_same_attempt_grace() {
        let (path, wal) = test_wal("per_item");
        let buf = TransactionBuffer::new();
        buf.push_transaction(tx("r-bad-item", "anonymous-ish"));
        buf.push_transaction(tx("r-good-item", "bob"));

        let hub = hub_with_item_failure("r-bad-item");
        for i in 0..MAX_FLUSH_ATTEMPTS {
            let flushed = buf.flush_to_api(&hub, "key", &wal);
            if i == 0 {
                assert_eq!(
                    flushed, 1,
                    "the good item in the same batch must still flush on the first attempt"
                );
            }
        }

        assert_eq!(buf.pending_count(), 0, "must be gone from pending");
        let rejected = read_rejected_lines(&wal);
        assert_eq!(
            rejected.len(),
            1,
            "quarantined exactly once, after MAX_FLUSH_ATTEMPTS, not on the first failure"
        );
        assert_eq!(rejected[0]["request_id"], "r-bad-item");
        assert!(
            rejected[0]["error"]
                .as_str()
                .unwrap_or("")
                .contains("User not found"),
            "the hub's per-item error text must be preserved"
        );

        cleanup(&path, &wal);
    }

    /// Test 4b: a per-item failure that succeeds on a later flush (the
    /// transient case the attempt grace exists for) must never be
    /// quarantined, and must reach the hub once the hub starts applying it.
    #[test]
    fn per_item_rejection_that_later_succeeds_is_not_quarantined() {
        let (path, wal) = test_wal("per_item_transient");
        let buf = TransactionBuffer::new();
        buf.push_transaction(tx("r-transient-item", "bob"));

        let hub = hub_with_item_failure_then_succeed("r-transient-item", 2);
        assert_eq!(buf.flush_to_api(&hub, "key", &wal), 0); // attempt 1: item fails
        assert_eq!(buf.pending_count(), 1, "requeued, not quarantined");
        assert_eq!(buf.flush_to_api(&hub, "key", &wal), 0); // attempt 2: item fails
        assert_eq!(buf.pending_count(), 1, "requeued, not quarantined");
        assert_eq!(buf.flush_to_api(&hub, "key", &wal), 1); // attempt 3: item applies

        assert_eq!(buf.pending_count(), 0);
        assert!(
            read_rejected_lines(&wal).is_empty(),
            "a per-item failure that eventually succeeds must never be quarantined"
        );

        cleanup(&path, &wal);
    }

    /// Test 5: a transient failure that later succeeds must NOT be
    /// quarantined — attempts stay below the threshold and the transaction
    /// eventually reaches the hub.
    #[test]
    fn transient_failure_then_success_is_not_quarantined() {
        let (path, wal) = test_wal("transient");
        let buf = TransactionBuffer::new();
        buf.push_transaction(tx("r-transient", "alice"));

        let hub = hub_fail_then_succeed(2, 500);
        assert_eq!(buf.flush_to_api(&hub, "key", &wal), 0); // attempt 1: fails
        assert_eq!(buf.pending_count(), 1, "requeued, not quarantined");
        assert_eq!(buf.flush_to_api(&hub, "key", &wal), 0); // attempt 2: fails
        assert_eq!(buf.pending_count(), 1, "requeued, not quarantined");
        assert_eq!(buf.flush_to_api(&hub, "key", &wal), 1); // attempt 3: succeeds

        assert_eq!(buf.pending_count(), 0);
        assert!(
            read_rejected_lines(&wal).is_empty(),
            "a transaction that eventually succeeds must never be quarantined"
        );

        cleanup(&path, &wal);
    }

    /// Test 6: `push_transaction` with the anonymous sentinel must not
    /// buffer it for the hub, while a normal user is buffered as usual.
    #[test]
    fn anonymous_sentinel_is_never_buffered() {
        let buf = TransactionBuffer::new();
        buf.push_transaction(tx("r-anon", ANONYMOUS_USER));
        assert_eq!(
            buf.pending_count(),
            0,
            "the anonymous sentinel must never be buffered for the hub"
        );

        buf.push_transaction(tx("r-real", "alice"));
        assert_eq!(
            buf.pending_count(),
            1,
            "a normal user must still be buffered"
        );
    }

    /// Test 7: every quarantine-file line is valid JSON, one per line, and
    /// carries the error text (already exercised structurally by the tests
    /// above via `read_rejected_lines`, which parses each line as JSON —
    /// this test additionally pins the one-line-per-entry and error-text
    /// shape directly).
    #[test]
    fn quarantine_file_lines_are_valid_json_with_error_text() {
        let (path, wal) = test_wal("valid_json_lines");
        let buf = TransactionBuffer::new();
        buf.push_transaction(tx("r-one", "alice"));
        buf.push_transaction(tx("r-two", "alice"));

        let hub = hub_always(500);
        for _ in 0..MAX_FLUSH_ATTEMPTS {
            buf.flush_to_api(&hub, "key", &wal);
        }

        let rejected_path = TransactionBuffer::rejected_path(&wal);
        let contents = std::fs::read_to_string(&rejected_path).expect("quarantine file exists");
        let lines: Vec<&str> = contents.lines().filter(|l| !l.trim().is_empty()).collect();
        assert_eq!(lines.len(), 2, "one line per quarantined transaction");
        for line in &lines {
            let parsed: serde_json::Value =
                serde_json::from_str(line).expect("each line must be standalone valid JSON");
            assert!(
                parsed["error"].as_str().is_some_and(|s| !s.is_empty()),
                "each quarantined line must carry the error text"
            );
        }

        cleanup(&path, &wal);
    }
}

#[cfg(test)]
mod voucher_nonce_tests {
    use super::*;

    fn tx(nonce: Option<&str>) -> BufferedTransaction {
        BufferedTransaction {
            request_id: "r".into(),
            user_id: "u".into(),
            tx_type: "commit".into(),
            amount: 1.0,
            balance_after: 9.0,
            worker_id: "w".into(),
            duration_ms: 10.0,
            source_node: None,
            worker_name: Some("w".into()),
            worker_uri: None,
            price_per_hour: 1.0,
            voucher_nonce: nonce.map(String::from),
        }
    }

    #[test]
    fn batch_row_carries_the_nonce_only_when_present() {
        let buf = TransactionBuffer::new();
        let row = buf.batch_row(&tx(Some("n-1")));
        assert_eq!(row["voucher_nonce"], "n-1");
        assert!(buf.batch_row(&tx(None)).get("voucher_nonce").is_none());
        assert!(buf.batch_row(&tx(Some(""))).get("voucher_nonce").is_none());
    }

    #[test]
    fn buffered_transaction_round_trips_and_old_json_decodes() {
        let back: BufferedTransaction =
            serde_json::from_str(&serde_json::to_string(&tx(Some("n-2"))).unwrap()).unwrap();
        assert_eq!(back.voucher_nonce.as_deref(), Some("n-2"));
        let plain = serde_json::to_string(&tx(None)).unwrap();
        assert!(!plain.contains("voucher_nonce"));
        let old = r#"{"request_id":"r","user_id":"u","tx_type":"commit","amount":1.0,"balance_after":2.0,"worker_id":"w","duration_ms":1.0,"source_node":null,"worker_name":null,"worker_uri":null,"price_per_hour":0.0}"#;
        let back: BufferedTransaction = serde_json::from_str(old).unwrap();
        assert_eq!(back.voucher_nonce, None);
    }
}