rch 2.1.10

Remote Compilation Helper - PreToolUse hook CLI
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
//! Exercise the production dispatch boundary without changing process-wide env.
//! Socket peers script replies; they do not simulate actual worker execution.

use super::*;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::AsyncWrite;

const REQUEST: &[u8] = b"GET /select-worker?project=owner&cores=1\n";

async fn query_fixture(
    reply: &[u8],
    wait: bool,
    dry_run: bool,
) -> anyhow::Result<SelectionResponse> {
    let root = tempfile::tempdir().unwrap();
    let path = root.path().join("selection.sock");
    let listener = tokio::net::UnixListener::bind(&path).unwrap();
    let server = async {
        let (stream, _) = listener.accept().await.unwrap();
        let (reader, mut writer) = stream.into_split();
        let mut request = String::new();
        BufReader::new(reader)
            .read_line(&mut request)
            .await
            .unwrap();
        assert!(request.starts_with("GET /select-worker?"), "{request}");
        assert_eq!(request.contains("&wait=1"), wait);
        assert_eq!(request.contains("&dry_run=1"), dry_run);
        assert!(request.contains("&local_wrapper_id=selection-test-owner"));
        // Oversized replies may be rejected before all bytes are written.
        let _ = writer.write_all(reply).await;
    };
    let client = query_daemon_with_mode(
        path.to_str().unwrap(),
        "owner",
        1,
        "cargo build",
        None,
        RequiredRuntime::None,
        CommandPriority::Normal,
        0,
        Some(std::process::id()),
        Some("selection-test-owner"),
        wait,
        &[],
        false,
        &[],
        dry_run,
    );
    let (result, ()) = timeout(Duration::from_secs(3), async {
        tokio::join!(client, server)
    })
    .await
    .expect("selection fixture must terminate");
    assert!(
        timeout(Duration::from_millis(20), listener.accept())
            .await
            .is_err(),
        "no automatic retry or compensating request after a lost result"
    );
    result
}

#[tokio::test]
async fn lost_invalid_and_oversized_replies_fence_both_queued_and_immediate_selection() {
    let _guard = rch_common::test_guard!();
    let mut oversized = b"HTTP/1.1 200 OK\r\n\r\n".to_vec();
    oversized.extend(vec![b'x'; MAX_DAEMON_BODY_BYTES + 1]);
    for reply in [
        Vec::new(),
        b"HTTP/1.1 200 OK\r\n".to_vec(),
        b"HTTP/1.1 503 Busy\r\n\r\n{}".to_vec(),
        b"HTTP/1.1 200 OK\r\n\r\n{".to_vec(),
        b"HTTP/1.1 200 OK\r\n\r\n{}".to_vec(),
        b"HTTP/1.1 200 OK\r\n\r\n\xff".to_vec(),
        oversized,
    ] {
        for wait in [false, true] {
            for dry_run in [false, true] {
                let error = query_fixture(&reply, wait, dry_run).await.unwrap_err();
                assert_eq!(
                    error
                        .downcast_ref::<SelectionOutcomeUnconfirmed>()
                        .is_some(),
                    !dry_run,
                    "wait={wait}, dry_run={dry_run}, reply={reply:?}: {error:#}"
                );
            }
        }
    }
}

#[tokio::test]
async fn confirmed_busy_and_cancellation_results_remain_ordinary_responses() {
    let _guard = rch_common::test_guard!();
    for reason in [
        SelectionReason::AllWorkersBusy,
        SelectionReason::NoWorkersConfigured,
        SelectionReason::SelectionError("job_cancelled_before_start".into()),
    ] {
        let reply = format!(
            "HTTP/1.1 200 OK\r\n\r\n{}",
            serde_json::to_string(&SelectionResponse {
                worker: None,
                reason: reason.clone(),
                build_id: None,
                diagnostics: None,
            })
            .unwrap()
        );
        for wait in [false, true] {
            let response = query_fixture(reply.as_bytes(), wait, false).await.unwrap();
            assert_eq!(response.reason, reason);
            assert!(response.worker.is_none() && response.build_id.is_none());
        }
    }
}

