zc2 0.0.47

P2P compute broker with yen-denominated 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
//! WAL replay on broker startup.
//!
//! Reads uncommitted WAL entries and:
//! - Reserved entries → closed (`Failed`) without crediting anything: the hold
//!   died with the process that held it (zc#566)
//! - Executed entries → re-buffer the debit for the flush path; the entry stays
//!   owed until the hub has it (or quarantines it). When the entry records the
//!   executor side of the job (`WalEntry::payout`, zc#562), the payout is
//!   settled too, so the job settles both legs or neither.
//! - Earned entries → re-buffer the owner's earn for the flush path
//! - EarnOwed entries → returned to the caller, which delivers them to the
//!   executor's broker over `/peer/earn` once the job's debit is at the hub
//! - RefundOwed entries → re-buffer the requester's refund row
//! - Entries written by a broker with no hub are closed: nothing could ever
//!   deliver them. Entries a hub broker wrote are left untouched by a restart
//!   that has no hub

use super::flush::{BufferedTransaction, TransactionBuffer};
use super::ledger::Ledger;
use super::wal::{PayoutTo, Wal, WalEntry, WalPayout, WalStatus};

/// The id of the `EarnOwed` entry that tracks a remote executor's payout for
/// job `request_id` (zc#562).
pub fn owed_payout_id(request_id: &str) -> String {
    format!("peer-earn-{request_id}")
}

/// Replay uncommitted WAL entries on startup.
///
/// `tx_buffer` and `node_name` are used to re-deliver `Earned` entries (peer
/// earns that were booked in-memory but never confirmed flushed to the
/// dashboard) via the normal flush path — see the `WalStatus::Earned` arm
/// below.
///
/// Returns the payouts still owed to remote executors (`EarnOwed` entries,
/// zc#562). This function makes no peer call: the caller delivers them once
/// its peers are reachable (`server::deliver_owed_payouts`), and each stays
/// open in the WAL, retried on every restart, until the executor accepts it.
pub fn replay_wal(
    wal: &Wal,
    ledger: &Ledger,
    tx_buffer: &TransactionBuffer,
    node_name: Option<&str>,
) -> Vec<WalEntry> {
    let mut owed = Vec::new();
    let uncommitted = match wal.read_uncommitted() {
        Ok(entries) => entries,
        Err(e) => {
            eprintln!("  [WAL] Failed to read uncommitted entries: {}", e);
            return owed;
        }
    };

    if uncommitted.is_empty() {
        return owed;
    }

    println!(
        "  [WAL] Replaying {} uncommitted entries...",
        uncommitted.len()
    );

    for entry in &uncommitted {
        match entry.status {
            WalStatus::Reserved => {
                // The job never finished, so nothing is owed either way: close
                // the entry and credit nothing (zc#566). The hold lived only
                // in the killed process's in-memory ledger, and this process
                // never made it. Replay seeds no balance, so the next read
                // starts from whatever this process's ledger loads: the hub's
                // balance, which never saw the hold, when the ledger reads the
                // hub (`fetch_balance`; not under `ZAKURO_MASTER_KEY`, which
                // skips the hub read even with `api_url` set), else the fresh
                // in-memory ledger, which holds nothing of the dead process.
                // Adding the hold back here (it used to, `cancel_from_wal`)
                // credited money nobody had taken: it seeded `local_balances`
                // with the hold itself, and that seed was then served as the
                // balance (from cache, or as the fallback when the hub was
                // down) instead of the hub's -- the reasoning #563 applied to
                // `Executed`.
                println!(
                    "  [WAL] Closing stale reservation for user {} (req: {}, held: {:.6}); nothing to refund",
                    entry.user_id, entry.request_id, entry.estimated_cost
                );
                let _ = wal.update_status(&entry.request_id, WalStatus::Failed, None, None);
            }
            // Written by a broker with no hub: the `zc-flush` thread never
            // calls `flush_to_api`, so nothing could ever deliver this row or
            // retire its entry. Close it instead of carrying it (and
            // re-buffering it) on every restart forever. Any payout it records
            // goes with it: the debit it would balance lived only in the
            // killed process's memory, so the job settles neither leg. The
            // same holds for an `Earned`, `EarnOwed` or `RefundOwed` entry
            // written without a hub (zc#566).
            WalStatus::Executed | WalStatus::Earned | WalStatus::RefundOwed if entry.hubless => {
                let _ = wal.update_status(&entry.request_id, WalStatus::Committed, None, None);
            }
            WalStatus::EarnOwed if entry.hubless => {
                let _ = wal.update_status(&entry.request_id, WalStatus::Failed, None, None);
            }
            // Written by a broker with a hub (or before entries were stamped),
            // but this process has none -- a missing secret, say. Leave the
            // entry exactly as it is for a restart that has its hub again:
            // closing it here would forgive the debit (or drop the payout)
            // for good, and re-buffering it would go nowhere.
            WalStatus::Executed
            | WalStatus::Earned
            | WalStatus::EarnOwed
            | WalStatus::RefundOwed
                if !ledger.has_hub() =>
            {
                eprintln!(
                    "  [WAL] {} ({:?}) is owed to a hub this broker has none of; kept as is",
                    entry.request_id, entry.status
                );
            }
            WalStatus::Executed => {
                // Worker completed, so the requester owes the charge:
                // re-deliver the debit through the flush path, exactly like an
                // unflushed earn below. The entry stays `Executed` until a
                // flush lands the row at the hub, which retires it
                // (`flush::retire_delivered`), or quarantines it, which also
                // retires it. The hub dedupes by request_id, so a debit it
                // already has is safe to resend.
                //
                // This arm used to POST the debit straight to the hub and mark
                // the entry Committed whatever the answer was. A broker
                // restarted while the hub was unreachable logged the failure
                // and dropped the requester's debit for good, while the owner's
                // earn for the same job (re-buffered by the `Earned` arm) was
                // retried until it landed (zc#459).
                //
                // Nothing is refunded in memory. The hold lived only in the
                // killed process's ledger; this one re-seeds the requester
                // from the hub, which never saw the hold. Adding back
                // `reserved - actual` here (it used to) minted that amount on
                // every restart for as long as the entry stayed open -- the
                // same reasoning as the `Earned` arm.
                let actual_cost = entry.actual_cost.unwrap_or(entry.estimated_cost);
                println!(
                    "  [WAL] Re-delivering unflushed debit {} for user {} (cost: {:.6})",
                    entry.request_id, entry.user_id, actual_cost
                );
                // Metadata only (the `batch-sync` row does not carry it), so
                // read the cache: `get_balance` fetches from the hub with no
                // timeout, and one blackholed hub would stall startup once
                // per replayed entry.
                let balance_after = ledger
                    .get_authoritative_balance(&entry.user_id)
                    .unwrap_or(0.0);

                // The hub knows this worker by its stable registered name
                // (`sync_workers_via_api` registers workers keyed on
                // `Worker.name`), never by the ephemeral `Worker.id` minted per
                // registration -- send `worker_name` when the WAL recorded one
                // (zc#272). Older WAL lines predate that field and fall back to
                // `worker_id`.
                let worker_identifier = entry
                    .worker_name
                    .clone()
                    .unwrap_or_else(|| entry.worker_id.clone());
                tx_buffer.push_transaction(BufferedTransaction {
                    request_id: entry.request_id.clone(),
                    user_id: entry.user_id.clone(),
                    tx_type: "commit".to_string(),
                    amount: actual_cost,
                    balance_after,
                    worker_id: entry.worker_id.clone(),
                    duration_ms: entry.duration_ms.unwrap_or(0.0),
                    source_node: node_name.map(|s| s.to_string()),
                    worker_name: Some(worker_identifier),
                    worker_uri: None,
                    price_per_hour: 0.0,
                    voucher_nonce: entry.voucher_nonce.clone(),
                });

                // The executor side (zc#562). A broker killed after `Executed`
                // and before the payout was logged left only this line, and
                // replay used to commit the debit alone: the requester paid,
                // nobody was paid. Lines written before `payout` existed, and
                // jobs whose settlement pays nobody, carry `None` and replay
                // exactly as before.
                if let Some(payout) = &entry.payout {
                    if let Some(o) = replay_payout(wal, ledger, tx_buffer, node_name, entry, payout)
                    {
                        owed.push(o);
                    }
                }
            }
            WalStatus::Earned => {
                // Worker earn was booked in-memory but never confirmed
                // flushed to the dashboard (crash before/while flushing).
                //
                // We must NOT re-apply the in-memory earning here. The dashboard
                // is authoritative for spendable balance: `authoritative_balances`
                // re-seeds lazily from the dashboard (via load_balance_if_needed)
                // the next time this user is touched, and on the crash-after-
                // dashboard-write window the dashboard ALREADY reflects this
                // earn. Calling local_add would seed-from-dashboard and
                // then add `amount` on top, inflating the in-memory spendable
                // balance by `amount` until a clean restart (bounded over-spend).
                //
                // So replay ONLY re-delivers the earn to the dashboard to make it
                // durable there: re-buffer the same `earn-{request_id}` earning tx
                // (idempotent via dashboard request_id dedup) and leave the WAL
                // entry `Earned`, so flush_to_api marks it Committed once the
                // dashboard confirms it applied/duplicate. balance_after is only
                // metadata on the tx row; use the ledger's current view without
                // mutating it.
                rebuffer_earn(ledger, tx_buffer, node_name, entry);
            }
            WalStatus::EarnOwed => owed.push(entry.clone()),
            // A refund owed to the requester: re-deliver its row; the flush
            // that lands it retires the entry.
            WalStatus::RefundOwed => rebuffer_refund(ledger, tx_buffer, node_name, entry),
            // Committed/Failed are filtered out by read_uncommitted
            _ => {}
        }
    }

    // Compact after replay
    if let Err(e) = wal.compact() {
        eprintln!("  [WAL] Failed to compact after replay: {}", e);
    }

    println!("  [WAL] Replay complete");
    owed
}

