zc2 0.0.48

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
//! Batch framing: many tasks per round trip, results streamed back as they
//! finish.
//!
//! On a mesh the round trip is the cost. A worker answers `add(2, 3)` in about
//! a millisecond while the trip to reach it takes 780 — so one task per request
//! caps a requester at `concurrency ÷ RTT` however fast the fleet is, and no
//! placement policy moves that ceiling. Carrying N tasks per trip divides it by
//! N.
//!
//! Binary rather than JSON: payloads are cloudpickle, and base64 would inflate
//! every one of them by a third on exactly the links where bandwidth is a real
//! term.

use std::time::Duration;

/// Batch request magic. Bumped when the framing changes shape.
pub(crate) const MAGIC: &[u8; 4] = b"ZKB1";

/// Largest single payload or requirements blob a frame may declare, and the
/// largest task count. Lengths arrive as `u32` from an untrusted peer; without
/// a cap, one four-byte field asks us to allocate four gigabytes.
pub(crate) const MAX_FIELD_BYTES: u32 = 64 * 1024 * 1024;
pub(crate) const MAX_TASKS: u32 = 10_000;

/// One task on the way out.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct BatchTask {
    pub id: u32,
    /// Per-task requirements override. Empty means "inherit the batch's
    /// `X-Zakuro-Requirements`", which is the common case and keeps a batch of
    /// identical tasks from repeating itself N times.
    pub requirements: Vec<u8>,
    pub payload: Vec<u8>,
}

/// How one task turned out.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ResultStatus {
    Ok,
    Failed,
}

/// One task on the way back. Frames arrive in completion order, not
/// submission order, and are matched by `id`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct BatchResult {
    pub id: u32,
    pub status: ResultStatus,
    pub body: Vec<u8>,
}

/// Why a frame could not be read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CodecError {
    BadMagic,
    Truncated,
    /// The body held more than the declared task count. Sender and receiver
    /// disagree about framing, which is corruption, not a short read.
    TrailingBytes(usize),
    DuplicateId(u32),
    TooLarge {
        field: &'static str,
        len: u32,
    },
    BadStatus(u8),
}

pub(crate) fn encode_request(tasks: &[BatchTask]) -> Vec<u8> {
    let mut out = Vec::with_capacity(
        8 + tasks
            .iter()
            .map(|t| 12 + t.requirements.len() + t.payload.len())
            .sum::<usize>(),
    );
    out.extend_from_slice(MAGIC);
    out.extend_from_slice(&(tasks.len() as u32).to_le_bytes());
    for t in tasks {
        out.extend_from_slice(&t.id.to_le_bytes());
        out.extend_from_slice(&(t.requirements.len() as u32).to_le_bytes());
        out.extend_from_slice(&t.requirements);
        out.extend_from_slice(&(t.payload.len() as u32).to_le_bytes());
        out.extend_from_slice(&t.payload);
    }
    out
}

/// Reads fields without ever trusting a length far enough to allocate on it.
struct Cursor<'a> {
    bytes: &'a [u8],
    at: usize,
}

pub(crate) fn decode_request(bytes: &[u8]) -> Result<Vec<BatchTask>, CodecError> {
    if bytes.len() < MAGIC.len() || &bytes[..MAGIC.len()] != MAGIC {
        return Err(CodecError::BadMagic);
    }
    let mut c = Cursor {
        bytes,
        at: MAGIC.len(),
    };
    let count = c.u32()?;
    if count > MAX_TASKS {
        return Err(CodecError::TooLarge {
            field: "count",
            len: count,
        });
    }

    let mut tasks = Vec::with_capacity(count as usize);
    let mut seen = std::collections::HashSet::with_capacity(count as usize);
    for _ in 0..count {
        let id = c.u32()?;
        if !seen.insert(id) {
            return Err(CodecError::DuplicateId(id));
        }
        let requirements = c.blob("requirements")?;
        let payload = c.blob("payload")?;
        tasks.push(BatchTask {
            id,
            requirements,
            payload,
        });
    }
    match bytes.len() - c.at {
        0 => Ok(tasks),
        extra => Err(CodecError::TrailingBytes(extra)),
    }
}

pub(crate) fn encode_result(result: &BatchResult) -> Vec<u8> {
    let mut out = Vec::with_capacity(9 + result.body.len());
    out.extend_from_slice(&result.id.to_le_bytes());
    out.push(match result.status {
        ResultStatus::Ok => 0,
        ResultStatus::Failed => 1,
    });
    out.extend_from_slice(&(result.body.len() as u32).to_le_bytes());
    out.extend_from_slice(&result.body);
    out
}

