indicatrix-worker 0.7.2

Coordinator and render worker for an indicatrix-backed design catalogue. `serve` (default build) is the coordinator: it serves indicatrix-net's read-only design-library protocol to viewers over mutual TLS and accepts joining render workers on a separate worker port. The optional `worker` feature adds render capacity -- `join` (dial a coordinator and render its requests), `serve --render` (render with the coordinator's own CPU/GPU) and `render` (a one-shot scene-to-PNG CLI).
Documentation
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
//! `TILT_CURVES`: the single-request/single-response analytic tilt-performance sweep --
//! contrast with `RENDER`'s progressive, multi-message stream (`crate::stream_emit`).
//! See `indicatrix_net::messages::tilt`'s module docs for the wire types.
//!
//! [`handle_tilt_curves_request`] is the one entry point, called from
//! `super::connection`'s worker-build request loop where `RenderRequest` instead calls
//! `crate::stream_emit::run_stream`.
//!
//! # Runs inline, unlike `RenderRequest`
//!
//! `stream_emit::run_stream` splits tracing onto its own thread so a slow `write()`
//! never stalls sample production across a multi-second stream. A `TiltCurvesRequest`
//! writes exactly one ~8,688-byte reply at the end, so there is nothing to stall and the
//! thread split buys nothing. Measured cost is ~1.36s total (four axes, ~340ms each).
//!
//! # Cancellation: 4 checkpoints, ~340ms worst-case latency
//!
//! [`poll_for_cancel`] runs once before each axis rather than `stream_emit`'s continuous
//! polling loop -- there's nothing to report progress on between axes. A `CANCEL`
//! arriving mid-axis is only noticed at the next checkpoint, bounding worst-case
//! cancellation latency to one axis's duration (~340ms).
//!
//! # `ComputeMode` plays no role here
//!
//! `evaluate_full_axis_profile_at_azimuth` is a CPU-only analytic sweep with no GPU
//! kernel; `--only-gpu`/`--only-cpu` have nothing to change, so
//! [`handle_tilt_curves_request`] deliberately takes no `ComputeMode` parameter.
//!
//! # No pipelining
//!
//! Only one `TiltCurvesRequest` may be outstanding per connection (unlike
//! `RenderRequest`, which `run_stream` accepts pipelined as an implicit cancel).
//! [`poll_for_cancel`] logs and drops anything else pipelined mid-computation. A client
//! wanting concurrent tilt-curve requests opens more than one connection.

use crate::{stream_emit::TimeoutRead, validate};
use indicatrix_net::messages::{
    AxisTiltCurves, ErrorMsg, NetError, TILT_CURVE_AXIS_COUNT, TiltCurvesRequest,
    TiltCurvesResponse, TiltCurvesResult,
};
use std::{
    io::{Read, Write},
    time::Duration,
};

/// How long [`poll_for_cancel`] waits, per checkpoint, for a `CANCEL` that might already
/// be sitting in the socket's receive buffer. Short and non-looping: this runs exactly
/// once per checkpoint, so it only needs to catch what's already arrived over the
/// ~340ms since the previous one.
const CANCEL_POLL_TIMEOUT: Duration = Duration::from_millis(5);

/// What one [`poll_for_cancel`] check found.
pub enum CancelPoll {
    /// Nothing pending within the poll window.
    Pending,
    /// A `CANCEL` for this exact `request_id`.
    Cancelled,
    /// The peer closed the connection.
    Closed,
}