/// Re-buffer an `Earned` entry's earning row for the flush path, without
/// touching the in-memory ledger (see the `Earned` arm of [`replay_wal`]).
fn rebuffer_earn(
    ledger: &Ledger,
    tx_buffer: &TransactionBuffer,
    node_name: Option<&str>,
    entry: &WalEntry,
) {
    let amount = entry.actual_cost.unwrap_or(entry.estimated_cost);
    println!(
        "  [WAL] Re-delivering unflushed earn {} for user {} (amount: {:.6})",
        entry.request_id, entry.user_id, amount
    );
    // Metadata only (the `batch-sync` row does not carry it), so read the
    // cache: `get_balance` fetches from the hub with no timeout, and one
    // blackholed hub would stall startup once per replayed entry.
    let balance_after = ledger
        .get_authoritative_balance(&entry.user_id)
        .unwrap_or(0.0);
    tx_buffer.push_transaction(BufferedTransaction {
        request_id: entry.request_id.clone(),
        user_id: entry.user_id.clone(),
        tx_type: "earning".to_string(),
        amount,
        balance_after,
        worker_id: entry.worker_id.clone(),
        duration_ms: entry.duration_ms.unwrap_or(0.0),
        source_node: node_name.map(|s| s.to_string()),
        worker_name: entry
            .worker_name
            .clone()
            .or_else(|| Some(entry.worker_id.clone())),
        worker_uri: None,
        price_per_hour: 0.0,
        voucher_nonce: None,
    });
}

/// Settle the payout an `Executed` entry records (zc#562), the way the live
/// settlement would have after its debit. Each payout gets a WAL entry of its
/// own, appended only if the WAL has none under that id yet (one atomic
/// check-and-insert, so an entry the kill came after -- or a payout delivered
/// and still retained -- is not settled twice):
///
/// - **Owner** (`settle_self_payout`): the owner's `Earned` entry, and its
///   `earn-` row re-buffered.
/// - **Requester** (nobody to pay): a `RefundOwed` entry under the id the
///   live path uses, and its `refund` row re-buffered.
/// - **Peer** (`settle_executor_payout`): an `EarnOwed` entry, returned for
///   delivery over `/peer/earn` once the debit is at the hub.
///
/// Nothing is booked in memory: balances re-seed from the hub.
fn replay_payout(
    wal: &Wal,
    ledger: &Ledger,
    tx_buffer: &TransactionBuffer,
    node_name: Option<&str>,
    job: &WalEntry,
    payout: &WalPayout,
) -> Option<WalEntry> {
    if payout.amount <= 0.0 {
        return None;
    }
    let worker_name = job
        .worker_name
        .clone()
        .unwrap_or_else(|| job.worker_id.clone());
    match &payout.to {
        PayoutTo::Owner { user_id } => {
            let earned = WalEntry {
                request_id: payout.row_id.clone(),
                user_id: user_id.clone(),
                reservation_id: String::new(),
                estimated_cost: payout.amount,
                actual_cost: Some(payout.amount),
                worker_id: job.worker_id.clone(),
                worker_name: Some(worker_name),
                duration_ms: job.duration_ms,
                timestamp: chrono::Utc::now(),
                status: WalStatus::Earned,
                voucher_nonce: None,
                unit: super::wal::WAL_UNIT.to_string(),
                payout: None,
                hubless: false,
                receipt_hash: None,
            };
            if matches!(wal.append_new(&earned), Ok(true)) {
                rebuffer_earn(ledger, tx_buffer, node_name, &earned);
            }
            None
        }
        PayoutTo::Requester => {
            let refund = refund_owed_entry(
                &payout.row_id,
                &job.user_id,
                payout.amount,
                &job.worker_id,
                &worker_name,
                job.duration_ms,
            );
            if matches!(wal.append_new(&refund), Ok(true)) {
                rebuffer_refund(ledger, tx_buffer, node_name, &refund);
            }
            None
        }
        PayoutTo::Peer { .. } => {
            let owed = owed_payout_entry(job, &worker_name, payout.clone());
            if !matches!(wal.append_new(&owed), Ok(true)) {
                return None;
            }
            println!(
                "  [WAL] Payout {:.6} for {} owed to its remote executor",
                payout.amount, job.request_id
            );
            Some(owed)
        }
    }
}