/// Read whatever complete result frames `bytes` holds, and say how many bytes
/// were consumed.
///
/// A streamed reply arrives in pieces: the caller keeps the unconsumed tail and
/// tries again when more arrives. A trailing partial frame is not an error.
pub(crate) fn decode_results(bytes: &[u8]) -> Result<(Vec<BatchResult>, usize), CodecError> {
    const HEADER: usize = 4 + 1 + 4;
    let mut out = Vec::new();
    let mut at = 0usize;
    while bytes.len() - at >= HEADER {
        let id = u32::from_le_bytes(bytes[at..at + 4].try_into().expect("4 bytes"));
        let status = match bytes[at + 4] {
            0 => ResultStatus::Ok,
            1 => ResultStatus::Failed,
            other => return Err(CodecError::BadStatus(other)),
        };
        let len = u32::from_le_bytes(bytes[at + 5..at + 9].try_into().expect("4 bytes"));
        if len > MAX_FIELD_BYTES {
            return Err(CodecError::TooLarge {
                field: "result",
                len,
            });
        }
        let end = at + HEADER + len as usize;
        if end > bytes.len() {
            break; // the rest of this frame has not arrived yet
        }
        out.push(BatchResult {
            id,
            status,
            body: bytes[at + HEADER..end].to_vec(),
        });
        at = end;
    }
    Ok((out, at))
}

/// How many tasks the next batch should carry.
///
/// The broker decides this, not a flag: it is the only party that knows how
/// fast its workers are answering and how many of them are free. A batch wants
/// to be big enough that the fleet is still busy when the next one arrives —
/// `slots × rtt / service` — and no bigger, because a larger batch holds more
/// money reserved and loses more work when a connection drops.
pub(crate) fn batch_hint(
    rtt: Duration,
    service_p50: Duration,
    worker_slots: usize,
    cap: usize,
) -> usize {
    let cap = cap.max(1);
    // Nothing free to keep busy, and no trip worth amortising: one task.
    if worker_slots == 0 || rtt.is_zero() {
        return 1;
    }
    // Service time not measured yet. Assume it is fast rather than slow — a
    // wrong guess downward costs a round trip, a wrong guess upward costs
    // nothing but a larger first batch.
    if service_p50.is_zero() {
        return cap;
    }
    let want = worker_slots as f64 * rtt.as_secs_f64() / service_p50.as_secs_f64();
    (want.ceil() as usize).clamp(1, cap)
}

