varta-watch 0.2.0

Varta observer — receives VLP frames and surfaces stalls.
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
//! Integration tests for Observer socket lifecycle — M5 (bind races) and M7
//! (Drop unlinks socket file).
//!
//! Each test uses a unique socket path derived from the process id and an
//! atomic counter so parallel `cargo test` runs cannot collide.

use std::io::ErrorKind;
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
use std::os::unix::net::UnixDatagram;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use varta_watch::listener::{drain_bind_dir_fsync_failures, PreThreadAttestation};
use varta_watch::tracker::DEFAULT_EVICTION_SCAN_WINDOW;
use varta_watch::{ClockSource, EvictionPolicy, Observer};

/// Return a token that skips the single-thread probe.
///
/// Tests run inside a multi-threaded test runner; the umask window is benign
/// because each test uses a unique socket path and no concurrent thread in
/// the test process creates files at those paths.
///
/// # Safety
/// Callers must ensure no concurrent thread creates filesystem objects at the
/// socket path during the `Observer::bind` window, which is true by
/// construction in this isolated test module.
#[allow(unsafe_code)]
fn pre_thread() -> PreThreadAttestation {
    // SAFETY: documented above.
    unsafe { PreThreadAttestation::new_unchecked() }
}

static COUNTER: AtomicU64 = AtomicU64::new(0);

fn unique_path(label: &str) -> PathBuf {
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    std::env::temp_dir().join(format!(
        "varta-obs-{}-{}-{}.sock",
        std::process::id(),
        label,
        n
    ))
}

const THRESHOLD: Duration = Duration::from_secs(1);

/// M5 baseline — Observer::bind creates the socket file with correct permissions.
#[test]
fn bind_succeeds_on_clean_path() {
    let path = unique_path("clean");
    assert!(!path.exists(), "path must not pre-exist");

    let _obs = Observer::bind(
        &path,
        THRESHOLD,
        0o600,
        Duration::from_millis(100),
        0,
        64,
        EvictionPolicy::Strict,
        DEFAULT_EVICTION_SCAN_WINDOW,
        None,
        0,
        0,
        ClockSource::Monotonic,
        &pre_thread(),
    )
    .expect("bind on clean path should succeed");

    assert!(path.exists(), "socket file must exist after bind");
    let meta = std::fs::metadata(&path).expect("metadata");
    assert!(meta.file_type().is_socket(), "must be a socket");
    assert_eq!(
        meta.permissions().mode() & 0o777,
        0o600,
        "permissions must be 0o600"
    );

    drop(_obs);
    assert!(
        !path.exists(),
        "socket file must be removed on observer drop"
    );
}

/// M5 contract — a second bind to a path with a live listener returns AddrInUse
/// with the exact error-message prefix.
#[test]
fn bind_fails_when_live_observer_present() {
    let path = unique_path("live");

    let _first = Observer::bind(
        &path,
        THRESHOLD,
        0o600,
        Duration::from_millis(100),
        0,
        64,
        EvictionPolicy::Strict,
        DEFAULT_EVICTION_SCAN_WINDOW,
        None,
        0,
        0,
        ClockSource::Monotonic,
        &pre_thread(),
    )
    .expect("first bind must succeed");

    let err = Observer::bind(
        &path,
        THRESHOLD,
        0o600,
        Duration::from_millis(100),
        0,
        64,
        EvictionPolicy::Strict,
        DEFAULT_EVICTION_SCAN_WINDOW,
        None,
        0,
        0,
        ClockSource::Monotonic,
        &pre_thread(),
    )
    .err()
    .expect("second bind on live socket must fail");

    assert_eq!(err.kind(), ErrorKind::AddrInUse);
    assert!(
        err.to_string()
            .contains("another varta-watch is already running at "),
        "error message mismatch: {err}"
    );

    drop(_first);
    let _ = std::fs::remove_file(&path);
}