/// A `RefundOwed` entry: `amount` owed back to `user_id`, booked at the hub
/// as the `refund` row `row_id` (L2 of the #568 review: a refund row with no
/// entry of its own was lost by a kill after its debit had landed).
pub fn refund_owed_entry(
    row_id: &str,
    user_id: &str,
    amount: f64,
    worker_id: &str,
    worker_name: &str,
    duration_ms: Option<f64>,
) -> WalEntry {
    WalEntry {
        request_id: row_id.to_string(),
        user_id: user_id.to_string(),
        reservation_id: String::new(),
        estimated_cost: amount,
        actual_cost: Some(amount),
        worker_id: worker_id.to_string(),
        worker_name: Some(worker_name.to_string()),
        duration_ms,
        timestamp: chrono::Utc::now(),
        status: WalStatus::RefundOwed,
        voucher_nonce: None,
        unit: super::wal::WAL_UNIT.to_string(),
        payout: None,
        hubless: false,
        receipt_hash: None,
    }
}

/// Re-buffer a `RefundOwed` entry's `refund` row for the flush path.
fn rebuffer_refund(
    ledger: &Ledger,
    tx_buffer: &TransactionBuffer,
    node_name: Option<&str>,
    entry: &WalEntry,
) {
    let amount = entry.actual_cost.unwrap_or(entry.estimated_cost);
    println!(
        "  [WAL] Re-delivering refund {} for user {} (amount: {:.6})",
        entry.request_id, entry.user_id, amount
    );
    tx_buffer.push_transaction(BufferedTransaction {
        request_id: entry.request_id.clone(),
        user_id: entry.user_id.clone(),
        tx_type: "refund".to_string(),
        amount,
        balance_after: ledger
            .get_authoritative_balance(&entry.user_id)
            .unwrap_or(0.0),
        worker_id: entry.worker_id.clone(),
        duration_ms: entry.duration_ms.unwrap_or(0.0),
        source_node: node_name.map(|s| s.to_string()),
        worker_name: entry
            .worker_name
            .clone()
            .or_else(|| Some(entry.worker_id.clone())),
        worker_uri: None,
        price_per_hour: 0.0,
        voucher_nonce: None,
    });
}

/// The `EarnOwed` entry for a remote executor's payout on `job` (zc#562).
/// `user_id` is the requester; `payout.row_id` is the id sent in
/// `/peer/earn`.
pub fn owed_payout_entry(job: &WalEntry, worker_name: &str, payout: WalPayout) -> WalEntry {
    WalEntry {
        request_id: owed_payout_id(&job.request_id),
        user_id: job.user_id.clone(),
        reservation_id: String::new(),
        estimated_cost: payout.amount,
        actual_cost: Some(payout.amount),
        worker_id: job.worker_id.clone(),
        worker_name: Some(worker_name.to_string()),
        duration_ms: job.duration_ms,
        timestamp: chrono::Utc::now(),
        status: WalStatus::EarnOwed,
        voucher_nonce: None,
        unit: super::wal::WAL_UNIT.to_string(),
        payout: Some(payout),
        hubless: false,
        receipt_hash: None,
    }
}

#[cfg(test)]
mod worker_attribution_tests {
    use super::*;
    use crate::broker::wal::WalEntry;
    use std::sync::{Arc, Mutex};

    fn tmp_wal(name: &str) -> std::path::PathBuf {
        std::path::PathBuf::from(format!("/tmp/zc_recovery_test_{}.jsonl", name))
    }

    fn cleanup(p: &std::path::Path) {
        let _ = std::fs::remove_file(p);
        let _ = std::fs::remove_file(p.with_extension("tmp"));
    }

    /// Mock hub on a fresh loopback port. Captures the raw body of the
    /// `/api/broker/batch-sync` POST (the flush that delivers a replayed
    /// debit) and answers *every* request 200 until it has been idle for a
    /// few seconds.
    ///
    /// It must keep serving: replay and the flush make more than one hub call
    /// (a balance GET via `ledger.get_balance`, then the flush POST). The old
    /// one-shot server answered the POST and exited, so the follow-up GET
    /// could land on a dead listener or a pooled keep-alive connection nobody
    /// reads from, and `ureq` (no default timeout) blocked forever. That was
    /// the intermittent >420s hang in CI.
    fn capturing_hub() -> (String, Arc<Mutex<Option<String>>>) {
        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
        let port = server.server_addr().to_ip().unwrap().port();
        let captured = Arc::new(Mutex::new(None));
        let seen = captured.clone();
        std::thread::spawn(move || {
            while let Ok(Some(mut req)) = server.recv_timeout(std::time::Duration::from_secs(5)) {
                let mut body = String::new();
                let _ = req.as_reader().read_to_string(&mut body);
                if req.url().ends_with("/api/broker/batch-sync") {
                    *seen.lock().unwrap() = Some(body);
                }
                let _ = req.respond(tiny_http::Response::from_string("{}").with_status_code(200));
            }
        });
        (format!("http://127.0.0.1:{port}"), captured)
    }

