zc2 0.0.52

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
//! Expected `/peer/earn` records (ZC-0012, earn binding).
//!
//! An executor that ran a paid job for a peer remembers, per request id, what
//! it charged (`cost`) and who asked (the requester's node fingerprint, when
//! known). When the requester later sends `/peer/earn` for that request id,
//! `handle_peer_earn` checks the earn against the record: without one an
//! earn is a claim about a job this node never ran.
//!
//! Memory first, bounded by age and count. The side file beside the WAL
//! (`<wal>.earn-expected.jsonl`) only keeps the records across a restart: lines
//! are queued on the request path and appended by the broker's periodic loop
//! ([`flush`](ExpectedEarns::flush)), so no request ever waits on a write or an
//! fsync. A crash can lose the last few seconds of records; in `observe` mode
//! that is a counter, which is why enforcement is opt-in.

use std::collections::VecDeque;
use std::io::Write;
use std::path::PathBuf;
use std::sync::Mutex;

use crossbeam_queue::SegQueue;
use dashmap::DashMap;
use serde::{Deserialize, Serialize};

/// How long a record is kept: as long as the executor remembers a booked earn.
pub const RETENTION_SECS: i64 = super::wal::EARN_DEDUPE_RETENTION.num_seconds();
/// At most this many records; the oldest go first.
pub const CAP: usize = 200_000;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Expected {
    pub id: String,
    pub cost: f64,
    /// The requester's node fingerprint (bare hex), when the transport
    /// authenticated it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requester_fp: Option<String>,
    pub ts: i64,
    /// The hub receipt that bound this earn when no job of this node's own
    /// backed it (`earn_receipt`). One receipt backs one earn.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub receipt_hash: Option<String>,
}

/// How an incoming earn relates to what this executor ran.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EarnClass {
    Bound,
    /// No record on this node, but the requester's debit receipt from the hub
    /// verified and covers it (`earn_receipt`).
    BoundByReceipt,
    UnknownJob,
    OverAmount,
    WrongRequester,
}

impl EarnClass {
    pub fn code(self) -> &'static str {
        match self {
            Self::Bound => "bound",
            Self::BoundByReceipt => "bound_by_receipt",
            Self::UnknownJob => "unknown_job",
            Self::OverAmount => "over_amount",
            Self::WrongRequester => "wrong_requester",
        }
    }
}

/// Rounding slack: the requester derives its payout from the cost this
/// executor reported, through a 6-decimal split.
pub(super) fn epsilon(cost: f64) -> f64 {
    1e-6 + cost.abs() * 1e-6
}

/// Pure classification of an earn of `amount` signed by `signer_fp`.
pub fn classify(expected: Option<&Expected>, amount: f64, signer_fp: Option<&str>) -> EarnClass {
    let Some(e) = expected else {
        return EarnClass::UnknownJob;
    };
    if amount > e.cost + epsilon(e.cost) {
        return EarnClass::OverAmount;
    }
    if let (Some(want), Some(got)) = (e.requester_fp.as_deref(), signer_fp) {
        if want != got {
            return EarnClass::WrongRequester;
        }
    }
    EarnClass::Bound
}

pub struct ExpectedEarns {
    path: Option<PathBuf>,
    map: DashMap<String, Expected>,
    /// receipt hash -> the request id it backs (rebuilt from `map`).
    receipts: DashMap<String, String>,
    order: Mutex<VecDeque<(String, i64)>>,
    queue: SegQueue<String>,
    cap: usize,
    /// Lines in the file beyond the live records, to decide when to compact.
    appended: std::sync::atomic::AtomicUsize,
    file_lock: Mutex<()>,
}

impl ExpectedEarns {
    pub fn in_memory() -> Self {
        Self::with(None, CAP)
    }