#[tokio::test]
async fn failures_before_connect_do_not_invent_unconfirmed_ownership() {
    let _guard = rch_common::test_guard!();
    let root = tempfile::tempdir().unwrap();
    let missing = root.path().join("missing.sock");
    let refused = root.path().join("refused.sock");
    // Dropping the listener leaves a socket path with nobody accepting it.
    drop(std::os::unix::net::UnixListener::bind(&refused).unwrap());
    for path in [&missing, &refused] {
        for wait in [false, true] {
            let error = query_daemon(
                path.to_str().unwrap(),
                "owner",
                1,
                "cargo build",
                None,
                RequiredRuntime::None,
                CommandPriority::Normal,
                0,
                None,
                Some("selection-test-owner"),
                wait,
                &[],
                false,
                &[],
            )
            .await
            .unwrap_err();
            assert!(
                error
                    .downcast_ref::<SelectionOutcomeUnconfirmed>()
                    .is_none()
            );
        }
    }
}

/// Models a transport accepting the complete request, then failing its flush.
/// Error means delivery is unconfirmed, not that the bytes were not delivered.
#[derive(Default)]
struct FailedFlush {
    received: Vec<u8>,
}

impl AsyncWrite for FailedFlush {
    fn poll_write(
        mut self: Pin<&mut Self>,
        _: &mut Context<'_>,
        bytes: &[u8],
    ) -> Poll<std::io::Result<usize>> {
        self.received.extend_from_slice(bytes);
        Poll::Ready(Ok(bytes.len()))
    }

    fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        Poll::Ready(Err(std::io::Error::new(
            std::io::ErrorKind::BrokenPipe,
            "flush failed",
        )))
    }

    fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        Poll::Ready(Ok(()))
    }
}

#[tokio::test]
async fn fully_written_request_followed_by_failed_flush_remains_uncertain() {
    for dry_run in [false, true] {
        let mut writer = FailedFlush::default();
        let error = exchange_selection_request(
            tokio::io::empty(),
            &mut writer,
            REQUEST,
            Duration::from_secs(1),
            Duration::from_secs(1),
            dry_run,
        )
        .await
        .unwrap_err()
        .context("outer caller context");
        assert_eq!(writer.received, REQUEST);
        assert_eq!(
            error
                .downcast_ref::<SelectionOutcomeUnconfirmed>()
                .is_some(),
            !dry_run
        );
        assert_eq!(
            error.downcast_ref::<std::io::Error>().unwrap().kind(),
            std::io::ErrorKind::BrokenPipe
        );
    }
}

#[tokio::test]
async fn stalled_dispatch_and_silent_reply_keep_the_uncertainty_boundary() {
    let (mut writer, mut peer) = tokio::io::duplex(8);
    let error = exchange_selection_request(
        tokio::io::empty(),
        &mut writer,
        REQUEST,
        Duration::from_millis(20),
        Duration::from_secs(1),
        false,
    )
    .await
    .unwrap_err();
    assert!(
        error
            .downcast_ref::<SelectionOutcomeUnconfirmed>()
            .is_some()
    );
    assert!(format!("{error:#}").contains("request write timed out"));
    drop(writer);
    let mut bytes = Vec::new();
    peer.read_to_end(&mut bytes).await.unwrap();
    assert_eq!(bytes, REQUEST[..8]);

    let (reader, _silent_peer) = tokio::io::duplex(8);
    let mut writer = Vec::new();
    let error = exchange_selection_request(
        reader,
        &mut writer,
        REQUEST,
        Duration::from_secs(1),
        Duration::from_millis(20),
        false,
    )
    .await
    .unwrap_err();
    assert!(
        error
            .downcast_ref::<SelectionOutcomeUnconfirmed>()
            .is_some()
    );
    assert!(format!("{error:#}").contains("response timed out"));
    assert_eq!(writer, REQUEST);
}