/// M5 contract — a stale socket inode at the path is removed and replaced by
/// the observer's socket.
#[test]
fn bind_cleans_up_stale_socket_file() {
    let path = unique_path("stale");

    let stale = UnixDatagram::bind(&path).expect("create stale socket");
    drop(stale);
    assert!(
        std::fs::metadata(&path)
            .expect("stale socket metadata")
            .file_type()
            .is_socket(),
        "test setup must leave a stale socket inode"
    );

    let _obs = Observer::bind(
        &path,
        THRESHOLD,
        0o600,
        Duration::from_millis(100),
        0,
        64,
        EvictionPolicy::Strict,
        DEFAULT_EVICTION_SCAN_WINDOW,
        None,
        0,
        0,
        ClockSource::Monotonic,
        &pre_thread(),
    )
    .expect("bind over stale socket must succeed");

    let meta = std::fs::metadata(&path).expect("metadata");
    assert!(
        meta.file_type().is_socket(),
        "stale file must be replaced by socket"
    );

    drop(_obs);
    let _ = std::fs::remove_file(&path);
}

/// M5 safety constraint — a non-socket occupant is not a stale observer
/// socket and must never be unlinked by bind recovery.
#[test]
fn bind_preserves_non_socket_file_at_path() {
    let path = unique_path("regular-file");

    std::fs::write(&path, b"do not delete").expect("create regular file");

    let err = Observer::bind(
        &path,
        THRESHOLD,
        0o600,
        Duration::from_millis(100),
        0,
        64,
        EvictionPolicy::Strict,
        DEFAULT_EVICTION_SCAN_WINDOW,
        None,
        0,
        0,
        ClockSource::Monotonic,
        &pre_thread(),
    )
    .err()
    .expect("bind over regular file must fail");

    assert_eq!(err.kind(), ErrorKind::AddrInUse);
    assert!(
        err.to_string().contains("path exists and is not a socket"),
        "error message mismatch: {err}"
    );
    assert_eq!(
        std::fs::read(&path).expect("regular file must be preserved"),
        b"do not delete"
    );

    let _ = std::fs::remove_file(&path);
}

/// M7 contract — dropping an Observer removes its bound socket file from disk.
/// Cleanup is owned by the UdsListener inside the Observer.
#[test]
fn drop_unlinks_bound_socket() {
    let path = unique_path("drop-unlink");

    let obs = Observer::bind(
        &path,
        THRESHOLD,
        0o600,
        Duration::from_millis(100),
        0,
        64,
        EvictionPolicy::Strict,
        DEFAULT_EVICTION_SCAN_WINDOW,
        None,
        0,
        0,
        ClockSource::Monotonic,
        &pre_thread(),
    )
    .expect("bind must succeed");

    assert!(path.exists(), "socket must exist after bind");

    drop(obs);
    assert!(!path.exists(), "socket must be removed after observer drop");
}

/// M7 contract — if the socket file is manually removed before the
/// Observer is dropped, the drop completes silently without panicking.
#[test]
fn drop_swallows_missing_file() {
    let path = unique_path("drop-missing");

    let obs = Observer::bind(
        &path,
        THRESHOLD,
        0o600,
        Duration::from_millis(100),
        0,
        64,
        EvictionPolicy::Strict,
        DEFAULT_EVICTION_SCAN_WINDOW,
        None,
        0,
        0,
        ClockSource::Monotonic,
        &pre_thread(),
    )
    .expect("bind must succeed");

    std::fs::remove_file(&path).expect("manual remove");
    assert!(!path.exists());

    drop(obs);
}

/// Bind on a tempdir path must not increment the dir-fsync failure counter.
/// Asserts that fsync_parent_dir runs and succeeds on a normal filesystem.
#[test]
fn bind_fsyncs_parent_directory_without_error() {
    let path = unique_path("dirfsync");
    let pre = drain_bind_dir_fsync_failures();

    let _obs = Observer::bind(
        &path,
        THRESHOLD,
        0o600,
        Duration::from_millis(100),
        0,
        64,
        EvictionPolicy::Strict,
        DEFAULT_EVICTION_SCAN_WINDOW,
        None,
        0,
        0,
        ClockSource::Monotonic,
        &pre_thread(),
    )
    .expect("bind must succeed and dir-fsync must not error");

    let post = drain_bind_dir_fsync_failures();
    assert_eq!(
        post, pre,
        "dir-fsync must not have failed on a normal tempdir"
    );
    drop(_obs);
}

