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
//! Write-Ahead Log for crash recovery.
//!
//! Append-only JSON Lines file that tracks the lifecycle of each request:
//! Reserved → Executed → Committed/Failed
//!
//! On broker restart, uncommitted entries are replayed to ensure
//! no money is lost if the broker crashes after worker execution.
//!
//! Optimizations:
//! - In-memory DashMap index for O(1) update_status lookups
//! - Lock-free `SegQueue` durability buffer; the hot path (`append`) only pushes
//! — it never holds a lock or `fsync`s. A dedicated flush worker
//! (`run_flush_worker`, spawned by the broker) drains the queue and `fsync`s
//! on a 100ms age bound (or sooner when the buffer crosses the size
//! threshold), so durability stays time-bounded with zero fsync on the
//! request path (group commit).
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::fs::{self, File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Condvar, Mutex};
use std::time::{Duration, Instant};
use crossbeam_queue::SegQueue;
/// Max entries before flushing the write buffer to disk. Large batches keep the
/// `fsync` rate bounded and off the per-request critical path under high load
/// (group commit); the `WRITE_BUFFER_MAX_AGE_MS` bound below still caps how long
/// any entry waits, so durability is time-bounded regardless of batch size.
const WRITE_BUFFER_MAX_ENTRIES: usize = 1024;
/// Max time (ms) before flushing the write buffer to disk.
const WRITE_BUFFER_MAX_AGE_MS: u128 = 100;
/// WAL entry status
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WalStatus {
Reserved,
Executed,
/// A peer earning has been applied to the in-memory ledger and queued
/// for dashboard delivery, but has not yet been confirmed flushed. Treated
/// as non-terminal (like `Reserved`/`Executed`): `read_uncommitted` and
/// `compact` both keep it around until it's marked `Committed`.
Earned,
/// A payout owed to a remote executor's broker (`/peer/earn`) that it has
/// not acknowledged yet, keyed `peer-earn-{request_id}` and carrying the
/// [`WalPayout`] to send (zc#562). Non-terminal: it stays open, and is
/// retried on every restart, until the executor answers 2xx.
#[serde(rename = "earn_owed")]
EarnOwed,
/// A refund owed to a requester (`{rid}-earn-refund`,
/// `{rid}-unresolved-refund`) that the hub has not confirmed yet. Replay
/// re-buffers its `refund` row; the flush that delivers it retires it.
#[serde(rename = "refund_owed")]
RefundOwed,
Committed,
Failed,
}
/// Whether an entry is still owed (anything but `Committed`/`Failed`).
pub fn is_open(status: &WalStatus) -> bool {
!matches!(status, WalStatus::Committed | WalStatus::Failed)
}
/// Who is paid the executor side of a job, and how much (zc#562).
///
/// Recorded on the `Executed` line, which is written before any of the
/// settlement it describes, so a broker killed anywhere between the requester's
/// debit and the executor's payout can finish the payout on replay instead of
/// committing the debit alone.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WalPayout {
pub to: PayoutTo,
/// The request_id the payout is booked under: the `earning` row
/// (`earn-{rid}`) for this broker's owner, the `refund` row for the
/// requester, or the id sent in `/peer/earn` (the job's own id; the
/// executor books it as `earn-{rid}`) for a remote executor.
pub row_id: String,
/// Payout to the executor (or refund to the requester).
pub amount: f64,
/// The platform's cut of the charge: `debit = amount + commission` for an
/// executor payout.
#[serde(default)]
pub commission: f64,
#[serde(default)]
pub commission_c: f64,
}
/// The payee of a [`WalPayout`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PayoutTo {
/// This broker's own worker ran the job: its owner is paid on this
/// broker's hub (`settle_self_payout`).
Owner { user_id: String },
/// Another node ran the job: its broker is paid over `/peer/earn`
/// (`settle_executor_payout`). `fp` is the executor's node fingerprint,
/// `url` the peer URL it resolved to when the job ran.
Peer { fp: String, url: String },
/// Nobody can be paid, so the amount goes back to the requester.
Requester,
}
/// A single WAL entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WalEntry {
pub request_id: String,
pub user_id: String,
pub reservation_id: String,
pub estimated_cost: f64,
pub actual_cost: Option<f64>,
pub worker_id: String,
/// The worker's stable registered name (`Worker.name`), the identifier
/// the hub actually knows it by (`sync_workers_via_api` registers
/// workers keyed on `name`, never on the ephemeral `Worker.id`). Recovery
/// publishes this to the dashboard instead of `worker_id` so replayed
/// transactions stay attributable (zc#272). `#[serde(default)]` so WAL
/// lines written before this field existed still deserialize — they fall
/// back to `worker_id` at the two read sites in `recovery.rs`.
#[serde(default)]
pub worker_name: Option<String>,
pub duration_ms: Option<f64>,
pub timestamp: DateTime<Utc>,
pub status: WalStatus,
/// Hub voucher `task_nonce` of the job, when it was voucher-backed
/// (zc#400). Persisted so recovery and late flushes still send it with
/// `/transaction` and `/batch-sync`. `#[serde(default)]` so older WAL
/// lines decode as `None`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub voucher_nonce: Option<String>,
/// Unit of `estimated_cost`/`actual_cost`: always [`WAL_UNIT`] once
/// written by this build. Empty only on a line written before ADR 0027,
/// whose amounts are in the old unit; [`Wal::open`] converts those once.
#[serde(default)]
pub unit: String,
/// The executor side of the job, on an `Executed` entry whose settlement
/// pays someone, and on an `EarnOwed` entry (zc#562). `None` on every
/// other entry, and on every line written before this field existed:
/// those replay exactly as before.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payout: Option<WalPayout>,
/// Written by a broker with no hub configured (stamped by [`Wal::append`]
/// once [`Wal::set_hubless`] is set). Replay closes only these when it has
/// no hub: an entry a hub broker wrote is left untouched by a restart that
/// is merely missing its hub secret. `false` on lines from before the
/// field, which are therefore never closed for want of a hub.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub hubless: bool,
/// The hub's signed receipt for this entry's debit, from the `batch-sync`
/// answer, kept so the executor's payout (`EarnOwed`) is delivered with
/// the proof (`earn_receipt`). `None` from a hub that issues none, and on
/// every line written before this field existed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub receipt_hash: Option<String>,
}
/// How long an executor remembers a `/peer/earn` request_id after its
/// `Earned` entry has left the WAL, so a resend is still recognised (zc#562).
pub const EARN_DEDUPE_RETENTION: chrono::Duration = chrono::Duration::days(7);
/// At most this many remembered `/peer/earn` ids; the oldest go first.
pub const EARN_DEDUPE_CAP: usize = 1_000_000;
/// `reservation_id` of an `Earned` entry booked by `/peer/earn` (as opposed
/// to an owner's earn from `settle_self_payout`): only these are remembered
/// once compacted away, since only these can be resent.
pub const PEER_EARN_MARK: &str = "peer/earn";
/// The `/peer/earn` ids an executor booked whose `Earned` entries have been
/// compacted out of the WAL (zc#562): `{request_id, ts}` lines in a side file
/// next to the WAL, bounded by [`EARN_DEDUPE_RETENTION`] and
/// [`EARN_DEDUPE_CAP`]. Kept out of the WAL so its size, compaction and
/// `/health` do not grow with job volume.
struct EarnReceived {
path: PathBuf,
/// id -> unix seconds it was remembered, plus insertion order for the cap.
inner: Mutex<ReceivedSet>,
/// Lines in the file that are no longer live (expired or evicted).
stale: AtomicUsize,
/// [`EARN_DEDUPE_CAP`], smaller in tests.
cap: usize,
/// Serializes writes to the side file (an append vs a rewrite), so the
/// I/O never runs under `inner`.
file_lock: Mutex<()>,
}
/// id -> when it was remembered, and the order they were remembered in.
type ReceivedSet = (
std::collections::HashMap<String, i64>,
std::collections::VecDeque<(String, i64)>,
);
#[derive(Serialize, Deserialize)]
struct ReceivedLine {
id: String,
ts: i64,
}
impl EarnReceived {
fn open(wal_path: &Path) -> Self {
let name = wal_path
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| "wal".into());
let path = wal_path.with_file_name(format!("{name}.earn-received.jsonl"));
let me = Self {
path,
inner: Mutex::new(Default::default()),
stale: AtomicUsize::new(0),
cap: EARN_DEDUPE_CAP,
file_lock: Mutex::new(()),
};
// A kill mid-append can leave a torn last line with no newline; the
// next append would then be glued onto it and both ids lost. Cut the
// file back to its last complete line first.
let bytes = fs::read(&me.path).unwrap_or_default();
if bytes.last().is_some_and(|b| *b != b'\n') {
let keep = bytes.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1);
if let Ok(f) = OpenOptions::new().write(true).open(&me.path) {
let _ = f.set_len(keep as u64);
let _ = f.sync_all();
}
}
let lines: Vec<ReceivedLine> = String::from_utf8_lossy(&bytes[..])
.lines()
.filter_map(|l| serde_json::from_str(l).ok())
.collect();
{
let mut g = me.inner.lock().unwrap_or_else(|e| e.into_inner());
for l in lines {
if g.0.insert(l.id.clone(), l.ts).is_none() {
g.1.push_back((l.id, l.ts));
}
}
}
me.expire(Utc::now().timestamp());
me
}
fn contains(&self, id: &str) -> bool {
let g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
g.0.contains_key(id)
}
/// Drop ids past the age bound or over the cap (oldest first).
fn expire(&self, now: i64) {
let cutoff = now - EARN_DEDUPE_RETENTION.num_seconds();
let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
let mut dropped = 0;
while let Some((id, ts)) = g.1.front().cloned() {
if ts >= cutoff && g.1.len() <= self.cap {
break;
}
g.1.pop_front();
if g.0.get(&id) == Some(&ts) {
g.0.remove(&id);
}
dropped += 1;
}
self.stale.fetch_add(dropped, Ordering::Relaxed);
}
/// Remember `ids` durably (appended and fsynced) before the caller drops
/// their entries from the WAL.
fn remember(&self, ids: &[String]) -> std::io::Result<()> {
if ids.is_empty() {
return Ok(());
}
let now = Utc::now().timestamp();
let _io = self.file_lock.lock().unwrap_or_else(|e| e.into_inner());
let mut f = OpenOptions::new()
.create(true)
.append(true)
.open(&self.path)?;
for id in ids {
let line = serde_json::to_string(&ReceivedLine {
id: id.clone(),
ts: now,
})
.map_err(std::io::Error::other)?;
writeln!(f, "{line}")?;
}
f.sync_data()?;
let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
for id in ids {
if g.0.insert(id.clone(), now).is_some() {
self.stale.fetch_add(1, Ordering::Relaxed);
}
g.1.push_back((id.clone(), now));
}
drop(g);
self.expire(now);
Ok(())
}
/// Rewrite the file with only the live ids, once enough of it is stale.
/// The new contents are built under `inner`; the file I/O runs outside
/// it, under `file_lock`.
fn compact(&self) -> std::io::Result<()> {
self.expire(Utc::now().timestamp());
let _io = self.file_lock.lock().unwrap_or_else(|e| e.into_inner());
let contents = {
let g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
let stale = self.stale.load(Ordering::Relaxed);
if stale == 0 || stale < g.1.len() / 4 {
return Ok(());
}
let mut out = String::new();
for (id, ts) in g.1.iter() {
if g.0.get(id) == Some(ts) {
let line = serde_json::to_string(&ReceivedLine {
id: id.clone(),
ts: *ts,
})
.map_err(std::io::Error::other)?;
out.push_str(&line);
out.push('\n');
}
}
out
};
let tmp = self.path.with_extension("tmp");
{
let mut f = File::create(&tmp)?;
f.write_all(contents.as_bytes())?;
f.sync_all()?;
}
fs::rename(&tmp, &self.path)?;
self.stale.store(0, Ordering::Relaxed);
Ok(())
}
#[cfg(test)]
fn len(&self) -> usize {
self.inner.lock().unwrap().0.len()
}
}
/// The unit every WAL amount is in (ADR 0027).
pub const WAL_UNIT: &str = super::balance::CURRENCY;
/// Yen per old (pre-ADR 0027) unit, for the one-time WAL upgrade.
const LEGACY_UNIT_IN_YEN: f64 = 150.0;
/// Convert an entry written before ADR 0027 (no `unit`) to yen in place.
/// Returns whether it changed. Rounds to 6 decimals like every amount.
fn upgrade_legacy_unit(entry: &mut WalEntry) -> bool {
if !entry.unit.is_empty() {
return false;
}
fn to_yen(v: f64) -> f64 {
(v * LEGACY_UNIT_IN_YEN * 1_000_000.0).round() / 1_000_000.0
}
entry.estimated_cost = to_yen(entry.estimated_cost);
entry.actual_cost = entry.actual_cost.map(to_yen);
entry.unit = WAL_UNIT.to_string();
true
}
/// Write-Ahead Log
///
/// Hot path (`append`) is fully non-blocking: it inserts into the sharded
/// `DashMap` index and pushes a serialized line onto a lock-free `SegQueue`. It
/// never takes the file lock and never `fsync`s. The `file` mutex + `fsync` live
/// entirely in `flush_buffer`, which is run by the dedicated `run_flush_worker`
/// thread (and by rare maintenance ops: `read_uncommitted`, `compact`, shutdown).
/// So no request thread ever blocks on `fsync`.
pub struct Wal {
path: PathBuf,
file: Mutex<File>,
/// In-memory index: request_id → latest WalEntry (O(1) lookup).
entries_index: DashMap<String, WalEntry>,
/// Lock-free durability buffer: serialized lines awaiting fsync.
pending: SegQueue<String>,
/// Approximate count of `pending` (drives the size-based flush trigger).
pending_count: AtomicUsize,
/// Flush-worker wake predicate: set true when `append` crosses the size
/// threshold, so the worker flushes early instead of waiting the full age
/// bound. Paired with `flush_cv`.
flush_signal: Mutex<bool>,
/// Condvar the flush worker parks on (woken by `flush_signal` or its own
/// `WRITE_BUFFER_MAX_AGE_MS` timeout).
flush_cv: Condvar,
/// Monotonic clock base for the age-based flush trigger.
start: Instant,
/// Nanos (since `start`) of the last flush, for the age-based trigger.
last_flush_nanos: AtomicU64,
/// Whether the index has been populated from disk.
index_populated: AtomicBool,
/// Stamp every appended entry `hubless` (this broker has no hub).
hubless: AtomicBool,
/// `/peer/earn` ids remembered past their WAL entries (executor dedupe).
earn_received: EarnReceived,
/// Compactions whose `earn_received.remember` failed.
remember_failures: AtomicUsize,
/// Runs inside `compact`, after the tmp file is written and before the
/// rename, with the file lock held.
#[cfg(test)]
before_swap: Mutex<Option<Box<dyn Fn() + Send + Sync>>>,
}
/// Exposed for tests only — reads entries directly from disk (bypasses index).
#[cfg(test)]
pub fn read_all_from_disk(path: &std::path::Path) -> std::io::Result<Vec<WalEntry>> {
let file = std::fs::File::open(path)?;
let reader = std::io::BufReader::new(file);
let mut entries = Vec::new();
for line in reader.lines() {
let line = line?;
if !line.trim().is_empty() {
if let Ok(e) = serde_json::from_str::<WalEntry>(&line) {
entries.push(e);
}
}
}
Ok(entries)
}
impl Wal {
/// Open or create a WAL file at the given path
pub fn open<P: AsRef<Path>>(path: P) -> std::io::Result<Self> {
let path = path.as_ref().to_path_buf();
// Ensure parent directory exists
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let file = OpenOptions::new().create(true).append(true).open(&path)?;
let earn_received = EarnReceived::open(&path);
let wal = Self {
earn_received,
remember_failures: AtomicUsize::new(0),
#[cfg(test)]
before_swap: Mutex::new(None),
path,
file: Mutex::new(file),
entries_index: DashMap::new(),
pending: SegQueue::new(),
pending_count: AtomicUsize::new(0),
flush_signal: Mutex::new(false),
flush_cv: Condvar::new(),
start: Instant::now(),
last_flush_nanos: AtomicU64::new(0),
index_populated: AtomicBool::new(false),
hubless: AtomicBool::new(false),
};
// Populate index from existing WAL file. Lines from before ADR 0027
// come back converted to yen; rewrite the file once so a restart never
// converts them again.
if wal.populate_index() {
wal.compact()?;
}
Ok(wal)
}
/// Whether `request_id` has an open entry (latest status neither
/// `Committed` nor `Failed`), i.e. replay would act on it after a
/// restart. O(1) from the in-memory index; no flush (zc#566).
pub fn has_open_entry(&self, request_id: &str) -> bool {
self.entries_index
.get(request_id)
.is_some_and(|e| is_open(&e.status))
}
/// Populate the in-memory index from the WAL file on disk.
fn populate_index(&self) -> bool {
let mut upgraded = false;
if let Ok(entries) = self.read_all() {
for mut entry in entries {
upgraded |= upgrade_legacy_unit(&mut entry);
self.entries_index.insert(entry.request_id.clone(), entry);
}
}
self.index_populated.store(true, Ordering::Release);
upgraded
}
/// Append a new entry to the WAL
pub fn append(&self, entry: &WalEntry) -> std::io::Result<()> {
let (entry, line) = self.stamp(entry)?;
// Update in-memory index (DashMap is sharded — no global lock).
self.entries_index.insert(entry.request_id.clone(), entry);
self.enqueue(line);
Ok(())
}
/// The entry as it is written (unit and `hubless` stamped) and its line.
fn stamp(&self, entry: &WalEntry) -> std::io::Result<(WalEntry, String)> {
let hubless = self.hubless.load(Ordering::Relaxed);
let mut entry = entry.clone();
if entry.unit.is_empty() {
entry.unit = WAL_UNIT.to_string();
}
entry.hubless |= hubless;
let line = serde_json::to_string(&entry).map_err(std::io::Error::other)?;
Ok((entry, line))
}
/// Push a line onto the lock-free durability buffer. The hot path stops
/// here: no file lock, no fsync — the dedicated flush worker drains the
/// queue.
fn enqueue(&self, line: String) {
self.pending.push(line);
let n = self.pending_count.fetch_add(1, Ordering::Relaxed) + 1;
// When the buffer crosses the size threshold, wake the worker early
// (best-effort, non-blocking): a missed wake just defers to the worker's
// age-bound timeout, so durability is still capped at the age bound.
if n >= WRITE_BUFFER_MAX_ENTRIES {
if let Ok(mut signaled) = self.flush_signal.try_lock() {
*signaled = true;
self.flush_cv.notify_one();
}
}
}
/// Dedicated WAL flush worker. The broker spawns one of these at startup; it
/// owns every `fsync` so no request thread ever blocks on durable I/O.
///
/// Parks on `flush_cv` with a `WRITE_BUFFER_MAX_AGE_MS` timeout: it wakes on
/// the timeout (age-bounded group commit) or early when `append` crosses the
/// size threshold, then drains the buffer with a single `fsync`. Runs until
/// `running` is cleared, then does a final drain so nothing is lost on a
/// graceful shutdown. Blocks the calling thread.
pub fn run_flush_worker(&self, running: &AtomicBool) {
let age = Duration::from_millis(WRITE_BUFFER_MAX_AGE_MS as u64);
while running.load(Ordering::Relaxed) {
{
let guard = self.flush_signal.lock().unwrap_or_else(|e| e.into_inner());
let (mut guard, _timeout) = self
.flush_cv
.wait_timeout(guard, age)
.unwrap_or_else(|e| e.into_inner());
*guard = false; // consume the signal
}
if !running.load(Ordering::Relaxed) {
break;
}
if self.pending_count.load(Ordering::Relaxed) > 0 {
let _ = self.flush_buffer();
}
}
// Final drain on shutdown.
let _ = self.flush_buffer();
}
/// Update the status of an existing entry by appending a new line
/// with the same request_id but updated status/fields.
/// Uses the in-memory index for O(1) lookup instead of reading from disk.
pub fn update_status(
&self,
request_id: &str,
status: WalStatus,
actual_cost: Option<f64>,
duration_ms: Option<f64>,
) -> std::io::Result<()> {
// Look up from in-memory index (O(1))
let original = self.entries_index.get(request_id).map(|e| e.clone());
if let Some(orig) = original {
let updated = WalEntry {
request_id: orig.request_id.clone(),
user_id: orig.user_id.clone(),
reservation_id: orig.reservation_id.clone(),
estimated_cost: orig.estimated_cost,
actual_cost: actual_cost.or(orig.actual_cost),
worker_id: orig.worker_id.clone(),
worker_name: orig.worker_name.clone(),
duration_ms: duration_ms.or(orig.duration_ms),
timestamp: Utc::now(),
status,
voucher_nonce: orig.voucher_nonce.clone(),
unit: orig.unit.clone(),
payout: orig.payout.clone(),
hubless: orig.hubless,
receipt_hash: orig.receipt_hash.clone(),
};
self.append(&updated)?;
}
Ok(())
}
/// Record the hub's receipt hash for `request_id`'s debit, keeping its
/// status. A no-op for an unknown id or the hash it already has.
pub fn attach_receipt(&self, request_id: &str, receipt_hash: &str) -> std::io::Result<()> {
let original = self.entries_index.get(request_id).map(|e| e.clone());
if let Some(orig) = original {
if orig.receipt_hash.as_deref() != Some(receipt_hash) {
self.append(&WalEntry {
timestamp: Utc::now(),
receipt_hash: Some(receipt_hash.to_string()),
..orig
})?;
}
}
Ok(())
}
/// Mark `request_id` `Executed` and record who its settlement pays, in
/// one line (zc#562). `worker` (`(id, name)`) names the worker that ran
/// it when the reservation could not (a batch is reserved before it is
/// placed): the hub refuses an earning whose debit names no worker. Like
/// `update_status`, a no-op for an unknown id.
pub fn mark_executed(
&self,
request_id: &str,
actual_cost: f64,
duration_ms: f64,
payout: Option<WalPayout>,
worker: Option<(&str, &str)>,
) -> std::io::Result<()> {
let original = self.entries_index.get(request_id).map(|e| e.clone());
if let Some(orig) = original {
let (worker_id, worker_name) = match worker {
Some((id, name)) => (id.to_string(), Some(name.to_string())),
None => (orig.worker_id.clone(), orig.worker_name.clone()),
};
self.append(&WalEntry {
actual_cost: Some(actual_cost),
duration_ms: Some(duration_ms),
timestamp: Utc::now(),
status: WalStatus::Executed,
payout,
worker_id,
worker_name,
..orig
})?;
}
Ok(())
}
/// Record that the payout on `request_id`'s `Executed` entry has been
/// settled some other way (paid, or refunded), so replay must not settle
/// it again. Keeps the entry's status: the debit it carries is still owed
/// until a flush delivers it. A no-op unless the entry is `Executed` with
/// a payout.
pub fn clear_payout(&self, request_id: &str) -> std::io::Result<()> {
let original = self.entries_index.get(request_id).map(|e| e.clone());
if let Some(orig) = original {
if orig.status == WalStatus::Executed && orig.payout.is_some() {
self.append(&WalEntry {
timestamp: Utc::now(),
payout: None,
..orig
})?;
}
}
Ok(())
}
/// The latest entry for `request_id`, if the index still has it.
/// Committed and Failed entries leave the index at the next compaction,
/// except the ones [`Wal::compact`] retains.
pub fn get(&self, request_id: &str) -> Option<WalEntry> {
self.entries_index.get(request_id).map(|e| e.clone())
}
/// Mark every entry appended from now on as written without a hub.
pub fn set_hubless(&self, hubless: bool) {
self.hubless.store(hubless, Ordering::Relaxed);
}
/// Append `entry` only if the WAL has no entry under its request_id, as
/// one atomic check-and-insert. Returns whether it was appended.
pub fn append_new(&self, entry: &WalEntry) -> std::io::Result<bool> {
use dashmap::mapref::entry::Entry;
let (entry, line) = self.stamp(entry)?;
match self.entries_index.entry(entry.request_id.clone()) {
Entry::Occupied(_) => Ok(false),
// Queued while the shard lock is held, so whoever sees the id in
// the index finds its line queued too: a `flush_buffer` after
// that makes it durable.
Entry::Vacant(v) => {
self.enqueue(line);
v.insert(entry);
Ok(true)
}
}
}
/// Open `EarnOwed` entries: payouts owed to remote executors.
pub fn open_owed_payouts(&self) -> Vec<WalEntry> {
self.entries_index
.iter()
.filter(|e| e.status == WalStatus::EarnOwed)
.map(|e| e.value().clone())
.collect()
}
/// How many payouts are owed to remote executors, and the age in seconds
/// of the oldest (for `/health`).
pub fn owed_payouts_summary(&self) -> (usize, i64) {
let now = Utc::now();
let owed = self.open_owed_payouts();
let oldest = owed
.iter()
.map(|e| (now - e.timestamp).num_seconds().max(0))
.max()
.unwrap_or(0);
(owed.len(), oldest)
}
/// Whether a closed entry must stay on disk and in the index anyway: a
/// job whose remote payout is still owed (`peer-earn-{rid}` open, listed
/// in `owed`), so the payout can tell a delivered debit from a refused
/// one.
fn retain_closed(entry: &WalEntry, owed: &std::collections::HashSet<String>) -> bool {
owed.contains(&format!("peer-earn-{}", entry.request_id))
}
/// Whether this executor already booked the `/peer/earn` booked as
/// `earn_id`: its `Earned` entry is still in the WAL, or it was compacted
/// away and remembered (zc#562).
pub fn peer_earn_seen(&self, earn_id: &str) -> bool {
self.entries_index.contains_key(earn_id) || self.earn_received.contains(earn_id)
}
/// Flush the durability buffer to disk with a single fsync.
///
/// The file lock is taken first and held across the drain+write, so only
/// one flusher runs at a time and the `SegQueue`'s FIFO order is preserved
/// on disk (a request's Reserved→Executed→Committed lines stay ordered).
/// Concurrent `append`s during a flush are lock-free and simply land in the
/// next batch.
pub fn flush_buffer(&self) -> std::io::Result<()> {
let mut file = self
.file
.lock()
.map_err(|_| std::io::Error::other("WAL lock poisoned"))?;
self.flush_locked(&mut file)
}
/// Drain `pending` into `file` and fsync, with the file lock held by the
/// caller.
fn flush_locked(&self, file: &mut File) -> std::io::Result<()> {
let mut drained = 0usize;
let mut wrote_any = false;
while let Some(line) = self.pending.pop() {
writeln!(file, "{}", line)?;
drained += 1;
wrote_any = true;
}
if !wrote_any {
return Ok(());
}
file.flush()?;
file.sync_data()?;
self.pending_count.fetch_sub(
drained.min(self.pending_count.load(Ordering::Relaxed)),
Ordering::Relaxed,
);
self.last_flush_nanos
.store(self.start.elapsed().as_nanos() as u64, Ordering::Relaxed);
Ok(())
}
/// Read all entries from the WAL file
fn read_all(&self) -> std::io::Result<Vec<WalEntry>> {
let file = File::open(&self.path)?;
let reader = BufReader::new(file);
let mut entries = Vec::new();
for line in reader.lines() {
let line = line?;
if line.trim().is_empty() {
continue;
}
if let Ok(entry) = serde_json::from_str::<WalEntry>(&line) {
entries.push(entry);
}
}
Ok(entries)
}
/// Read uncommitted entries (the latest status for each request_id
/// that is not Committed or Failed).
/// Uses in-memory index when available.
pub fn read_uncommitted(&self) -> std::io::Result<Vec<WalEntry>> {
// Flush any buffered writes first
let _ = self.flush_buffer();
if self.index_populated.load(Ordering::Acquire) {
// Fast path: read from DashMap index
Ok(self
.entries_index
.iter()
.filter(|e| e.status != WalStatus::Committed && e.status != WalStatus::Failed)
.map(|e| e.value().clone())
.collect())
} else {
// Fallback: read from disk
let entries = self.read_all()?;
let mut latest: std::collections::HashMap<String, WalEntry> =
std::collections::HashMap::new();
for mut entry in entries {
upgrade_legacy_unit(&mut entry);
latest.insert(entry.request_id.clone(), entry);
}
Ok(latest
.into_values()
.filter(|e| e.status != WalStatus::Committed && e.status != WalStatus::Failed)
.collect())
}
}
/// Path to the WAL file. Used by `flush` to derive the sibling
/// `wal-rejected.jsonl` quarantine path (same directory resolution),
/// and by tests.
pub fn path(&self) -> &std::path::Path {
&self.path
}
/// Compact the WAL: rewrite keeping the open entries, the closed ones
/// [`Wal::retain_closed`] keeps, and every line this build cannot parse.
/// `/peer/earn` ids leaving it are remembered in the side file first.
/// Also clears the dropped entries from the in-memory index.
pub fn compact(&self) -> std::io::Result<()> {
// Hold the file lock from the drain through the swap: a line flushed
// in between would be fsynced into the old file and then lost by the
// rename over a tmp built from an older snapshot -- for a `/peer/earn`
// line already acknowledged 200, an earn lost on the next kill. Lock
// order: file, then index shards (read in the snapshot, write in
// `remove_if`); nothing takes them the other way round.
let mut file = self
.file
.lock()
.map_err(|_| std::io::Error::other("WAL lock poisoned"))?;
self.flush_locked(&mut file)?;
// Snapshot first: deciding what to keep looks other entries up, and
// that must not happen under the index's shard locks.
let all: Vec<WalEntry> = self
.entries_index
.iter()
.map(|e| e.value().clone())
.collect();
let owed: std::collections::HashSet<String> = all
.iter()
.filter(|e| e.status == WalStatus::EarnOwed)
.map(|e| e.request_id.clone())
.collect();
let (mut kept, mut dropped): (Vec<WalEntry>, Vec<WalEntry>) = all
.into_iter()
.partition(|e| is_open(&e.status) || Self::retain_closed(e, &owed));
// Remember the `/peer/earn` ids about to leave the WAL, durably and
// before they leave it, so a resend is still recognised. If that
// fails (disk full), keep those entries in the WAL instead -- the
// dedupe must not be lost -- and say so loudly; the rest of the
// compaction goes ahead.
let received: Vec<String> = dropped
.iter()
.filter(|e| e.reservation_id == PEER_EARN_MARK)
.map(|e| e.request_id.clone())
.collect();
if let Err(e) = self.earn_received.remember(&received) {
self.remember_failures.fetch_add(1, Ordering::Relaxed);
eprintln!(
" [WAL] ERROR: could not remember {} /peer/earn ids in {}: {e}; \
keeping their entries in the WAL",
received.len(),
self.earn_received.path.display()
);
let (keep, rest): (Vec<WalEntry>, Vec<WalEntry>) = dropped
.into_iter()
.partition(|e| e.reservation_id == PEER_EARN_MARK);
kept.extend(keep);
dropped = rest;
}
if let Err(e) = self.earn_received.compact() {
eprintln!(
" [WAL] could not rewrite {}: {e}",
self.earn_received.path.display()
);
}
// Lines this build cannot parse (a newer build's status, say) are
// kept verbatim rather than erased: they may be money a newer build
// still owes.
let unknown = self.read_unparseable().unwrap_or_default();
// Write to temp file, then rename
let tmp_path = self.path.with_extension("tmp");
{
let mut tmp = File::create(&tmp_path)?;
for line in &unknown {
writeln!(tmp, "{}", line)?;
}
for entry in &kept {
let line = serde_json::to_string(entry).map_err(std::io::Error::other)?;
writeln!(tmp, "{}", line)?;
}
tmp.sync_all()?;
}
#[cfg(test)]
if let Some(hook) = self.before_swap.lock().unwrap().as_ref() {
hook();
}
// Swap files
fs::rename(&tmp_path, &self.path)?;
// Reopen the file handle for future appends
*file = OpenOptions::new()
.create(true)
.append(true)
.open(&self.path)?;
// Clear the closed entries that were not kept from the index, unless
// an append changed them meanwhile.
for e in dropped {
self.entries_index.remove_if(&e.request_id, |_, cur| {
cur.timestamp == e.timestamp && !is_open(&cur.status)
});
}
Ok(())
}
/// Compactions that could not remember the `/peer/earn` ids leaving the
/// WAL (and so kept them in it), since start (for `/health`).
pub fn earn_dedupe_failures(&self) -> usize {
self.remember_failures.load(Ordering::Relaxed)
}
/// Non-empty lines of the WAL file that do not parse as a [`WalEntry`].
fn read_unparseable(&self) -> std::io::Result<Vec<String>> {
let file = File::open(&self.path)?;
Ok(BufReader::new(file)
.lines()
.map_while(Result::ok)
.filter(|l| !l.trim().is_empty() && serde_json::from_str::<WalEntry>(l).is_err())
.collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn tmp_wal(name: &str) -> std::path::PathBuf {
std::path::PathBuf::from(format!("/tmp/zc_wal_test_{}.jsonl", name))
}
fn cleanup(p: &std::path::Path) {
let _ = fs::remove_file(p);
let _ = fs::remove_file(p.with_extension("tmp"));
}
fn entry(request_id: &str, status: WalStatus) -> 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: None,
worker_id: "worker-1".to_string(),
worker_name: None,
duration_ms: None,
timestamp: Utc::now(),
status,
voucher_nonce: None,
unit: WAL_UNIT.to_string(),
payout: None,
hubless: false,
receipt_hash: None,
}
}
#[test]
fn test_open_creates_file() {
let path = tmp_wal("open");
cleanup(&path);
let _wal = Wal::open(&path).unwrap();
assert!(path.exists());
cleanup(&path);
}
#[test]
fn test_append_then_flush_persists_to_disk() {
let path = tmp_wal("append");
cleanup(&path);
let wal = Wal::open(&path).unwrap();
wal.append(&entry("req-1", WalStatus::Reserved)).unwrap();
wal.flush_buffer().unwrap();
let disk = read_all_from_disk(&path).unwrap();
assert_eq!(disk.len(), 1);
assert_eq!(disk[0].request_id, "req-1");
assert_eq!(disk[0].status, WalStatus::Reserved);
cleanup(&path);
}
#[test]
fn test_update_status_appends_new_line() {
let path = tmp_wal("update");
cleanup(&path);
let wal = Wal::open(&path).unwrap();
wal.append(&entry("req-2", WalStatus::Reserved)).unwrap();
wal.update_status("req-2", WalStatus::Committed, Some(0.03), Some(100.0))
.unwrap();
wal.flush_buffer().unwrap();
// Two lines on disk: reserved + committed
let disk = read_all_from_disk(&path).unwrap();
assert_eq!(disk.len(), 2);
assert_eq!(disk[1].status, WalStatus::Committed);
assert_eq!(disk[1].actual_cost, Some(0.03));
cleanup(&path);
}
#[test]
fn test_update_status_unknown_request_is_noop() {
let path = tmp_wal("update_noop");
cleanup(&path);
let wal = Wal::open(&path).unwrap();
// Should not panic or error
wal.update_status("nonexistent", WalStatus::Committed, None, None)
.unwrap();
wal.flush_buffer().unwrap();
let disk = read_all_from_disk(&path).unwrap();
assert!(disk.is_empty());
cleanup(&path);
}
#[test]
fn test_read_uncommitted_excludes_committed_and_failed() {
let path = tmp_wal("uncommitted");
cleanup(&path);
let wal = Wal::open(&path).unwrap();
wal.append(&entry("req-a", WalStatus::Reserved)).unwrap();
wal.append(&entry("req-b", WalStatus::Reserved)).unwrap();
wal.append(&entry("req-c", WalStatus::Reserved)).unwrap();
wal.update_status("req-b", WalStatus::Committed, Some(0.01), Some(10.0))
.unwrap();
wal.update_status("req-c", WalStatus::Failed, None, None)
.unwrap();
wal.flush_buffer().unwrap();
let uncommitted = wal.read_uncommitted().unwrap();
let ids: Vec<&str> = uncommitted.iter().map(|e| e.request_id.as_str()).collect();
assert!(ids.contains(&"req-a"), "req-a should be uncommitted");
assert!(
!ids.contains(&"req-b"),
"req-b (committed) should be excluded"
);
assert!(!ids.contains(&"req-c"), "req-c (failed) should be excluded");
cleanup(&path);
}
#[test]
fn test_compact_removes_committed_entries_from_disk() {
let path = tmp_wal("compact");
cleanup(&path);
let wal = Wal::open(&path).unwrap();
wal.append(&entry("req-keep", WalStatus::Reserved)).unwrap();
wal.append(&entry("req-done", WalStatus::Reserved)).unwrap();
wal.update_status("req-done", WalStatus::Committed, Some(0.01), Some(5.0))
.unwrap();
wal.flush_buffer().unwrap();
wal.compact().unwrap();
let disk = read_all_from_disk(&path).unwrap();
let ids: Vec<&str> = disk.iter().map(|e| e.request_id.as_str()).collect();
assert!(
ids.contains(&"req-keep"),
"uncommitted entry should survive compaction"
);
assert!(
!ids.contains(&"req-done"),
"committed entry should be removed"
);
cleanup(&path);
}
#[test]
fn test_compact_also_clears_failed_entries() {
let path = tmp_wal("compact_failed");
cleanup(&path);
let wal = Wal::open(&path).unwrap();
wal.append(&entry("req-fail", WalStatus::Reserved)).unwrap();
wal.update_status("req-fail", WalStatus::Failed, None, None)
.unwrap();
wal.flush_buffer().unwrap();
wal.compact().unwrap();
let disk = read_all_from_disk(&path).unwrap();
assert!(disk.is_empty());
cleanup(&path);
}
#[test]
fn test_reload_populates_index_from_disk() {
let path = tmp_wal("reload");
cleanup(&path);
// Write and close
{
let wal = Wal::open(&path).unwrap();
wal.append(&entry("req-persist", WalStatus::Reserved))
.unwrap();
wal.flush_buffer().unwrap();
}
// Reopen: index must be repopulated from disk
{
let wal = Wal::open(&path).unwrap();
let uncommitted = wal.read_uncommitted().unwrap();
assert!(
uncommitted.iter().any(|e| e.request_id == "req-persist"),
"Reloaded WAL must surface persisted reserved entry"
);
}
cleanup(&path);
}
#[test]
fn test_flush_worker_persists_without_manual_flush() {
use std::sync::Arc;
use std::time::Duration;
let path = tmp_wal("flush_worker");
cleanup(&path);
let wal = Arc::new(Wal::open(&path).unwrap());
let running = Arc::new(AtomicBool::new(true));
// Spawn the dedicated flush worker (what the broker does at startup).
let w = wal.clone();
let r = running.clone();
let handle = std::thread::spawn(move || w.run_flush_worker(&r));
// append() must NOT fsync inline — the worker persists it within the age bound.
wal.append(&entry("req-bg", WalStatus::Reserved)).unwrap();
// Wait comfortably past the age bound for the worker to flush.
std::thread::sleep(Duration::from_millis(WRITE_BUFFER_MAX_AGE_MS as u64 * 4));
let disk = read_all_from_disk(&path).unwrap();
assert_eq!(
disk.len(),
1,
"worker should have persisted the appended entry"
);
assert_eq!(disk[0].request_id, "req-bg");
running.store(false, Ordering::Release);
handle.join().unwrap();
cleanup(&path);
}
#[test]
fn test_flush_worker_drains_on_shutdown() {
use std::sync::Arc;
let path = tmp_wal("flush_worker_shutdown");
cleanup(&path);
let wal = Arc::new(Wal::open(&path).unwrap());
let running = Arc::new(AtomicBool::new(true));
let w = wal.clone();
let r = running.clone();
let handle = std::thread::spawn(move || w.run_flush_worker(&r));
// Append then immediately request shutdown; the worker must drain on exit.
wal.append(&entry("req-drain", WalStatus::Reserved))
.unwrap();
running.store(false, Ordering::Release);
handle.join().unwrap();
let disk = read_all_from_disk(&path).unwrap();
assert!(
disk.iter().any(|e| e.request_id == "req-drain"),
"worker must flush pending entries on shutdown"
);
cleanup(&path);
}
#[test]
fn test_earned_status_is_uncommitted_until_marked_committed() {
let path = tmp_wal("earned_uncommitted");
cleanup(&path);
let wal = Wal::open(&path).unwrap();
let mut e = entry("earn-req-1", WalStatus::Earned);
e.actual_cost = Some(0.02);
wal.append(&e).unwrap();
wal.flush_buffer().unwrap();
// Earned is non-terminal: it must show up as uncommitted (replay-eligible),
// same as Reserved/Executed.
let uncommitted = wal.read_uncommitted().unwrap();
assert!(
uncommitted.iter().any(|e| e.request_id == "earn-req-1"),
"Earned entries must be replay-eligible until marked Committed"
);
// compact() must NOT drop it while still Earned.
wal.compact().unwrap();
let disk = read_all_from_disk(&path).unwrap();
assert!(
disk.iter().any(|e| e.request_id == "earn-req-1"),
"Earned entries must survive compaction until Committed"
);
// Once marked Committed, it's excluded and compaction drops it.
wal.update_status("earn-req-1", WalStatus::Committed, Some(0.02), None)
.unwrap();
wal.flush_buffer().unwrap();
let uncommitted = wal.read_uncommitted().unwrap();
assert!(!uncommitted.iter().any(|e| e.request_id == "earn-req-1"));
cleanup(&path);
}
#[test]
fn test_full_lifecycle_reserved_executed_committed() {
let path = tmp_wal("lifecycle");
cleanup(&path);
let wal = Wal::open(&path).unwrap();
let e = entry("req-life", WalStatus::Reserved);
wal.append(&e).unwrap();
// Transition to Executed
wal.update_status("req-life", WalStatus::Executed, None, Some(250.0))
.unwrap();
// Transition to Committed
wal.update_status("req-life", WalStatus::Committed, Some(0.04), Some(250.0))
.unwrap();
wal.flush_buffer().unwrap();
// No uncommitted entries should remain
let uncommitted = wal.read_uncommitted().unwrap();
assert!(!uncommitted.iter().any(|e| e.request_id == "req-life"));
cleanup(&path);
}
#[test]
fn voucher_nonce_round_trips_and_old_records_decode() {
let mut e = entry("r-n", WalStatus::Reserved);
e.voucher_nonce = Some("nonce-1".to_string());
let line = serde_json::to_string(&e).unwrap();
let back: WalEntry = serde_json::from_str(&line).unwrap();
assert_eq!(back.voucher_nonce.as_deref(), Some("nonce-1"));
// Without a nonce the field is not written, and reads back as None.
let plain = serde_json::to_string(&entry("r-p", WalStatus::Reserved)).unwrap();
assert!(!plain.contains("voucher_nonce"), "{plain}");
let back: WalEntry = serde_json::from_str(&plain).unwrap();
assert_eq!(back.voucher_nonce, None);
// A record written before the field existed (no `voucher_nonce`, no
// `worker_name`) still decodes.
let old = r#"{"request_id":"old","user_id":"u","reservation_id":"x","estimated_cost":1.0,"actual_cost":null,"worker_id":"w","duration_ms":null,"timestamp":"2026-10-01T00:00:00Z","status":"reserved"}"#;
let back: WalEntry = serde_json::from_str(old).unwrap();
assert_eq!(back.voucher_nonce, None);
}
#[test]
fn status_update_keeps_the_voucher_nonce() {
let path =
std::env::temp_dir().join(format!("zc-wal-nonce-{}.jsonl", uuid::Uuid::new_v4()));
let wal = Wal::open(&path).unwrap();
let mut e = entry("r-keep", WalStatus::Reserved);
e.voucher_nonce = Some("nonce-keep".to_string());
wal.append(&e).unwrap();
wal.update_status("r-keep", WalStatus::Executed, Some(1.0), Some(5.0))
.unwrap();
wal.flush_buffer().unwrap();
let all = read_all_from_disk(&path).unwrap();
assert!(!all.is_empty());
assert!(all
.iter()
.all(|x| x.voucher_nonce.as_deref() == Some("nonce-keep")));
let _ = std::fs::remove_file(&path);
}
/// ADR 0027: an un-flushed line from before the yen switch (no `unit`)
/// is converted x150 exactly once and tagged; a committed one is dropped
/// by the rewrite (already delivered).
#[test]
fn legacy_entries_are_converted_to_yen_once() {
let path = std::env::temp_dir().join(format!("zc-wal-unit-{}.jsonl", uuid::Uuid::new_v4()));
let legacy = |rid: &str, status: &str| {
format!(
r#"{{"request_id":"{rid}","user_id":"u","reservation_id":"x","estimated_cost":0.01,"actual_cost":0.004,"worker_id":"w","duration_ms":null,"timestamp":"2026-10-01T00:00:00Z","status":"{status}"}}"#
)
};
fs::write(
&path,
format!(
"{}\n{}\n",
legacy("open", "executed"),
legacy("done", "committed")
),
)
.unwrap();
for _ in 0..2 {
// Twice: the second open must not convert again.
let wal = Wal::open(&path).unwrap();
let pending = wal.read_uncommitted().unwrap();
assert_eq!(pending.len(), 1, "{pending:?}");
let e = &pending[0];
assert_eq!(e.request_id, "open");
assert_eq!(e.unit, "jpy");
assert!(
(e.estimated_cost - 1.5).abs() < 1e-9,
"{}",
e.estimated_cost
);
assert!((e.actual_cost.unwrap() - 0.6).abs() < 1e-9);
}
let on_disk = read_all_from_disk(&path).unwrap();
assert!(on_disk.iter().all(|e| e.unit == "jpy"), "{on_disk:?}");
assert!((on_disk[0].estimated_cost - 1.5).abs() < 1e-9);
let _ = fs::remove_file(&path);
}
#[test]
fn appended_entries_are_tagged_jpy() {
let path = std::env::temp_dir().join(format!("zc-wal-tag-{}.jsonl", uuid::Uuid::new_v4()));
let wal = Wal::open(&path).unwrap();
let mut e = entry("r-tag", WalStatus::Reserved);
e.unit = String::new();
wal.append(&e).unwrap();
wal.flush_buffer().unwrap();
let all = read_all_from_disk(&path).unwrap();
assert_eq!(all[0].unit, "jpy");
assert!(
(all[0].estimated_cost - 0.05).abs() < 1e-12,
"a tagged entry is never converted"
);
let _ = fs::remove_file(&path);
}
/// A line this build cannot parse (a newer build's status) survives
/// compaction verbatim instead of being erased (review L1 of #568).
#[test]
fn compaction_keeps_lines_it_cannot_parse() {
let path = tmp_wal("unknown_line");
cleanup(&path);
let future = r#"{"request_id":"x","status":"from_the_future"}"#;
fs::write(&path, format!("{future}\n")).unwrap();
let wal = Wal::open(&path).unwrap();
wal.append(&entry("req-done", WalStatus::Reserved)).unwrap();
wal.update_status("req-done", WalStatus::Committed, None, None)
.unwrap();
wal.compact().unwrap();
let text = fs::read_to_string(&path).unwrap();
assert!(text.contains(future), "{text}");
assert!(!text.contains("req-done"), "{text}");
cleanup(&path);
}
/// Kept through compaction: a closed job whose remote payout is still
/// owed. A delivered `/peer/earn` entry leaves the WAL but its id is
/// remembered in the side file; an owner's own earn is simply dropped.
#[test]
fn compaction_keeps_what_payouts_still_need() {
let path = tmp_wal("retain");
cleanup(&path);
let side = path.with_file_name("zc_wal_test_retain.earn-received.jsonl");
let _ = fs::remove_file(&side);
let wal = Wal::open(&path).unwrap();
wal.append(&entry("earn-r1", WalStatus::Earned)).unwrap();
wal.update_status("earn-r1", WalStatus::Committed, None, None)
.unwrap();
wal.append(&WalEntry {
reservation_id: PEER_EARN_MARK.to_string(),
..entry("earn-p1", WalStatus::Earned)
})
.unwrap();
wal.update_status("earn-p1", WalStatus::Committed, None, None)
.unwrap();
wal.append(&entry("job-r2", WalStatus::Executed)).unwrap();
wal.update_status("job-r2", WalStatus::Committed, None, None)
.unwrap();
wal.append(&entry("peer-earn-job-r2", WalStatus::EarnOwed))
.unwrap();
wal.append(&entry("job-r3", WalStatus::Executed)).unwrap();
wal.update_status("job-r3", WalStatus::Committed, None, None)
.unwrap();
wal.compact().unwrap();
drop(wal);
let wal = Wal::open(&path).unwrap();
assert!(wal.get("earn-r1").is_none());
assert!(
!wal.peer_earn_seen("earn-r1"),
"an owner earn is not remembered"
);
assert!(wal.get("earn-p1").is_none(), "not kept in the WAL");
assert!(wal.peer_earn_seen("earn-p1"), "remembered in the side file");
assert_eq!(wal.get("job-r2").unwrap().status, WalStatus::Committed);
assert!(wal.get("job-r3").is_none(), "nothing owed on it");
assert_eq!(wal.owed_payouts_summary().0, 1);
// Once the payout is settled, the job goes at the next compaction.
wal.update_status("peer-earn-job-r2", WalStatus::Committed, None, None)
.unwrap();
wal.compact().unwrap();
assert!(wal.get("job-r2").is_none());
assert_eq!(wal.owed_payouts_summary().0, 0);
assert!(!fs::read_to_string(&path).unwrap().contains("earn-p1"));
cleanup(&path);
let _ = fs::remove_file(&side);
}
/// The remembered ids are bounded by age and by count, oldest first, and
/// the file is rewritten once enough of it is stale.
#[test]
fn remembered_peer_earn_ids_are_bounded() {
let path = tmp_wal("received_bound");
let side = path.with_file_name("zc_wal_test_received_bound.earn-received.jsonl");
let old = Utc::now().timestamp() - EARN_DEDUPE_RETENTION.num_seconds() - 10;
fs::write(&side, format!("{{\"id\":\"earn-old\",\"ts\":{old}}}\n")).unwrap();
let mut r = EarnReceived::open(&path);
assert!(!r.contains("earn-old"), "past the age bound");
r.cap = 3;
let ids: Vec<String> = (0..5).map(|i| format!("earn-{i}")).collect();
r.remember(&ids).unwrap();
assert_eq!(r.len(), 3);
assert!(!r.contains("earn-0") && !r.contains("earn-1"));
assert!(r.contains("earn-4"));
r.compact().unwrap();
let text = fs::read_to_string(&side).unwrap();
assert_eq!(text.lines().count(), 3, "{text}");
let _ = fs::remove_file(&side);
}
/// `append_new` books a request_id once.
#[test]
fn append_new_is_a_check_and_insert() {
let path = tmp_wal("append_new");
cleanup(&path);
let wal = Wal::open(&path).unwrap();
assert!(wal.append_new(&entry("earn-z", WalStatus::Earned)).unwrap());
assert!(!wal.append_new(&entry("earn-z", WalStatus::Earned)).unwrap());
wal.flush_buffer().unwrap();
assert_eq!(read_all_from_disk(&path).unwrap().len(), 1);
cleanup(&path);
}
/// A hubless broker's entries are stamped; others are not, and the stamp
/// is not written when false (older builds read the line unchanged).
#[test]
fn entries_are_stamped_hubless_only_on_a_hubless_wal() {
let path = tmp_wal("hubless_stamp");
cleanup(&path);
let wal = Wal::open(&path).unwrap();
wal.append(&entry("a", WalStatus::Reserved)).unwrap();
wal.set_hubless(true);
wal.append(&entry("b", WalStatus::Reserved)).unwrap();
wal.update_status("a", WalStatus::Executed, None, None)
.unwrap();
wal.flush_buffer().unwrap();
let text = fs::read_to_string(&path).unwrap();
let lines: Vec<&str> = text.lines().collect();
assert!(!lines[0].contains("hubless"), "{text}");
assert!(lines[1].contains("\"hubless\":true"), "{text}");
assert!(lines[2].contains("\"hubless\":true"), "{text}");
cleanup(&path);
}
/// A line flushed while compaction runs is not lost by its rename: the
/// flush waits for the swap and lands in the new file (review round 3).
#[test]
fn a_line_flushed_during_compaction_survives_it() {
use std::sync::Arc;
let path = tmp_wal("compact_race");
cleanup(&path);
let wal = Arc::new(Wal::open(&path).unwrap());
wal.append(&entry("req-old", WalStatus::Reserved)).unwrap();
let handle: Arc<Mutex<Option<std::thread::JoinHandle<()>>>> = Arc::new(Mutex::new(None));
let (w, h) = (wal.clone(), handle.clone());
*wal.before_swap.lock().unwrap() = Some(Box::new(move || {
let w = w.clone();
*h.lock().unwrap() = Some(std::thread::spawn(move || {
w.append(&entry("req-racer", WalStatus::Reserved)).unwrap();
w.flush_buffer().unwrap();
}));
// Give the racer every chance to flush before the rename.
std::thread::sleep(std::time::Duration::from_millis(100));
}));
wal.compact().unwrap();
*wal.before_swap.lock().unwrap() = None;
handle.lock().unwrap().take().unwrap().join().unwrap();
let on_disk = read_all_from_disk(&path).unwrap();
assert!(
on_disk.iter().any(|e| e.request_id == "req-racer"),
"{on_disk:?}"
);
assert!(
on_disk.iter().any(|e| e.request_id == "req-old"),
"{on_disk:?}"
);
cleanup(&path);
}
/// A torn last line in the side file is cut off, so the next id is not
/// glued onto it.
#[test]
fn a_torn_side_file_line_does_not_swallow_the_next_id() {
let path = tmp_wal("torn_side");
let side = path.with_file_name("zc_wal_test_torn_side.earn-received.jsonl");
let now = Utc::now().timestamp();
fs::write(
&side,
format!("{{\"id\":\"earn-a\",\"ts\":{now}}}\n{{\"id\":\"earn-b\",\"ts"),
)
.unwrap();
let r = EarnReceived::open(&path);
assert!(r.contains("earn-a"));
r.remember(&["earn-c".to_string()]).unwrap();
drop(r);
let r = EarnReceived::open(&path);
assert!(r.contains("earn-a") && r.contains("earn-c"));
assert!(!r.contains("earn-b"));
let _ = fs::remove_file(&side);
}
/// When the side file cannot be written, compaction keeps the `/peer/earn`
/// entries in the WAL (the dedupe is not lost), counts the failure, and
/// still compacts the rest.
#[test]
fn a_failed_remember_keeps_the_earn_in_the_wal() {
let path = tmp_wal("remember_fails");
cleanup(&path);
let side = path.with_file_name("zc_wal_test_remember_fails.earn-received.jsonl");
let _ = fs::remove_file(&side);
let _ = fs::remove_dir_all(&side);
fs::create_dir_all(&side).unwrap(); // appends to it fail
let wal = Wal::open(&path).unwrap();
wal.append(&WalEntry {
reservation_id: PEER_EARN_MARK.to_string(),
..entry("earn-p", WalStatus::Earned)
})
.unwrap();
wal.update_status("earn-p", WalStatus::Committed, None, None)
.unwrap();
wal.append(&entry("req-done", WalStatus::Reserved)).unwrap();
wal.update_status("req-done", WalStatus::Committed, None, None)
.unwrap();
wal.compact().unwrap();
assert_eq!(wal.earn_dedupe_failures(), 1);
assert!(wal.peer_earn_seen("earn-p"), "still deduped from the WAL");
assert!(wal.get("req-done").is_none(), "the rest still compacted");
let _ = fs::remove_dir_all(&side);
cleanup(&path);
}
}