/// The first reply names a worker outside the requested allow-set. Capture
/// every follow-up request so a preview cannot silently mutate daemon state.
async fn unrequested_fixture(
    dry_run: bool,
    build_id: Option<u64>,
    acknowledgement: &[u8],
) -> (anyhow::Result<SelectionResponse>, Vec<String>) {
    let root = tempfile::tempdir().unwrap();
    let path = root.path().join("assignment.sock");
    let listener = tokio::net::UnixListener::bind(&path).unwrap();
    let server = async {
        let (stream, _) = listener.accept().await.unwrap();
        let (reader, mut writer) = stream.into_split();
        let mut first = String::new();
        BufReader::new(reader).read_line(&mut first).await.unwrap();
        assert!(first.contains("&worker=requested-worker"));
        assert_eq!(first.contains("&dry_run=1"), dry_run);
        let reply = serde_json::json!({
            "worker": {
                "id": "unrequested-worker", "host": "localhost", "user": "test",
                "identity_file": "/no-test-key", "slots_available": 2, "speed_score": 1.0
            },
            "reason": "success",
            "build_id": build_id,
        });
        writer
            .write_all(format!("HTTP/1.1 200 OK\r\n\r\n{reply}").as_bytes())
            .await
            .unwrap();
        drop(writer);
        let mut requests = vec![first];
        if let Ok(Ok((stream, _))) = timeout(Duration::from_millis(100), listener.accept()).await {
            let (reader, mut writer) = stream.into_split();
            let mut request = String::new();
            BufReader::new(reader)
                .read_line(&mut request)
                .await
                .unwrap();
            requests.push(request);
            let _ = writer.write_all(acknowledgement).await;
        }
        assert!(
            timeout(Duration::from_millis(20), listener.accept())
                .await
                .is_err()
        );
        requests
    };
    let requested = [WorkerId::new("requested-worker")];
    let client = query_daemon_with_mode(
        path.to_str().unwrap(),
        "owner",
        2,
        "cargo build",
        None,
        RequiredRuntime::None,
        CommandPriority::Normal,
        0,
        Some(std::process::id()),
        Some("selection-test-owner"),
        false,
        &requested,
        false,
        &[],
        dry_run,
    );
    timeout(Duration::from_secs(3), async {
        tokio::join!(client, server)
    })
    .await
    .expect("assignment refusal must terminate")
}

#[tokio::test]
async fn diagnostic_worker_mismatch_never_sends_a_release() {
    let _guard = rch_common::test_guard!();
    for build_id in [None, Some(42), Some(u64::MAX)] {
        let (result, requests) = unrequested_fixture(true, build_id, b"HTTP/1.1 200 OK\r\n").await;
        let response = result.unwrap();
        assert_eq!(response.reason, SelectionReason::NoMatchingWorkers);
        assert!(response.worker.is_none() && response.build_id.is_none());
        assert_eq!(
            requests.len(),
            1,
            "a preview must remain read-only: {requests:?}"
        );
    }
}

#[tokio::test]
async fn real_worker_mismatch_requires_an_identity_bound_acknowledged_release() {
    let _guard = rch_common::test_guard!();
    let (result, requests) = unrequested_fixture(false, Some(42), b"HTTP/1.1 200 OK\r\n").await;
    let response = result.unwrap();
    assert_eq!(response.reason, SelectionReason::NoMatchingWorkers);
    assert!(response.worker.is_none() && response.build_id.is_none());
    assert_eq!(requests.len(), 2);
    assert!(
        requests[1]
            .starts_with("POST /release-worker?worker=unrequested-worker&slots=2&build_id=42")
    );
    assert!(requests[1].contains("&local_wrapper_id=selection-test-owner"));
    assert!(requests[1].contains(&format!("&exit_code={EXIT_BUILD_ERROR}")));
}

#[tokio::test]
async fn unowned_mismatched_assignment_cannot_fall_back_or_release_by_slot_count() {
    let _guard = rch_common::test_guard!();
    for build_id in [None, Some(0), Some(1_u64 << 63), Some(u64::MAX)] {
        let (result, requests) = unrequested_fixture(false, build_id, b"HTTP/1.1 200 OK\r\n").await;
        let error = result.unwrap_err();
        assert!(
            error
                .downcast_ref::<SelectionOutcomeUnconfirmed>()
                .is_some()
        );
        assert!(format!("{error:#}").contains("no valid active build identity"));
        assert_eq!(
            requests.len(),
            1,
            "never guess which reservation to release"
        );
    }
}

#[tokio::test]
async fn unacknowledged_mismatch_release_preserves_uncertainty_and_correlation() {
    let _guard = rch_common::test_guard!();
    for ack in [
        b"".as_slice(),
        b"HTTP/1.1 500 Failed\r\n",
        b"HTTP/1.1 200 OK",
    ] {
        let (result, requests) = unrequested_fixture(false, Some(42), ack).await;
        let error = result.unwrap_err();
        assert!(
            error
                .downcast_ref::<SelectionOutcomeUnconfirmed>()
                .is_some()
        );
        let message = format!("{error:#}");
        assert!(message.contains("unrequested-worker build 42"), "{message}");
        assert!(message.contains("not acknowledged"), "{message}");
        assert_eq!(
            requests.len(),
            2,
            "one attempted release, no selection replay"
        );
    }
}