    /// Open the side file next to the WAL at `wal_path`.
    pub fn open(wal_path: &std::path::Path) -> Self {
        let name = wal_path
            .file_stem()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| "wal".into());
        Self::open_at(
            wal_path.with_file_name(format!("{name}.earn-expected.jsonl")),
            CAP,
        )
    }

    fn open_at(path: PathBuf, cap: usize) -> Self {
        let me = Self::with(Some(path.clone()), cap);
        let bytes = std::fs::read(&path).unwrap_or_default();
        // A kill mid-append can leave a torn last line; cut back to the last
        // complete one so the next append is not glued onto it.
        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) = std::fs::OpenOptions::new().write(true).open(&path) {
                let _ = f.set_len(keep as u64);
            }
        }
        let now = chrono::Utc::now().timestamp();
        for l in String::from_utf8_lossy(&bytes).lines() {
            if let Ok(e) = serde_json::from_str::<Expected>(l) {
                me.insert(e, now);
            }
        }
        me.appended.store(0, std::sync::atomic::Ordering::Relaxed);
        me
    }

    fn with(path: Option<PathBuf>, cap: usize) -> Self {
        Self {
            path,
            map: DashMap::new(),
            receipts: DashMap::new(),
            order: Mutex::new(VecDeque::new()),
            queue: SegQueue::new(),
            cap,
            appended: std::sync::atomic::AtomicUsize::new(0),
            file_lock: Mutex::new(()),
        }
    }

    fn insert(&self, e: Expected, now: i64) {
        let mut order = self.order.lock().unwrap_or_else(|p| p.into_inner());
        // A re-recorded id gets a second order entry; the first no longer matches
        // the stored `ts`, so evicting it removes nothing.
        if let Some(h) = &e.receipt_hash {
            self.receipts.insert(h.clone(), e.id.clone());
        }
        self.map.insert(e.id.clone(), e.clone());
        order.push_back((e.id.clone(), e.ts));
        let cutoff = now - RETENTION_SECS;
        while let Some((id, ts)) = order.front().cloned() {
            if ts >= cutoff && order.len() <= self.cap {
                break;
            }
            order.pop_front();
            // Only drop the record this order entry stands for.
            if let Some((_, gone)) = self.map.remove_if(&id, |_, v| v.ts == ts) {
                if let Some(h) = gone.receipt_hash {
                    self.receipts.remove_if(&h, |_, rid| *rid == id);
                }
            }
        }
    }

    /// Remember that this executor ran `request_id` for `cost`. Never does I/O.
    pub fn record(&self, request_id: &str, cost: f64, requester_fp: Option<&str>) {
        let now = chrono::Utc::now().timestamp();
        let e = Expected {
            id: request_id.to_string(),
            cost,
            requester_fp: requester_fp
                .map(|f| super::node_identity::strip_node_arg(f).to_string())
                .filter(|f| !f.is_empty()),
            ts: now,
            receipt_hash: None,
        };
        if let Ok(line) = serde_json::to_string(&e) {
            self.queue.push(line);
        }
        self.insert(e, now);
    }

    /// Bind `request_id`'s earn to hub receipt `receipt_hash`, recording the
    /// amount the receipt settled. Atomic on the receipt: `false` when it
    /// already backs a DIFFERENT request id (a resend of the same one is fine).
    pub fn bind_receipt(
        &self,
        request_id: &str,
        receipt_hash: &str,
        settled: f64,
        requester_fp: Option<&str>,
    ) -> bool {
        use dashmap::mapref::entry::Entry;
        match self.receipts.entry(receipt_hash.to_string()) {
            Entry::Occupied(o) if o.get() != request_id => return false,
            Entry::Occupied(_) => {}
            Entry::Vacant(v) => {
                v.insert(request_id.to_string());
            }
        }
        let now = chrono::Utc::now().timestamp();
        // A resend that carries no signature keeps the requester the first one did.
        let requester_fp = requester_fp
            .map(|f| super::node_identity::strip_node_arg(f).to_string())
            .filter(|f| !f.is_empty())
            .or_else(|| self.get(request_id).and_then(|e| e.requester_fp));
        let e = Expected {
            id: request_id.to_string(),
            cost: settled,
            requester_fp,
            ts: now,
            receipt_hash: Some(receipt_hash.to_string()),
        };
        if let Ok(line) = serde_json::to_string(&e) {
            self.queue.push(line);
        }
        self.insert(e, now);
        true
    }

    /// The request id a receipt already backs, if any.
    pub fn receipt_backs(&self, receipt_hash: &str) -> Option<String> {
        self.receipts.get(receipt_hash).map(|r| r.clone())
    }

    pub fn get(&self, request_id: &str) -> Option<Expected> {
        self.map.get(request_id).map(|e| e.clone())
    }

    pub fn len(&self) -> usize {
        self.map.len()
    }

    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Append the queued lines to the side file (called by the periodic loop,
    /// not by a request), compacting it once it has grown to twice its live size.
    pub fn flush(&self) {
        let Some(path) = &self.path else {
            while self.queue.pop().is_some() {}
            return;
        };
        let _io = self.file_lock.lock().unwrap_or_else(|e| e.into_inner());
        let mut lines = Vec::new();
        while let Some(l) = self.queue.pop() {
            lines.push(l);
        }
        if !lines.is_empty() {
            if let Some(dir) = path.parent() {
                let _ = std::fs::create_dir_all(dir);
            }
            if let Ok(mut f) = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)
            {
                let mut buf = lines.join("\n");
                buf.push('\n');
                if f.write_all(buf.as_bytes()).is_ok() {
                    let _ = f.sync_data();
                    self.appended
                        .fetch_add(lines.len(), std::sync::atomic::Ordering::Relaxed);
                }
            }
        }
        let live = self.map.len();
        if self.appended.load(std::sync::atomic::Ordering::Relaxed) > live * 2 + 1024 {
            let mut live_recs: Vec<Expected> = self.map.iter().map(|e| e.clone()).collect();
            live_recs.sort_by_key(|e| e.ts);
            let mut out = String::new();
            for e in &live_recs {
                if let Ok(l) = serde_json::to_string(e) {
                    out.push_str(&l);
                    out.push('\n');
                }
            }
            let tmp = path.with_extension("tmp");
            if std::fs::write(&tmp, out).is_ok() && std::fs::rename(&tmp, path).is_ok() {
                self.appended.store(0, std::sync::atomic::Ordering::Relaxed);
            }
        }
    }
}

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

    fn rec(cost: f64, fp: Option<&str>) -> Expected {
        Expected {
            id: "r".into(),
            cost,
            requester_fp: fp.map(String::from),
            ts: 0,
            receipt_hash: None,
        }
    }

    #[test]
    fn classification() {
        assert_eq!(classify(None, 1.0, Some("a")), EarnClass::UnknownJob);
        let e = rec(1.0, Some("aaaa"));
        assert_eq!(classify(Some(&e), 0.9, Some("aaaa")), EarnClass::Bound);
        assert_eq!(classify(Some(&e), 1.0, Some("aaaa")), EarnClass::Bound);
        assert_eq!(
            classify(Some(&e), 1.0000001, Some("aaaa")),
            EarnClass::Bound
        );
        assert_eq!(classify(Some(&e), 1.5, Some("aaaa")), EarnClass::OverAmount);
        assert_eq!(
            classify(Some(&e), 0.5, Some("bbbb")),
            EarnClass::WrongRequester
        );
        // either side unknown: the signer is not compared
        assert_eq!(classify(Some(&e), 0.5, None), EarnClass::Bound);
        assert_eq!(
            classify(Some(&rec(1.0, None)), 0.5, Some("bbbb")),
            EarnClass::Bound
        );
    }

    #[test]
    fn records_are_bounded_by_count_and_replaced_by_id() {
        let q = ExpectedEarns::with(None, 3);
        for i in 0..5 {
            q.record(&format!("r{i}"), 1.0, None);
        }
        assert_eq!(q.len(), 3);
        assert!(q.get("r0").is_none() && q.get("r1").is_none());
        assert!(q.get("r4").is_some());
        q.record("r4", 2.0, Some("zc://node-abcd"));
        let e = q.get("r4").unwrap();
        assert_eq!((e.cost, e.requester_fp.as_deref()), (2.0, Some("abcd")));
    }

    #[test]
    fn records_survive_a_restart_through_the_side_file_and_flush_is_the_only_io() {
        let dir = std::env::temp_dir().join(format!("zc-ee-{}-{}", std::process::id(), line!()));
        std::fs::create_dir_all(&dir).unwrap();
        let wal = dir.join("wal.jsonl");
        let q = ExpectedEarns::open(&wal);
        q.record("job-1", 0.25, Some("ffff"));
        let side = dir.join("wal.earn-expected.jsonl");
        assert!(!side.exists(), "recording never touches the disk");
        q.flush();
        assert!(side.exists());
        let q2 = ExpectedEarns::open(&wal);
        let e = q2.get("job-1").expect("reloaded");
        assert_eq!((e.cost, e.requester_fp.as_deref()), (0.25, Some("ffff")));
        // a torn trailing line is cut, not glued
        let mut s = std::fs::read_to_string(&side).unwrap();
        s.push_str("{\"id\":\"torn");
        std::fs::write(&side, s).unwrap();
        let q3 = ExpectedEarns::open(&wal);
        q3.record("job-2", 1.0, None);
        q3.flush();
        let q4 = ExpectedEarns::open(&wal);
        assert!(q4.get("job-1").is_some() && q4.get("job-2").is_some());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_receipt_backs_one_earn_and_that_survives_a_restart() {
        let dir = std::env::temp_dir().join(format!("zc-ee-{}-{}", std::process::id(), line!()));
        std::fs::create_dir_all(&dir).unwrap();
        let wal = dir.join("wal.jsonl");
        let q = ExpectedEarns::open(&wal);
        let h = "c".repeat(64);
        assert!(q.bind_receipt("job-1", &h, 2.0, Some("zc://node-ffff")));
        // a resend of the same request id is the same earn
        assert!(q.bind_receipt("job-1", &h, 2.0, None));
        // another request id cannot spend it again
        assert!(!q.bind_receipt("job-2", &h, 2.0, None));
        assert_eq!(q.receipt_backs(&h).as_deref(), Some("job-1"));
        let e = q.get("job-1").unwrap();
        assert_eq!((e.cost, e.requester_fp.as_deref()), (2.0, Some("ffff")));
        assert!(q.get("job-2").is_none(), "a refused bind records nothing");
        q.flush();

        let q2 = ExpectedEarns::open(&wal);
        assert_eq!(q2.receipt_backs(&h).as_deref(), Some("job-1"));
        assert!(!q2.bind_receipt("job-3", &h, 2.0, None));
        assert_eq!(
            q2.get("job-1").unwrap().receipt_hash.as_deref(),
            Some(h.as_str())
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn an_evicted_record_frees_its_receipt() {
        let q = ExpectedEarns::with(None, 2);
        let (a, b) = ("a".repeat(64), "b".repeat(64));
        assert!(q.bind_receipt("r0", &a, 1.0, None));
        q.record("r1", 1.0, None);
        q.record("r2", 1.0, None); // pushes r0 out (cap 2)
        assert!(q.get("r0").is_none());
        assert_eq!(q.receipt_backs(&a), None);
        assert!(q.bind_receipt("r9", &a, 1.0, None));
        assert!(q.bind_receipt("r10", &b, 1.0, None));
    }
}