/// Stale-recovery bind path must also fsync the parent directory without error.
#[test]
fn bind_fsyncs_parent_directory_after_stale_recovery() {
    let path = unique_path("dirfsync-stale");

    let stale = UnixDatagram::bind(&path).expect("create stale socket");
    drop(stale);

    let pre = drain_bind_dir_fsync_failures();

    let _obs = Observer::bind(
        &path,
        THRESHOLD,
        0o600,
        Duration::from_millis(100),
        0,
        64,
        EvictionPolicy::Strict,
        DEFAULT_EVICTION_SCAN_WINDOW,
        None,
        0,
        0,
        ClockSource::Monotonic,
        &pre_thread(),
    )
    .expect("stale-recovery bind must succeed and dir-fsync must not error");

    let post = drain_bind_dir_fsync_failures();
    assert_eq!(
        post, pre,
        "dir-fsync must not have failed on a normal tempdir (stale-recovery path)"
    );
    drop(_obs);
    let _ = std::fs::remove_file(&path);
}

/// PreThreadAttestation — the happy path (single-threaded process) is validated
/// by the production binary itself: `main.rs` calls `PreThreadAttestation::new()?`
/// as its very first statement. If that call returned an error, the binary would
/// refuse to start.  No integration-test can replicate a truly single-threaded
/// process because the test harness spawns infrastructure threads before the
/// first test function runs; any probe here would falsely detect multi-threadedness.
#[test]
// JUSTIFY: cargo test harness is multi-threaded; success case verified at production startup.
#[ignore = "probe always fails in the multi-threaded test harness; \
            the success case is validated by the production binary startup"]
fn pre_thread_attestation_succeeds_when_single_threaded() {
    let _tok = PreThreadAttestation::new().expect("single-threaded probe must succeed");
}

/// PreThreadAttestation — the probe must reject a multi-threaded process.
#[test]
fn pre_thread_attestation_rejects_multi_threaded_process() {
    // Park a background thread so the process has ≥ 2 threads.
    let barrier = std::sync::Arc::new(std::sync::Barrier::new(2));
    let b2 = std::sync::Arc::clone(&barrier);
    let handle = std::thread::spawn(move || {
        b2.wait(); // signal that we are running
        std::thread::park();
    });
    barrier.wait(); // wait until the spawned thread is alive

    let result = PreThreadAttestation::new();

    handle.thread().unpark();
    let _ = handle.join();

    // On Linux and macOS the probe must hard-error.
    // On other platforms it is best-effort (no probe), so we skip the assertion.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    {
        let err = result.expect_err("multi-threaded process must be rejected");
        assert!(
            err.to_string().contains("multi-threaded"),
            "error message must mention multi-threaded, got: {err}"
        );
    }
    // On platforms without a probe, result is Ok — no assertion needed.
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    let _ = result;
}

/// M7 constraint #6 — if another Observer has won the path (different inode),
/// the original Observer's Drop must NOT remove the foreign file.
#[test]
fn drop_preserves_foreign_inode() {
    let path = unique_path("drop-inode");

    let obs_a = Observer::bind(
        &path,
        THRESHOLD,
        0o600,
        Duration::from_millis(100),
        0,
        64,
        EvictionPolicy::Strict,
        DEFAULT_EVICTION_SCAN_WINDOW,
        None,
        0,
        0,
        ClockSource::Monotonic,
        &pre_thread(),
    )
    .expect("first bind must succeed");

    std::fs::remove_file(&path).expect("manual remove for inode swap");

    let obs_b = Observer::bind(
        &path,
        THRESHOLD,
        0o600,
        Duration::from_millis(100),
        0,
        64,
        EvictionPolicy::Strict,
        DEFAULT_EVICTION_SCAN_WINDOW,
        None,
        0,
        0,
        ClockSource::Monotonic,
        &pre_thread(),
    )
    .expect("second bind must succeed");

    drop(obs_a);
    assert!(
        path.exists(),
        "drop of stale observer must not remove the current (foreign) socket"
    );

    drop(obs_b);
    assert!(
        !path.exists(),
        "drop of current observer must remove the socket"
    );
}