impl Cursor<'_> {
    fn take(&mut self, n: usize) -> Result<&[u8], CodecError> {
        let end = self.at.checked_add(n).ok_or(CodecError::Truncated)?;
        let slice = self.bytes.get(self.at..end).ok_or(CodecError::Truncated)?;
        self.at = end;
        Ok(slice)
    }

    fn u32(&mut self) -> Result<u32, CodecError> {
        Ok(u32::from_le_bytes(
            self.take(4)?.try_into().expect("take(4) yields 4 bytes"),
        ))
    }

    /// A length-prefixed blob, with the length checked against the ceiling
    /// BEFORE it is used to size anything.
    fn blob(&mut self, field: &'static str) -> Result<Vec<u8>, CodecError> {
        let len = self.u32()?;
        if len > MAX_FIELD_BYTES {
            return Err(CodecError::TooLarge { field, len });
        }
        Ok(self.take(len as usize)?.to_vec())
    }
}

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

    fn task(id: u32, payload: &[u8]) -> BatchTask {
        BatchTask {
            id,
            requirements: Vec::new(),
            payload: payload.to_vec(),
        }
    }

    // ---- request framing -------------------------------------------------

    #[test]
    fn a_batch_survives_the_round_trip() {
        let tasks = vec![
            task(1, b"\x80\x05K\x05."),
            BatchTask {
                id: 2,
                requirements: br#"{"cpus":4.0}"#.to_vec(),
                payload: b"payload two".to_vec(),
            },
            task(3, b""),
        ];
        let wire = encode_request(&tasks);
        assert_eq!(decode_request(&wire).unwrap(), tasks);
    }

    #[test]
    fn an_empty_batch_is_legal_and_round_trips() {
        let wire = encode_request(&[]);
        assert_eq!(decode_request(&wire).unwrap(), Vec::new());
    }

    /// The common case: every task shares the batch's requirements, so each
    /// frame carries none. A fifty-task batch must not repeat them fifty
    /// times.
    #[test]
    fn tasks_inheriting_the_batch_requirements_cost_no_bytes_for_them() {
        let inherited = encode_request(&[task(1, b"x"), task(2, b"y")]);
        let overridden = encode_request(&[
            BatchTask {
                id: 1,
                requirements: br#"{"cpus":4.0}"#.to_vec(),
                payload: b"x".to_vec(),
            },
            task(2, b"y"),
        ]);
        assert_eq!(
            overridden.len() - inherited.len(),
            r#"{"cpus":4.0}"#.len(),
            "an inherited requirement costs its length field and nothing else"
        );
    }

    #[test]
    fn something_that_is_not_a_batch_is_refused_before_anything_is_allocated() {
        assert_eq!(
            decode_request(b"<html>nope</html>"),
            Err(CodecError::BadMagic)
        );
        assert_eq!(decode_request(b""), Err(CodecError::BadMagic));
    }

    /// Every prefix of a real batch must be refused rather than read as a
    /// shorter one — a truncated frame is the shape a dropped connection
    /// produces, and reading it as valid would silently lose tasks.
    #[test]
    fn every_truncation_of_a_batch_is_refused() {
        let wire = encode_request(&[task(1, b"hello"), task(2, b"world")]);
        for cut in 0..wire.len() {
            let err = decode_request(&wire[..cut]).unwrap_err();
            assert!(
                matches!(err, CodecError::BadMagic | CodecError::Truncated),
                "prefix of {cut} bytes gave {err:?}"
            );
        }
        assert!(decode_request(&wire).is_ok(), "the whole thing still reads");
    }

    /// Ids match results to tasks. Two tasks with the same id would make a
    /// result ambiguous, so the batch is refused rather than half-delivered.
    #[test]
    fn a_repeated_id_is_refused() {
        let wire = encode_request(&[task(7, b"a"), task(7, b"b")]);
        assert_eq!(decode_request(&wire), Err(CodecError::DuplicateId(7)));
    }

    /// A length field is four bytes from a stranger. Believing one without a
    /// ceiling turns a 12-byte request into a 4 GiB allocation.
    #[test]
    fn an_absurd_length_is_refused_rather_than_allocated() {
        let mut wire = Vec::new();
        wire.extend_from_slice(MAGIC);
        wire.extend_from_slice(&1u32.to_le_bytes()); // count
        wire.extend_from_slice(&1u32.to_le_bytes()); // id
        wire.extend_from_slice(&0u32.to_le_bytes()); // req_len
        wire.extend_from_slice(&u32::MAX.to_le_bytes()); // payload_len
        assert_eq!(
            decode_request(&wire),
            Err(CodecError::TooLarge {
                field: "payload",
                len: u32::MAX
            })
        );
    }

    #[test]
    fn an_absurd_task_count_is_refused_before_the_loop() {
        let mut wire = Vec::new();
        wire.extend_from_slice(MAGIC);
        wire.extend_from_slice(&u32::MAX.to_le_bytes());
        assert_eq!(
            decode_request(&wire),
            Err(CodecError::TooLarge {
                field: "count",
                len: u32::MAX
            })
        );
    }

    /// A count that promises more than the body holds is a truncation, and
    /// must not yield the tasks that happened to fit.
    #[test]
    fn a_count_larger_than_the_body_is_a_truncation() {
        let mut wire = encode_request(&[task(1, b"a")]);
        wire[4..8].copy_from_slice(&3u32.to_le_bytes());
        assert_eq!(decode_request(&wire), Err(CodecError::Truncated));
    }

    /// More body than the count declared means the two ends disagree about
    /// framing. Reading the tasks that parsed and discarding the rest would
    /// silently drop work, so the batch is refused whole.
    #[test]
    fn a_body_longer_than_the_declared_count_is_refused() {
        let mut wire = encode_request(&[task(1, b"a")]);
        wire.extend_from_slice(b"leftover");
        assert_eq!(decode_request(&wire), Err(CodecError::TrailingBytes(8)));
    }

    // ---- result framing (streamed) ---------------------------------------

    #[test]
    fn a_result_survives_the_round_trip() {
        let r = BatchResult {
            id: 9,
            status: ResultStatus::Ok,
            body: b"\x80\x05K\x05.".to_vec(),
        };
        let (got, used) = decode_results(&encode_result(&r)).unwrap();
        assert_eq!(got, vec![r.clone()]);
        assert_eq!(used, encode_result(&r).len());
    }

    /// Results are read as they arrive. A buffer holding two whole frames and
    /// the first half of a third yields two results and says how much it
    /// consumed, so the caller can keep the remainder and try again.
    #[test]
    fn a_partial_trailing_frame_is_kept_for_later_not_treated_as_an_error() {
        let a = BatchResult {
            id: 1,
            status: ResultStatus::Ok,
            body: b"first".to_vec(),
        };
        let b = BatchResult {
            id: 2,
            status: ResultStatus::Failed,
            body: b"worker raised".to_vec(),
        };
        let mut buf = encode_result(&a);
        buf.extend_from_slice(&encode_result(&b));
        let whole = buf.len();
        buf.extend_from_slice(
            &encode_result(&BatchResult {
                id: 3,
                status: ResultStatus::Ok,
                body: b"incomplete".to_vec(),
            })[..4],
        );

        let (got, used) = decode_results(&buf).unwrap();
        assert_eq!(got, vec![a, b]);
        assert_eq!(used, whole, "only the complete frames are consumed");
    }

    #[test]
    fn nothing_yet_is_not_an_error() {
        assert_eq!(decode_results(b"").unwrap(), (Vec::new(), 0));
    }

    #[test]
    fn an_unknown_status_byte_is_refused() {
        let mut wire = encode_result(&BatchResult {
            id: 1,
            status: ResultStatus::Ok,
            body: b"x".to_vec(),
        });
        wire[4] = 99;
        assert_eq!(decode_results(&wire), Err(CodecError::BadStatus(99)));
    }

    #[test]
    fn a_result_claiming_an_absurd_body_is_refused() {
        let mut wire = Vec::new();
        wire.extend_from_slice(&1u32.to_le_bytes()); // id
        wire.push(0); // status Ok
        wire.extend_from_slice(&u32::MAX.to_le_bytes()); // len
        assert_eq!(
            decode_results(&wire),
            Err(CodecError::TooLarge {
                field: "result",
                len: u32::MAX
            })
        );
    }

    // ---- how big the next batch should be --------------------------------

    const CAP: usize = 512;

    /// The rule: keep the fleet busy while the next batch is in flight. Eight
    /// slots answering in 10ms across a 800ms trip need 640 tasks to stay fed
    /// — clamped by the cap, which exists so one reservation never holds an
    /// unbounded amount of money.
    #[test]
    fn the_hint_keeps_the_fleet_fed_across_one_round_trip() {
        assert_eq!(
            batch_hint(
                Duration::from_millis(800),
                Duration::from_millis(10),
                8,
                CAP
            ),
            CAP
        );
        assert_eq!(
            batch_hint(
                Duration::from_millis(800),
                Duration::from_millis(100),
                4,
                CAP
            ),
            32
        );
    }

    /// On a broker that is already here there is no trip to amortise, so
    /// batching buys nothing and the rule says so by itself rather than
    /// needing to be turned off.
    #[test]
    fn a_local_broker_is_told_not_to_batch() {
        assert_eq!(
            batch_hint(Duration::ZERO, Duration::from_millis(1), 32, CAP),
            1
        );
    }

    /// Slow work amortises the trip on its own; a batch of one is already
    /// keeping the worker busy longer than the trip takes.
    #[test]
    fn work_slower_than_the_round_trip_needs_no_batching() {
        assert_eq!(
            batch_hint(Duration::from_millis(800), Duration::from_secs(30), 1, CAP),
            1
        );
    }

    /// Degenerate inputs must give a usable batch size, never zero (which
    /// would stall the client) and never a division by zero.
    #[test]
    fn degenerate_inputs_still_give_a_usable_size() {
        assert_eq!(
            batch_hint(Duration::from_millis(800), Duration::ZERO, 8, CAP),
            CAP,
            "unmeasured service time means we do not know it is slow"
        );
        assert_eq!(
            batch_hint(
                Duration::from_millis(800),
                Duration::from_millis(10),
                0,
                CAP
            ),
            1,
            "no free slots: ask for one task, not none"
        );
        assert_eq!(
            batch_hint(Duration::from_millis(800), Duration::from_millis(10), 8, 0),
            1,
            "a zero cap must not mean a zero batch"
        );
    }
}