/// Checks whether a `CANCEL` for `request_id` is already sitting on `stream`'s socket
/// buffer, without blocking longer than [`CANCEL_POLL_TIMEOUT`].
///
/// Mirrors `crate::stream_emit`'s private `poll_for_client_message`: the length-prefix's
/// first byte is read with a raw, timeout-tolerant `read()` rather than `read_exact`
/// (whose docs leave it unspecified how many bytes land on an error), since a timeout
/// must never land mid-message. Once a byte is seen, the rest of that message is read
/// (bounded by `MAX_CONTROL_FRAME_LEN`) under a bounded timeout
/// (`FRAME_REMAINDER_TIMEOUT`) where a timeout IS a protocol error. The first byte's timeout tolerance goes through
/// [`crate::stream_emit::is_stream_timeout`] since a TLS stream's timeout can surface as
/// `WriteZero` even from a read.
///
/// Anything besides a matching `CANCEL` -- a stale `CANCEL`, or any other pipelined
/// `ClientMessage` -- is logged and dropped as [`CancelPoll::Pending`]: `TILT_CURVES`
/// supports no pipelining, and the connection's next ordinary read picks it up once this
/// reply has gone out. A dropped `ASSET` or `CONTRIBUTION` has its payload frame consumed
/// too, so the stream stays in sync.
///
/// # Errors
///
/// Returns [`NetError`] for a transport-level failure other than the tolerated timeout.
pub fn poll_for_cancel<S: Read + TimeoutRead>(
    stream: &mut S,
    request_id: u32,
) -> Result<CancelPoll, NetError> {
    stream
        .set_read_timeout(Some(CANCEL_POLL_TIMEOUT))
        .map_err(|e| NetError::Framing(indicatrix_net::framing::FramingError::Io(e)))?;

    let mut len_bytes = [0u8; indicatrix_net::framing::LEN_PREFIX_BYTES];
    let n = match stream.read(&mut len_bytes) {
        Ok(0) => return Ok(CancelPoll::Closed),
        Ok(n) => n,
        Err(e) if crate::stream_emit::is_stream_timeout(&e) => {
            return Ok(CancelPoll::Pending);
        }
        Err(e) => {
            return Err(NetError::Framing(
                indicatrix_net::framing::FramingError::Io(e),
            ));
        }
    };

    // At least one byte of a message has arrived -- commit to reading the rest of it
    // under a bounded timeout, not `None` (see this function's own doc comment).
    stream
        .set_read_timeout(Some(crate::stream_emit::FRAME_REMAINDER_TIMEOUT))
        .map_err(|e| NetError::Framing(indicatrix_net::framing::FramingError::Io(e)))?;
    let payload = indicatrix_net::framing::read_frame_continuing(
        stream,
        &len_bytes[..n],
        indicatrix_net::framing::MAX_CONTROL_FRAME_LEN,
    )?;

    let msg: indicatrix_net::messages::ClientMessage =
        indicatrix_net::messages::decode_control_frame(&payload)?;
    Ok(match msg {
        indicatrix_net::messages::ClientMessage::Cancel(c) if c.request_id == request_id => {
            CancelPoll::Cancelled
        }
        // An unrequested payload-carrying message: its payload frame follows and must be
        // consumed, or it would be misread as the next message.
        indicatrix_net::messages::ClientMessage::Asset(header) => {
            crate::assets::discard_asset(stream, &header)?;
            CancelPoll::Pending
        }
        indicatrix_net::messages::ClientMessage::Contribution(header) => {
            indicatrix_net::messages::discard_contribution_payload(stream, &header)?;
            CancelPoll::Pending
        }
        other => {
            tracing::debug!(
                "ignoring a message pipelined while request_id={request_id}'s tilt-curves \
                 computation was in flight (TILT_CURVES has no mid-request pipelining in this \
                 phase): {other:?}"
            );
            CancelPoll::Pending
        }
    })
}

/// Handles one `TiltCurvesRequest` end to end: validates the embedded scene, computes
/// all [`TILT_CURVE_AXIS_COUNT`] axes, and writes exactly one [`TiltCurvesResponse`] --
/// never a stream. See the module docs for why this runs inline, the cancellation
/// design, and why `ComputeMode` plays no role.
///
/// Validates with [`validate::validate_scene`] -- the same path `RenderRequest` uses, so
/// a rejected scene gets [`TiltCurvesResponse::Error`] carrying
/// `super::connection::VALIDATION_FAILED_CODE`, the same numeric code `RenderRequest`
/// uses in its own envelope.
///
/// Runs the per-axis evaluation inside `catch_unwind`, mirroring
/// `stream_emit::tracer::run_tracer`'s precedent: a pathological but validation-passing
/// scene is reported as [`TiltCurvesResponse::Error`] with
/// `super::connection::TRACE_PANIC_CODE`, not a crashed connection.
///
/// Restores `stream`'s read timeout to `None` (blocking) before returning, on every
/// return path: [`poll_for_cancel`] leaves either [`CANCEL_POLL_TIMEOUT`]
/// or [`crate::stream_emit::FRAME_REMAINDER_TIMEOUT`] applied to the socket, and this
/// connection's next `read_message` call (`super::connection`'s request loop) assumes a
/// blocking read exactly like every other message on this connection, same as before
/// this request started. A thin wrapper around [`handle_tilt_curves_request_inner`],
/// which does the actual work and may return early from several places -- restoring the
/// timeout once, here, after it returns (however it returns) is simpler and less
/// error-prone than duplicating the restore at each of those sites.
///
/// # Errors
///
/// Returns [`NetError`] for a transport-level failure while polling for `CANCEL` or
/// writing the reply. A validation failure or caught panic is NOT an error return --
/// both are reported as `TiltCurvesResponse::Error` and this returns `Ok(())`.
///
/// # Panics
///
/// Never panics in practice: the `unreachable!()` converting the axes `Vec` into a
/// fixed-size array is unreachable by construction (the `debug_assert_eq!` above the
/// loop pins the two independently-defined axis counts equal in every debug build).
pub fn handle_tilt_curves_request<S: Read + Write + TimeoutRead>(
    stream: &mut S,
    request: &TiltCurvesRequest,
) -> Result<(), NetError> {
    let result = handle_tilt_curves_request_inner(stream, request);
    // Best-effort, like `serve::apply_handshake_timeout`: a failed `set_read_timeout`
    // call is logged neither here nor there -- the inner result (the meaningful outcome
    // either way) is returned regardless, and a socket that can't have its timeout
    // changed will surface that on the connection's very next read.
    let _ = stream.set_read_timeout(None);
    result
}