    /// Run `replay_wal`, then the flush that delivers what it re-buffered, on
    /// a helper thread, and fail fast if they do not return instead of
    /// hanging CI until the job timeout.
    fn replay_bounded(wal: Wal, hub: String, tx_buffer: TransactionBuffer) {
        let (done_tx, done_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let ledger = Ledger::new(Some(hub.clone()), Some("zk_1_test".to_string()));
            replay_wal(&wal, &ledger, &tx_buffer, None);
            tx_buffer.flush_to_api(&hub, "zk_1_test", &wal);
            let _ = done_tx.send(());
        });
        done_rx
            .recv_timeout(std::time::Duration::from_secs(30))
            .expect("replay_wal did not return within 30s (blocked on a hub call?)");
    }

    fn wait_for_json(captured: &Arc<Mutex<Option<String>>>) -> serde_json::Value {
        for _ in 0..300 {
            if let Some(body) = captured.lock().unwrap().clone() {
                let rows: serde_json::Value = serde_json::from_str(&body)
                    .unwrap_or_else(|e| panic!("captured body {body:?} was not JSON: {e}"));
                return rows[0].clone();
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        panic!("the mock hub never received the dashboard POST");
    }

    fn executed_entry(request_id: &str, worker_id: &str, worker_name: Option<&str>) -> WalEntry {
        WalEntry {
            request_id: request_id.to_string(),
            user_id: "alice".to_string(),
            reservation_id: format!("res-{request_id}"),
            estimated_cost: 0.05,
            actual_cost: Some(0.05),
            worker_id: worker_id.to_string(),
            worker_name: worker_name.map(str::to_string),
            duration_ms: Some(1000.0),
            timestamp: chrono::Utc::now(),
            status: WalStatus::Executed,
            voucher_nonce: None,
            unit: crate::broker::wal::WAL_UNIT.to_string(),
            payout: None,
            hubless: false,
            receipt_hash: None,
        }
    }

    /// The Executed arm re-buffers the debit for the flush path. It must send
    /// the WAL-recorded `worker_name` (the identifier the hub actually
    /// registered the worker under, per `sync_workers_via_api`), not the
    /// ephemeral `worker_id` the original `Reserved` entry was appended with
    /// (zc#272).
    #[test]
    fn replay_of_an_executed_entry_publishes_the_workers_recorded_name() {
        let path = tmp_wal("executed_with_name");
        cleanup(&path);
        let wal = Wal::open(&path).unwrap();
        wal.append(&executed_entry(
            "req-exec-1",
            "ephemeral-uuid-1234",
            Some("gpu-box-1"),
        ))
        .unwrap();
        wal.flush_buffer().unwrap();

        let (hub, captured) = capturing_hub();
        let tx_buffer = TransactionBuffer::new();

        replay_bounded(wal, hub, tx_buffer);

        let body = wait_for_json(&captured);
        assert_eq!(
            body["worker_id"], "gpu-box-1",
            "replay must publish the worker's registered name, body: {body}"
        );
        assert_ne!(
            body["worker_id"], "ephemeral-uuid-1234",
            "must not leak the ephemeral registry id to the hub, body: {body}"
        );
        assert_eq!(body["request_id"], "req-exec-1", "body: {body}");

        cleanup(&path);
    }

    /// Old WAL lines written before `worker_name` existed deserialize with
    /// `None` (`#[serde(default)]`) — replay must still fall back to
    /// `worker_id` rather than sending an empty/null identifier.
    #[test]
    fn replay_of_an_executed_entry_without_a_recorded_name_falls_back_to_worker_id() {
        let path = tmp_wal("executed_without_name");
        cleanup(&path);
        let wal = Wal::open(&path).unwrap();
        wal.append(&executed_entry("req-exec-2", "legacy-worker-id", None))
            .unwrap();
        wal.flush_buffer().unwrap();

        let (hub, captured) = capturing_hub();
        let tx_buffer = TransactionBuffer::new();

        replay_bounded(wal, hub, tx_buffer);

        let body = wait_for_json(&captured);
        assert_eq!(body["worker_id"], "legacy-worker-id", "body: {body}");

        cleanup(&path);
    }

    /// The Earned arm re-buffers the earning for the normal flush path
    /// (`flush::flush_to_api`), which sends `tx.worker_name` to the hub. It
    /// must carry forward the WAL-recorded name, not the ephemeral id.
    #[test]
    fn replay_of_an_earned_entry_rebuffers_the_workers_recorded_name() {
        let path = tmp_wal("earned_with_name");
        cleanup(&path);
        let wal = Wal::open(&path).unwrap();
        wal.append(&WalEntry {
            request_id: "earn-req-1".to_string(),
            user_id: "owner".to_string(),
            reservation_id: String::new(),
            estimated_cost: 1.0,
            actual_cost: Some(1.0),
            worker_id: "ephemeral-uuid-5678".to_string(),
            worker_name: Some("gpu-box-2".to_string()),
            duration_ms: Some(500.0),
            timestamp: chrono::Utc::now(),
            status: WalStatus::Earned,
            voucher_nonce: None,
            unit: crate::broker::wal::WAL_UNIT.to_string(),
            payout: None,
            hubless: false,
            receipt_hash: None,
        })
        .unwrap();
        wal.flush_buffer().unwrap();

        // A hub is configured (down): without one the entry is closed, not
        // re-buffered (zc#566).
        let ledger = Ledger::new(Some("http://127.0.0.1:1".into()), Some("k".into()));
        let tx_buffer = TransactionBuffer::new();

        replay_wal(&wal, &ledger, &tx_buffer, None);

        let queued = tx_buffer.pending_snapshot();
        let tx = queued
            .iter()
            .find(|t| t.request_id == "earn-req-1")
            .expect("the unflushed earn must be re-buffered");
        assert_eq!(
            tx.worker_name,
            Some("gpu-box-2".to_string()),
            "re-buffered earn must carry the worker's recorded name, not its ephemeral id"
        );

        cleanup(&path);
    }
}

/// A mock hub for the replay tests: books each request_id once (it dedupes,
/// like the real one) and counts every row it receives. It can also refuse
/// the way the real one does (`Mode`).
#[cfg(test)]
mod test_hub {
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    #[derive(Clone, Copy)]
    pub(super) enum Mode {
        Accept,
        /// Every row fails with this per-item error. With nothing stored the
        /// real hub answers 500 and puts the per-item results under `detail`.
        ItemError(&'static str),
        /// The whole request is answered with this status.
        Status(u16),
        /// A chunk carrying this request_id fails validation as a whole
        /// (422); any other chunk is accepted.
        InvalidRow(&'static str),
        /// Like `InvalidRow`, for every request_id ending in this suffix.
        InvalidSuffix(&'static str),
    }

    pub(super) struct BookHub {
        pub(super) url: String,
        /// request_id -> (transaction_type, amount)
        book: Arc<Mutex<HashMap<String, (String, f64)>>>,
        pub(super) received: Arc<Mutex<HashMap<String, usize>>>,
        /// `batch-sync` requests answered so far.
        requests: Arc<std::sync::atomic::AtomicUsize>,
    }

    impl BookHub {
        pub(super) fn start() -> Self {
            Self::with(Mode::Accept)
        }

        pub(super) fn with(mode: Mode) -> Self {
            let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
            let url = format!(
                "http://127.0.0.1:{}",
                server.server_addr().to_ip().unwrap().port()
            );
            let book = Arc::new(Mutex::new(HashMap::new()));
            let received = Arc::new(Mutex::new(HashMap::new()));
            let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0));
            let (b, n, q) = (book.clone(), received.clone(), requests.clone());
            std::thread::spawn(move || {
                while let Ok(Some(mut req)) = server.recv_timeout(Duration::from_secs(10)) {
                    let mut body = String::new();
                    let _ = req.as_reader().read_to_string(&mut body);
                    if req.url().ends_with("/api/broker/batch-sync") {
                        q.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    }
                    let rows = match serde_json::from_str::<serde_json::Value>(&body) {
                        Ok(serde_json::Value::Array(rows)) => rows,
                        Ok(row) if req.url().ends_with("/api/broker/transaction") => vec![row],
                        _ => Vec::new(),
                    };
                    let rids: Vec<String> = rows
                        .iter()
                        .filter_map(|r| r["request_id"].as_str().map(str::to_string))
                        .collect();
                    for rid in &rids {
                        *n.lock().unwrap().entry(rid.clone()).or_default() += 1;
                    }
                    let (status, answer) = match mode {
                        Mode::Status(code) => (code, "{}".to_string()),
                        Mode::InvalidRow(bad) if rids.iter().any(|r| r == bad) => {
                            (422, r#"{"detail":"validation error"}"#.to_string())
                        }
                        Mode::InvalidSuffix(bad) if rids.iter().any(|r| r.ends_with(bad)) => {
                            (422, r#"{"detail":"validation error"}"#.to_string())
                        }
                        Mode::ItemError(error) if !rows.is_empty() => {
                            let results: Vec<_> = rids
                                .iter()
                                .map(|r| {
                                    serde_json::json!({
                                        "request_id": r, "status": "failed", "error": error,
                                    })
                                })
                                .collect();
                            let detail = serde_json::json!({
                                "results": results, "success": false, "inserted": 0,
                                "failed": rids.len(),
                            });
                            (500, serde_json::json!({ "detail": detail }).to_string())
                        }
                        _ => {
                            for row in &rows {
                                if let Some(rid) = row["request_id"].as_str() {
                                    b.lock().unwrap().entry(rid.to_string()).or_insert((
                                        row["transaction_type"].as_str().unwrap_or("").to_string(),
                                        row["amount"].as_f64().unwrap_or(f64::NAN),
                                    ));
                                }
                            }
                            (200, "{}".to_string())
                        }
                    };
                    let _ = req
                        .respond(tiny_http::Response::from_string(answer).with_status_code(status));
                }
            });
            Self {
                url,
                book,
                received,
                requests,
            }
        }

        pub(super) fn requests(&self) -> usize {
            self.requests.load(std::sync::atomic::Ordering::SeqCst)
        }

        pub(super) fn booked(&self, rid: &str, kind: &str) -> Option<f64> {
            self.book.lock().unwrap().get(rid).map(|(t, a)| {
                assert_eq!(t, kind, "{rid} booked as {t}");
                *a
            })
        }

        pub(super) fn received(&self, rid: &str) -> usize {
            self.received.lock().unwrap().get(rid).copied().unwrap_or(0)
        }
    }
}

/// What replay leaves open, and what it does to in-memory balances, across
/// restarts that do not deliver everything (zc#459 review).
#[cfg(test)]
mod replay_retirement_tests {
    use super::test_hub::{BookHub, Mode};
    use super::*;
    use crate::broker::wal::WalEntry;
    use std::path::{Path, PathBuf};

    const DOWN: &str = "http://127.0.0.1:1";

    fn wal_dir(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("zc-replay-{name}-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// A job that ran and was charged 4 of the 10 held, debit not delivered.
    fn executed(rid: &str) -> WalEntry {
        WalEntry {
            request_id: rid.to_string(),
            user_id: "u1".to_string(),
            reservation_id: format!("res-{rid}"),
            estimated_cost: 10.0,
            actual_cost: Some(4.0),
            worker_id: "wid".to_string(),
            worker_name: Some("w".to_string()),
            duration_ms: Some(1000.0),
            timestamp: chrono::Utc::now(),
            status: WalStatus::Executed,
            voucher_nonce: None,
            unit: crate::broker::wal::WAL_UNIT.to_string(),
            payout: None,
            hubless: false,
            receipt_hash: None,
        }
    }

    fn write_wal(dir: &Path, entries: &[WalEntry]) {
        let wal = Wal::open(dir.join("wal.jsonl")).unwrap();
        for e in entries {
            wal.append(e).unwrap();
        }
        wal.flush_buffer().unwrap();
    }

    /// One restart: replay against `hub_url` (None: no hub configured), then
    /// flush to it until the buffer is empty or `flushes` runs out. Returns
    /// the ledger (to inspect what replay did to balances) and what is still
    /// owed in the WAL afterwards.
    fn restart(dir: &Path, hub_url: Option<&str>, flushes: usize) -> (Ledger, Vec<WalEntry>) {
        let wal = Wal::open(dir.join("wal.jsonl")).unwrap();
        let ledger = Ledger::new(
            hub_url.map(str::to_string),
            hub_url.map(|_| "k".to_string()),
        );
        let tx_buffer = TransactionBuffer::new();
        replay_wal(&wal, &ledger, &tx_buffer, None);
        if let Some(url) = hub_url {
            for _ in 0..flushes {
                if tx_buffer.pending_count() == 0 {
                    break;
                }
                tx_buffer.flush_to_api(url, "k", &wal);
            }
        }
        wal.flush_buffer().unwrap();
        let owed = wal.read_uncommitted().unwrap();
        (ledger, owed)
    }

    fn local_balance(ledger: &Ledger, user: &str) -> f64 {
        ledger.local_balances.get(user).map_or(0.0, |b| *b)
    }

    /// Restarted while its debit is still undelivered: the debit stays owed
    /// across a restart that cannot deliver it, is delivered exactly once by
    /// the next, and no restart refunds the dead hold (`reserved - actual`)
    /// into memory.
    #[test]
    fn an_undelivered_debit_is_delivered_once_and_never_refunded_on_restart() {
        let dir = wal_dir("undelivered");
        write_wal(&dir, &[executed("job-a")]);

        let (ledger, owed) = restart(&dir, Some(DOWN), 1);
        assert!(owed.iter().any(|e| e.request_id == "job-a"), "{owed:?}");
        assert!(
            local_balance(&ledger, "u1").abs() < 1e-9,
            "no refund minted"
        );

        let hub = BookHub::start();
        for _ in 0..2 {
            let (ledger, owed) = restart(&dir, Some(&hub.url), 1);
            assert!(owed.is_empty(), "delivered, so retired: {owed:?}");
            assert!(
                local_balance(&ledger, "u1").abs() < 1e-9,
                "no refund minted"
            );
        }
        assert_eq!(hub.received("job-a"), 1);
        assert_eq!(hub.booked("job-a", "job_execution"), Some(4.0));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A debit the hub refuses for good (here the requester does not exist,
    /// as the hub words it) is quarantined once and its entry retired: the
    /// next restart sends it nowhere and quarantines nothing new.
    #[test]
    fn a_permanently_refused_debit_is_quarantined_once_not_on_every_restart() {
        let dir = wal_dir("refused");
        write_wal(&dir, &[executed("job-r")]);
        let hub = BookHub::with(Mode::ItemError("User not found: u1"));

        let (_, owed) = restart(&dir, Some(&hub.url), 20);
        assert!(owed.is_empty(), "quarantined, so retired: {owed:?}");
        let attempts = hub.received("job-r");
        assert!(attempts > 0);

        let (_, owed) = restart(&dir, Some(&hub.url), 20);
        assert!(owed.is_empty(), "{owed:?}");
        assert_eq!(hub.received("job-r"), attempts, "re-sent after quarantine");
        let rejected = std::fs::read_to_string(dir.join("wal-rejected.jsonl")).unwrap();
        assert_eq!(
            rejected.lines().filter(|l| l.contains("job-r")).count(),
            1,
            "{rejected}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Refusals that clear -- an expired session or rotated key (403), rate
    /// limiting (429), a per-item lookup failure on the hub -- quarantine the
    /// row but keep its entry, so a restart against a good hub delivers it.
    #[test]
    fn a_debit_refused_for_a_reason_that_clears_is_delivered_after_a_restart() {
        for mode in [
            // A whole-request status is never the row's fault on batch-sync:
            // 400 from the edge, 404 from an ingress mid-redeploy, 403 from an
            // expired session or rotated key, 429 from a rate limiter.
            Mode::Status(400),
            Mode::Status(404),
            Mode::Status(403),
            Mode::Status(429),
            Mode::ItemError("403: Acting for another account requires a hub voucher for that account (lookup_error)"),
        ] {
            let dir = wal_dir("transient");
            write_wal(&dir, &[executed("job-t")]);
            let refusing = BookHub::with(mode);

            let (_, owed) = restart(&dir, Some(&refusing.url), 20);
            assert!(refusing.received("job-t") > 0);
            assert!(owed.iter().any(|e| e.request_id == "job-t"), "{owed:?}");

            let hub = BookHub::start();
            let (_, owed) = restart(&dir, Some(&hub.url), 1);
            assert!(owed.is_empty(), "{owed:?}");
            assert_eq!(hub.received("job-t"), 1);
            assert_eq!(hub.booked("job-t", "job_execution"), Some(4.0));
            let _ = std::fs::remove_dir_all(&dir);
        }
    }

    /// One malformed row fails validation for its whole chunk (422). The
    /// chunk is bisected, so the innocent rows land. The bad row stays owed
    /// even once it is refused on its own: the hub may be the one at fault
    /// (a validator tightened in a deploy), and a row re-sent on every
    /// restart beats a charge dropped for good.
    #[test]
    fn a_422_chunk_still_delivers_its_innocent_rows_and_keeps_the_bad_one_owed() {
        let dir = wal_dir("invalid");
        write_wal(
            &dir,
            &[
                executed("job-ok-1"),
                executed("job-bad"),
                executed("job-ok-2"),
            ],
        );
        let hub = BookHub::with(Mode::InvalidRow("job-bad"));

        let (_, owed) = restart(&dir, Some(&hub.url), 20);
        let owed: Vec<_> = owed.iter().map(|e| e.request_id.as_str()).collect();
        assert_eq!(owed, ["job-bad"]);
        assert_eq!(hub.booked("job-ok-1", "job_execution"), Some(4.0));
        assert_eq!(hub.booked("job-ok-2", "job_execution"), Some(4.0));
        assert_eq!(hub.booked("job-bad", "job_execution"), None);

        let fixed = BookHub::start();
        let (_, owed) = restart(&dir, Some(&fixed.url), 1);
        assert!(owed.is_empty(), "{owed:?}");
        assert_eq!(fixed.booked("job-bad", "job_execution"), Some(4.0));
        assert_eq!(
            fixed.received("job-ok-1"),
            0,
            "delivered rows are not re-sent"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Bisecting a refused chunk costs a bounded number of requests per
    /// flush, however many rows it holds; the rest wait for the next flush,
    /// and every innocent row is delivered in the end.
    #[test]
    fn bisecting_a_refused_chunk_is_bounded_per_flush() {
        let dir = wal_dir("bisect");
        // 300 rows, every tenth one malformed.
        let entries: Vec<_> = (0..300)
            .map(|i| executed(&format!("job-{i}{}", if i % 10 == 0 { "-bad" } else { "" })))
            .collect();
        write_wal(&dir, &entries);
        let hub = BookHub::with(Mode::InvalidSuffix("-bad"));

        let wal = Wal::open(dir.join("wal.jsonl")).unwrap();
        let ledger = Ledger::new(Some(hub.url.clone()), Some("k".to_string()));
        let tx_buffer = TransactionBuffer::new();
        replay_wal(&wal, &ledger, &tx_buffer, None);
        for _ in 0..200 {
            let before = hub.requests();
            tx_buffer.flush_to_api(&hub.url, "k", &wal);
            let spent = hub.requests() - before;
            // One request for the chunk itself, plus the split budget.
            assert!(spent <= 1 + 64, "one flush sent {spent} requests");
            if tx_buffer.pending_count() == 0 {
                break;
            }
        }
        assert_eq!(tx_buffer.pending_count(), 0, "the backlog drained");
        for i in (0..300).filter(|i| i % 10 != 0) {
            assert_eq!(
                hub.booked(&format!("job-{i}"), "job_execution"),
                Some(4.0),
                "job-{i}"
            );
        }
        wal.flush_buffer().unwrap();
        let owed = wal.read_uncommitted().unwrap();
        assert_eq!(owed.len(), 30, "only the malformed rows stay owed");
        assert!(owed.iter().all(|e| e.request_id.ends_with("-bad")));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Quarantined because the hub could not be reached, a debit keeps its
    /// entry, so the restart after the outage delivers it.
    #[test]
    fn a_debit_quarantined_while_the_hub_is_down_is_delivered_after_it() {
        let dir = wal_dir("outage");
        write_wal(&dir, &[executed("job-o")]);

        let (_, owed) = restart(&dir, Some(DOWN), 20);
        assert!(owed.iter().any(|e| e.request_id == "job-o"), "{owed:?}");

        let hub = BookHub::start();
        let (_, owed) = restart(&dir, Some(&hub.url), 1);
        assert!(owed.is_empty(), "{owed:?}");
        assert_eq!(hub.booked("job-o", "job_execution"), Some(4.0));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A billing broker with no hub (ZAKURO_MASTER_KEY, no api_url/api_key)
    /// never flushes, so nothing would ever retire an open debit: replay
    /// closes the entries it wrote (stamped `hubless`), and restarts do not
    /// move in-memory balances.
    #[test]
    fn a_hubless_broker_closes_executed_entries_and_mints_nothing() {
        let dir = wal_dir("hubless");
        let hubless = |rid: &str| WalEntry {
            hubless: true,
            receipt_hash: None,
            ..executed(rid)
        };
        write_wal(
            &dir,
            &[hubless("job-1"), hubless("job-2"), hubless("job-3")],
        );
        for _ in 0..2 {
            let (ledger, owed) = restart(&dir, None, 0);
            assert!(owed.is_empty(), "{owed:?}");
            assert!(
                local_balance(&ledger, "u1").abs() < 1e-9,
                "no refund minted"
            );
        }
        let _ = std::fs::remove_dir_all(&dir);
    }
    /// An owner's earn logged by a broker with no hub could never be flushed,
    /// so it was re-buffered on every restart forever. Replay closes the ones
    /// stamped `hubless` (zc#566); restarts do not move in-memory balances.
    #[test]
    fn a_hubless_broker_closes_earned_entries_and_mints_nothing() {
        let dir = wal_dir("hubless-earned");
        let earned = |rid: &str| WalEntry {
            request_id: format!("earn-{rid}"),
            user_id: "owner".to_string(),
            reservation_id: String::new(),
            actual_cost: Some(3.6),
            estimated_cost: 3.6,
            status: WalStatus::Earned,
            hubless: true,
            receipt_hash: None,
            ..executed(rid)
        };
        write_wal(&dir, &[earned("job-1"), earned("job-2")]);
        for _ in 0..2 {
            let (ledger, owed) = restart(&dir, None, 0);
            assert!(owed.is_empty(), "{owed:?}");
            assert!(
                local_balance(&ledger, "owner").abs() < 1e-9,
                "no earn minted"
            );
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A hub broker restarted once without its hub (a missing secret) must
    /// not forgive what it owes: its entries are left untouched -- not
    /// closed, not re-buffered -- and the next restart with the hub delivers
    /// them (review M4 of #568).
    #[test]
    fn a_hub_brokers_entries_survive_a_restart_without_its_hub() {
        let dir = wal_dir("missing-secret");
        let earned = WalEntry {
            request_id: "earn-job-1".to_string(),
            user_id: "owner".to_string(),
            reservation_id: String::new(),
            actual_cost: Some(3.6),
            estimated_cost: 3.6,
            status: WalStatus::Earned,
            ..executed("job-1")
        };
        write_wal(&dir, &[executed("job-1"), earned]);
        for _ in 0..2 {
            let (ledger, owed) = restart(&dir, None, 0);
            assert_eq!(owed.len(), 2, "both still owed: {owed:?}");
            assert!(local_balance(&ledger, "u1").abs() < 1e-9);
            assert!(local_balance(&ledger, "owner").abs() < 1e-9);
        }
        let hub = BookHub::start();
        let (_, owed) = restart(&dir, Some(&hub.url), 1);
        assert!(owed.is_empty(), "{owed:?}");
        assert_eq!(hub.booked("job-1", "job_execution"), Some(4.0));
        assert_eq!(hub.booked("earn-job-1", "earning"), Some(3.6));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// With a hub, the same entries are still re-delivered and stay owed
    /// until a flush lands them.
    #[test]
    fn a_broker_with_a_hub_keeps_earned_entries_owed_until_delivered() {
        let dir = wal_dir("hub-earned");
        let earned = WalEntry {
            request_id: "earn-job-1".to_string(),
            user_id: "owner".to_string(),
            reservation_id: String::new(),
            actual_cost: Some(3.6),
            estimated_cost: 3.6,
            status: WalStatus::Earned,
            ..executed("job-1")
        };
        write_wal(&dir, &[earned]);
        let (_, owed) = restart(&dir, Some(DOWN), 1);
        assert!(
            owed.iter().any(|e| e.request_id == "earn-job-1"),
            "{owed:?}"
        );
        let hub = BookHub::start();
        let (_, owed) = restart(&dir, Some(&hub.url), 1);
        assert!(owed.is_empty(), "{owed:?}");
        assert_eq!(hub.booked("earn-job-1", "earning"), Some(3.6));
        let _ = std::fs::remove_dir_all(&dir);
    }
}

/// `kill -9` at each settlement boundary (zc#459).
///
/// Each test SIGKILLs a real process -- this test binary re-run as
/// `kill9_child` -- that writes one billed job's WAL lines through the real
/// group-commit flush worker (no manual flush), in the order `execute_prepare`
/// and `execute_finish` write them: `Reserved`, then `Executed`, then the
/// owner's `earn-` entry (`Earned`, from `settle_self_payout`). The child is
/// killed once the worker has persisted the boundary under test; the rows it
/// had queued for the hub die with it. The parent then restarts the broker
/// side -- `replay_wal` and one flush -- against a mock hub that books each
/// request_id once, as the real one does, and checks the books.
///
/// The order the real settlement code writes those lines in, and every crash
/// point inside it, is covered by `server::settlement_crash_tests`.
#[cfg(all(test, unix))]
mod kill9_tests {
    use super::test_hub::BookHub;
    use super::*;
    use crate::broker::wal::{read_all_from_disk, PayoutTo, WalEntry, WalPayout};
    use std::io::{BufRead, BufReader, Write};
    use std::os::unix::process::ExitStatusExt;
    use std::path::{Path, PathBuf};
    use std::process::{Child, Command, Stdio};
    use std::sync::atomic::AtomicBool;
    use std::sync::Arc;
    use std::time::{Duration, Instant};

    const ENV_DIR: &str = "ZC_KILL9_WAL_DIR";
    const ENV_BOUNDARY: &str = "ZC_KILL9_BOUNDARY";
    const READY: &str = "ZC_KILL9_READY";
    const RID: &str = "kill9-job";
    const HELD: f64 = 10.0;
    const COST: f64 = 4.0;
    /// Commission rate: the owner is paid `COST * (1 - C)`.
    const C: f64 = 0.1;

    fn entry(request_id: &str, user: &str, status: WalStatus, amount: f64) -> WalEntry {
        WalEntry {
            request_id: request_id.to_string(),
            user_id: user.to_string(),
            reservation_id: format!("res-{RID}"),
            estimated_cost: amount,
            actual_cost: (status != WalStatus::Reserved).then_some(amount),
            worker_id: "wid".to_string(),
            worker_name: Some("own-worker".to_string()),
            duration_ms: Some(1000.0),
            timestamp: chrono::Utc::now(),
            status,
            voucher_nonce: None,
            unit: crate::broker::wal::WAL_UNIT.to_string(),
            payout: None,
            hubless: false,
            receipt_hash: None,
        }
    }

    /// The broker half, run only in the child the parent kills. A no-op in a
    /// normal test run (the env is unset).
    #[test]
    fn kill9_child() {
        let (Ok(dir), Ok(boundary)) = (std::env::var(ENV_DIR), std::env::var(ENV_BOUNDARY)) else {
            return;
        };
        let path = Path::new(&dir).join("wal.jsonl");
        let wal = Arc::new(Wal::open(&path).unwrap());
        let running = Arc::new(AtomicBool::new(true));
        let (w, r) = (wal.clone(), running.clone());
        std::thread::spawn(move || w.run_flush_worker(&r));

        // execute_prepare
        wal.append(&entry(RID, "u1", WalStatus::Reserved, HELD))
            .unwrap();
        let mut lines = 1;
        if boundary != "reserved" {
            // execute_finish, before commit_charge: the line records the
            // owner's payout, as `planned_payout` does (zc#562)
            wal.mark_executed(
                RID,
                COST,
                1000.0,
                Some(WalPayout {
                    to: PayoutTo::Owner {
                        user_id: "owner".to_string(),
                    },
                    row_id: format!("earn-{RID}"),
                    amount: COST * (1.0 - C),
                    commission: COST * C,
                    commission_c: C,
                }),
                None,
            )
            .unwrap();
            lines += 1;
        }
        if boundary == "earned" {
            // commit_charge -> settle_self_payout
            let earn = format!("earn-{RID}");
            wal.append(&entry(&earn, "owner", WalStatus::Earned, COST * (1.0 - C)))
                .unwrap();
            lines += 1;
        }

        // Wait for the flush worker, not a manual flush, to make it durable.
        let deadline = Instant::now() + Duration::from_secs(10);
        while read_all_from_disk(&path).map_or(0, |e| e.len()) < lines {
            assert!(Instant::now() < deadline, "flush worker never persisted");
            std::thread::sleep(Duration::from_millis(5));
        }
        println!("{READY}");
        std::io::stdout().flush().unwrap();
        // The parent SIGKILLs us here. Never outlive a parent that failed.
        std::thread::sleep(Duration::from_secs(60));
        std::process::exit(3);
    }

    /// Kills the child however the parent exits.
    struct Reaper(Child);
    impl Drop for Reaper {
        fn drop(&mut self) {
            let _ = self.0.kill();
            let _ = self.0.wait();
        }
    }

    /// Run `kill9_child` up to `boundary`, SIGKILL it there, and return the
    /// directory holding the WAL it left.
    fn sigkill_at(boundary: &str) -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("zc-kill9-{boundary}-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let module = module_path!().split_once("::").unwrap().1;
        let child = Command::new(std::env::current_exe().unwrap())
            .args([
                &format!("{module}::kill9_child"),
                "--exact",
                "--nocapture",
                "--test-threads=1",
            ])
            .env(ENV_DIR, &dir)
            .env(ENV_BOUNDARY, boundary)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit())
            .spawn()
            .unwrap();
        let mut child = Reaper(child);
        let stdout = child.0.stdout.take().unwrap();
        let (ready_tx, ready_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            for line in BufReader::new(stdout).lines().map_while(Result::ok) {
                // libtest prints `test <name> ... ` without a newline
                // before the test's own output, so READY ends the line.
                if line.trim_end().ends_with(READY) {
                    let _ = ready_tx.send(());
                }
            }
        });
        ready_rx
            .recv_timeout(Duration::from_secs(60))
            .expect("the child never reached its boundary");

        child.0.kill().unwrap(); // SIGKILL on unix
        let status = child.0.wait().unwrap();
        assert_eq!(
            status.signal(),
            Some(9),
            "child was not SIGKILLed: {status:?}"
        );
        dir
    }

    /// Restart the killed broker twice: replay (against the hub as it was at
    /// startup) then one flush (against the live hub), each time. The second
    /// restart proves delivery retired the WAL: it must re-send nothing.
    fn restart_twice(dir: &Path, hub: &BookHub, hub_up_at_replay: bool) {
        let at_replay = if hub_up_at_replay {
            hub.url.clone()
        } else {
            "http://127.0.0.1:1".to_string() // refused: hub unreachable at boot
        };
        for _ in 0..2 {
            let wal = Wal::open(dir.join("wal.jsonl")).unwrap();
            let ledger = Ledger::new(Some(at_replay.clone()), Some("k".to_string()));
            let tx_buffer = TransactionBuffer::new();
            replay_wal(&wal, &ledger, &tx_buffer, None);
            tx_buffer.flush_to_api(&hub.url, "k", &wal);
            wal.flush_buffer().unwrap();
        }
        for (rid, n) in hub.received.lock().unwrap().iter() {
            assert_eq!(*n, 1, "{rid} delivered {n} times");
        }
    }

    /// Debit and earn for the job, as booked at the hub.
    fn settle(boundary: &str, hub_up_at_replay: bool) -> (Option<f64>, Option<f64>) {
        let dir = sigkill_at(boundary);
        let hub = BookHub::start();
        restart_twice(&dir, &hub, hub_up_at_replay);
        let _ = std::fs::remove_dir_all(&dir);
        (
            hub.booked(RID, "job_execution"),
            hub.booked(&format!("earn-{RID}"), "earning"),
        )
    }

    fn assert_conserves(debit: Option<f64>, earn: Option<f64>) {
        let (Some(debit), Some(earn)) = (debit, earn) else {
            panic!("requester debit {debit:?}, owner earn {earn:?}: one leg was dropped");
        };
        assert!((debit - COST).abs() < 1e-9, "debit {debit} != {COST}");
        assert!(
            (debit - (earn + COST * C)).abs() < 1e-9,
            "debit {debit} != earn {earn} + commission {}",
            COST * C
        );
    }

    #[test]
    fn kill9_after_reserved_settles_nothing() {
        for hub_up in [true, false] {
            assert_eq!(settle("reserved", hub_up), (None, None), "hub up: {hub_up}");
        }
    }

    /// The Oct 2 incident with a healthy hub: fixed on master by #349.
    #[test]
    fn kill9_after_earned_redelivers_debit_and_earn() {
        let (debit, earn) = settle("earned", true);
        assert_conserves(debit, earn);
    }

    /// The Oct 2 symptom, still reproducible after #349: when the hub is
    /// unreachable while the restarted broker replays, the `Executed` arm's
    /// one-shot POST failed, the debit was retired anyway, and only the
    /// re-buffered earn was ever delivered.
    #[test]
    fn kill9_after_earned_with_the_hub_down_at_restart_redelivers_debit_and_earn() {
        let (debit, earn) = settle("earned", false);
        assert_conserves(debit, earn);
    }

    #[test]
    fn kill9_after_executed_redelivers_the_debit() {
        for hub_up in [true, false] {
            let (debit, _) = settle("executed", hub_up);
            assert_eq!(debit, Some(COST), "hub up: {hub_up}");
        }
    }

    /// Killed after `Executed` and before the earn is logged, the replayed
    /// debit used to have no earn beside it: nothing in the WAL said the
    /// owner was owed the payout (zc#562). The `Executed` line records it now.
    #[test]
    fn kill9_after_executed_redelivers_debit_and_earn() {
        for hub_up in [true, false] {
            let (debit, earn) = settle("executed", hub_up);
            assert_conserves(debit, earn);
        }
    }
}