/// The actual `TILT_CURVES` handling [`handle_tilt_curves_request`] wraps -- see that
/// function's doc comment for everything except the timeout-restore responsibility,
/// which deliberately lives in the wrapper, not here.
fn handle_tilt_curves_request_inner<S: Read + Write + TimeoutRead>(
    stream: &mut S,
    request: &TiltCurvesRequest,
) -> Result<(), NetError> {
    if let Err(message) = validate::validate_scene(&request.scene) {
        return indicatrix_net::messages::write_message(
            stream,
            &TiltCurvesResponse::Error(ErrorMsg {
                code: super::connection::VALIDATION_FAILED_CODE,
                message,
                request_id: Some(request.request_id),
            }),
        );
    }

    debug_assert_eq!(
        indicatrix::color::metrics::PROFILE_AZIMUTHS_DEG.len(),
        TILT_CURVE_AXIS_COUNT,
        "indicatrix's PROFILE_AZIMUTHS_DEG and indicatrix-net's independently-pinned \
         TILT_CURVE_AXIS_COUNT must agree -- see indicatrix_net::messages::tilt's module doc \
         comment for why the two are pinned separately rather than sharing one constant"
    );

    let mut axes: Vec<AxisTiltCurves> = Vec::with_capacity(TILT_CURVE_AXIS_COUNT);
    let scene = &request.scene;
    // The curves are scored under the scene's own lighting preset and light pose, the
    // radiance the same scene renders with (the stone's optics never see the exposure).
    let environment =
        scene
            .lighting_preset
            .studio(scene.exposure, scene.light_yaw, scene.light_pitch);

    for (axis_index, &azimuth_deg) in indicatrix::color::metrics::PROFILE_AZIMUTHS_DEG
        .iter()
        .enumerate()
    {
        match poll_for_cancel(stream, request.request_id)? {
            CancelPoll::Cancelled => {
                tracing::debug!(
                    "request_id={}: CANCEL honored after {} of {TILT_CURVE_AXIS_COUNT} axes",
                    request.request_id,
                    axes.len(),
                );
                return indicatrix_net::messages::write_message(
                    stream,
                    &TiltCurvesResponse::Cancelled {
                        request_id: request.request_id,
                    },
                );
            }
            CancelPoll::Closed => return Ok(()),
            CancelPoll::Pending => {}
        }

        let axis_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            indicatrix::color::metrics::evaluate_full_axis_profile_at_azimuth_geom(
                indicatrix::geometry::StoneGeometry {
                    planes: &scene.planes,
                    tools: &scene.tools,
                },
                &scene.material,
                azimuth_deg,
                environment,
            )
        }));

        if let Ok((brilliance_pct, extinction_pct, windowing_pct)) = axis_result {
            axes.push(AxisTiltCurves::from_arrays(
                brilliance_pct,
                extinction_pct,
                windowing_pct,
            ));
        } else {
            tracing::warn!(
                "tilt-curves computation panicked for a request that passed validation \
                 (request_id={}, axis_index={axis_index}, azimuth_deg={azimuth_deg})",
                request.request_id,
            );
            return indicatrix_net::messages::write_message(
                stream,
                &TiltCurvesResponse::Error(ErrorMsg {
                    code: super::connection::TRACE_PANIC_CODE,
                    message: "internal error while computing tilt-performance curves".to_string(),
                    request_id: Some(request.request_id),
                }),
            );
        }
    }

    let axes: [AxisTiltCurves; TILT_CURVE_AXIS_COUNT] = axes.try_into().unwrap_or_else(|v: Vec<_>| {
        unreachable!(
            "exactly TILT_CURVE_AXIS_COUNT={TILT_CURVE_AXIS_COUNT} axes were pushed above, got {}",
            v.len()
        )
    });

    indicatrix_net::messages::write_message(
        stream,
        &TiltCurvesResponse::Curves(Box::new(TiltCurvesResult {
            request_id: request.request_id,
            axes,
        })),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use indicatrix::{
        geometry::cuts::StandardGemCuts,
        optics::{materials::GemMaterial, raytracer::LightingPreset},
    };
    use indicatrix_net::{SceneState, messages::write_message};
    use std::io::Cursor;

    /// A minimal `Read + Write + TimeoutRead` double over two in-memory buffers,
    /// mirroring `super::super::tests::DuplexHalf` (kept separate rather than reaching
    /// across that module boundary). `closed` distinguishes "peer hung up" (`Ok(0)`
    /// even with a timeout active) from "nothing pending yet" (`WouldBlock`/`TimedOut`),
    /// since a bare `timeout_active` flag alone can't tell them apart.
    struct DuplexHalf {
        in_: Cursor<Vec<u8>>,
        out: Vec<u8>,
        timeout_active: bool,
        closed: bool,
    }

    impl DuplexHalf {
        const fn new(input: Vec<u8>) -> Self {
            Self {
                in_: Cursor::new(input),
                out: Vec::new(),
                timeout_active: false,
                closed: false,
            }
        }
    }

    impl Read for DuplexHalf {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            let n = self.in_.read(buf)?;
            if n == 0 && !self.closed && self.timeout_active {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::WouldBlock,
                    "DuplexHalf: no more scripted input (yet)",
                ));
            }
            Ok(n)
        }
    }

    impl Write for DuplexHalf {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.out.write(buf)
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl TimeoutRead for DuplexHalf {
        fn set_read_timeout(&mut self, duration: Option<Duration>) -> std::io::Result<()> {
            self.timeout_active = duration.is_some();
            Ok(())
        }
    }

    fn valid_scene() -> SceneState {
        SceneState {
            width: 4,
            height: 4,
            yaw: 0.4,
            pitch: 0.3,
            distance: 3.0,
            light_yaw: 0.85,
            light_pitch: 0.95,
            exposure: 1.0,
            max_bounces: 4,
            lighting_preset: LightingPreset::Daylight,
            material: GemMaterial::diamond(),
            planes: StandardGemCuts::standard_round_brilliant(),
            girdle_frosted: false,
            backdrop: 0.0,
            environment: indicatrix_net::scene::SceneEnvironment::Studio,
            surface_glare: 1.0,
            tools: Vec::new(),
            fluorescence: indicatrix::optics::fluorescence::Fluorescence::default(),
            head_shadow_deg: 16.0,
        }
    }

    fn read_response(out: &[u8]) -> TiltCurvesResponse {
        let mut cursor = Cursor::new(out.to_vec());
        indicatrix_net::messages::read_message(&mut cursor).unwrap()
    }

    #[test]
    fn rejects_an_invalid_scene_with_the_shared_validation_failed_code() {
        let mut scene = valid_scene();
        scene.planes.clear(); // fails validate_scene: planes must not be empty
        let request = TiltCurvesRequest {
            request_id: 1,
            scene,
        };
        let mut duplex = DuplexHalf::new(Vec::new());

        handle_tilt_curves_request(&mut duplex, &request).unwrap();

        let response = read_response(&duplex.out);
        match response {
            TiltCurvesResponse::Error(ErrorMsg { code, message, .. }) => {
                assert_eq!(code, super::super::connection::VALIDATION_FAILED_CODE);
                assert!(message.contains("planes"), "{message}");
            }
            other => panic!("expected TiltCurvesResponse::Error, got {other:?}"),
        }
    }

    #[test]
    fn a_matching_cancel_already_on_the_wire_is_honored_before_any_axis_computes() {
        let request = TiltCurvesRequest {
            request_id: 5,
            scene: valid_scene(),
        };
        // Already sitting in the input buffer; the first checkpoint must catch it.
        let mut cancel_bytes = Vec::new();
        write_message(
            &mut cancel_bytes,
            &indicatrix_net::messages::ClientMessage::Cancel(indicatrix_net::messages::Cancel {
                request_id: 5,
            }),
        )
        .unwrap();
        let mut duplex = DuplexHalf::new(cancel_bytes);

        handle_tilt_curves_request(&mut duplex, &request).unwrap();

        let response = read_response(&duplex.out);
        assert_eq!(response, TiltCurvesResponse::Cancelled { request_id: 5 });
    }

    #[test]
    fn a_cancel_for_a_different_request_id_is_ignored_and_the_request_completes() {
        let request = TiltCurvesRequest {
            request_id: 5,
            scene: valid_scene(),
        };
        let mut stale_cancel_bytes = Vec::new();
        write_message(
            &mut stale_cancel_bytes,
            &indicatrix_net::messages::ClientMessage::Cancel(indicatrix_net::messages::Cancel {
                request_id: 999,
            }),
        )
        .unwrap();
        let mut duplex = DuplexHalf::new(stale_cancel_bytes);

        handle_tilt_curves_request(&mut duplex, &request).unwrap();

        let response = read_response(&duplex.out);
        match response {
            TiltCurvesResponse::Curves(result) => {
                assert_eq!(result.request_id, 5);
                assert_eq!(result.axes.len(), TILT_CURVE_AXIS_COUNT);
            }
            other => panic!("expected TiltCurvesResponse::Curves, got {other:?}"),
        }
    }

    #[test]
    fn a_closed_connection_writes_nothing() {
        let request = TiltCurvesRequest {
            request_id: 1,
            scene: valid_scene(),
        };
        let mut duplex = DuplexHalf::new(Vec::new());
        duplex.closed = true; // simulates a peer that already hung up

        handle_tilt_curves_request(&mut duplex, &request).unwrap();
        assert!(
            duplex.out.is_empty(),
            "a peer that already closed the connection gets no reply written"
        );
    }

    /// Every return path must restore the socket's read timeout to `None`
    /// (blocking) before returning, since `poll_for_cancel` leaves a short timeout
    /// applied and this connection's next `read_message` call assumes a blocking read.
    /// Covers the three paths [`handle_tilt_curves_request_inner`] can take: a normal
    /// completion (this test), an invalid scene, and an honored `CANCEL`.
    #[test]
    fn read_timeout_is_restored_to_blocking_after_a_normal_completion() {
        let request = TiltCurvesRequest {
            request_id: 9,
            scene: valid_scene(),
        };
        let mut duplex = DuplexHalf::new(Vec::new());

        handle_tilt_curves_request(&mut duplex, &request).unwrap();

        assert!(
            !duplex.timeout_active,
            "the read timeout must be restored to None (blocking) once this request is done"
        );
    }

    #[test]
    fn read_timeout_is_restored_to_blocking_after_a_validation_failure() {
        let mut scene = valid_scene();
        scene.planes.clear();
        let request = TiltCurvesRequest {
            request_id: 10,
            scene,
        };
        let mut duplex = DuplexHalf::new(Vec::new());

        handle_tilt_curves_request(&mut duplex, &request).unwrap();

        assert!(!duplex.timeout_active);
    }

    #[test]
    fn read_timeout_is_restored_to_blocking_after_an_honored_cancel() {
        let request = TiltCurvesRequest {
            request_id: 11,
            scene: valid_scene(),
        };
        let mut cancel_bytes = Vec::new();
        write_message(
            &mut cancel_bytes,
            &indicatrix_net::messages::ClientMessage::Cancel(indicatrix_net::messages::Cancel {
                request_id: 11,
            }),
        )
        .unwrap();
        let mut duplex = DuplexHalf::new(cancel_bytes);

        handle_tilt_curves_request(&mut duplex, &request).unwrap();

        assert!(!duplex.timeout_active);
    }

    /// Pins that `poll_for_cancel` tolerates a `WriteZero` (which a real TLS stream can
    /// surface for a socket timeout even from a read) exactly like `WouldBlock`/
    /// `TimedOut`, rather than tearing the connection down.
    struct WriteZeroOnFirstRead;

    impl Read for WriteZeroOnFirstRead {
        fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
            Err(std::io::Error::new(
                std::io::ErrorKind::WriteZero,
                "scripted: TLS complete_io() swallowed an inner write timeout",
            ))
        }
    }

    impl TimeoutRead for WriteZeroOnFirstRead {
        fn set_read_timeout(&mut self, _duration: Option<Duration>) -> std::io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn poll_for_cancel_tolerates_a_write_zero_on_the_first_byte() {
        let mut stream = WriteZeroOnFirstRead;
        let result = poll_for_cancel(&mut stream, 1);
        assert!(
            matches!(result, Ok(CancelPoll::Pending)),
            "a WriteZero on the very first read must be tolerated as \"nothing pending \
             yet\", not a fatal protocol error"
        );
    }
}