kernal-api 0.1.14

Async OS HAL, profiling, symbolization, and allocator instrumentation
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
//! Native authenticated entry-to-Blob bridge on the tracked archive job lane.
use super::*;
use std::io;

impl OperationHub {
    pub(crate) fn submit_archive_entry_open(
        self: &Arc<Self>,
        runtime: crate::async_engine::RuntimeHandle,
        store: u64,
        entry: OpaqueToken,
    ) -> Result<OpaqueToken, HubError> {
        let producer_runtime = runtime.clone();
        self.submit_archive_work(
            runtime,
            store,
            (
                entry,
                archive_inventory::ENTRY_KIND,
                archive_inventory::ENTRY_RIGHT,
            ),
            move |hub, operation| {
                let (archive, index) = {
                    let state = hub.state.lock().map_err(|_| HubError::Closed)?;
                    let slot = state.resources.get(&entry).ok_or(HubError::Closed)?;
                    Self::validate_resource(
                        slot,
                        store,
                        archive_inventory::ENTRY_KIND,
                        archive_inventory::ENTRY_RIGHT,
                    )?;
                    let ResourceValue::ArchiveEntry(entry) = &slot.value else {
                        return Err(HubError::WrongKind);
                    };
                    (Arc::clone(&entry.archive), entry.index)
                };
                let mut sink = NativeArchiveSink::new(Arc::clone(hub), producer_runtime, store)?;
                let mut state = hub.state.lock().map_err(|_| HubError::Closed)?;
                if !state.resources.contains_key(&entry)
                    || state
                        .operations
                        .get(&operation)
                        .is_none_or(|slot| slot.terminal.is_some())
                {
                    return Err(HubError::Closed);
                }
                state
                    .operations
                    .get_mut(&operation)
                    .ok_or(HubError::Closed)?
                    .created_resource = Some(sink.blob());
                let notify = Self::terminal_locked(
                    &mut state,
                    operation,
                    TerminalResult {
                        terminal: Terminal::Completed,
                        resource: Some(sink.blob()),
                    },
                )?;
                // Transfer entry authority exactly once. Publication must
                // precede copying: the consumer releases producer capacity.
                let notifications =
                    Self::close_resource_with_terminal_locked(&mut state, entry, Terminal::Closed)?;
                drop(state);
                if let Some(notify) = notify {
                    notify.notify_one();
                }
                for notify in notifications {
                    notify.notify_one();
                }
                {
                    // Never acquire this reader mutex while holding hub state.
                    let mut reader = archive.lock().map_err(|_| HubError::Closed)?;
                    reader
                        .reader
                        .copy_entry(index, &mut sink)
                        .map_err(|_| HubError::Invalid)?;
                }
                // Successful EOF only follows a fully checked entry copy.
                sink.finish().map_err(|_| HubError::Closed)
            },
        )
    }
}

/// Producer authority is this non-cloneable value, never a consumer token.
/// Constructed only alongside a new read-only blob; no token-adoption method.
struct NativeArchiveSink {
    hub: Arc<OperationHub>,
    runtime: crate::async_engine::RuntimeHandle,
    store: u64,
    blob: OpaqueToken,
    failed: bool,
    finished: bool,
}

impl NativeArchiveSink {
    fn new(
        hub: Arc<OperationHub>,
        runtime: crate::async_engine::RuntimeHandle,
        store: u64,
    ) -> Result<Self, HubError> {
        let blob = hub.create_resource_value(
            store,
            BLOB_RESOURCE_KIND,
            BLOB_RIGHT_READ,
            false,
            ResourceValue::Blob {
                buffer: VecDeque::new(),
                sealed: false,
            },
        )?;
        {
            let mut state = hub.state.lock().map_err(|_| HubError::Closed)?;
            state
                .resources
                .get_mut(&blob)
                .ok_or(HubError::Closed)?
                .reserved = false;
        }
        Ok(Self {
            hub,
            runtime,
            store,
            blob,
            failed: false,
            finished: false,
        })
    }

    fn blob(&self) -> OpaqueToken {
        self.blob
    }

    /// Called from the supplied runtime's blocking worker. The owned reader
    /// retains authenticated staging while bounded writes wait for capacity.
    fn copy_archive(
        mut self,
        mut reader: crate::archive::authenticated_staging::AuthenticatedReader,
        index: usize,
    ) -> io::Result<u64> {
        let copied = reader.copy_entry(index, &mut self)?;
        self.finish()?;
        Ok(copied)
    }

    fn finish(&mut self) -> io::Result<()> {
        if self.failed || self.finished {
            return Err(io::ErrorKind::BrokenPipe.into());
        }
        self.failed = true;
        self.hub
            .seal_blob_checked(self.store, self.blob, BLOB_RIGHT_READ)
            .map_err(transfer_error)?;
        self.failed = false;
        self.finished = true;
        Ok(())
    }
}

fn transfer_error(error: HubError) -> io::Error {
    io::Error::new(
        io::ErrorKind::BrokenPipe,
        format!("archive blob transfer: {error:?}"),
    )
}

struct PendingArchiveWrite<'a> {
    hub: &'a OperationHub,
    store: u64,
    operation: OpaqueToken,
}

impl Drop for PendingArchiveWrite<'_> {
    fn drop(&mut self) {
        // Collection may already have removed it. Otherwise revoke both the
        // operation and retained bytes on every early return or unwind.
        let _ = self
            .hub
            .abandon_transfer_wire(self.store, self.operation.wire());
    }
}

impl io::Write for NativeArchiveSink {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        if self.failed || self.finished {
            return Err(io::ErrorKind::BrokenPipe.into());
        }
        if bytes.is_empty() {
            return Ok(0);
        }
        self.failed = true;
        let count = bytes.len().min(self.hub.blob_limits.maximum_chunk_bytes);
        // Only the private producer reaches this path. Ordinary guest writes
        // always require WRITE rights; the consumer has READ rights only.
        let operation = self
            .hub
            .submit_blob_write_checked(self.store, self.blob, count, BLOB_RIGHT_READ, || {
                bytes[..count].to_vec()
            })
            .map_err(transfer_error)?;
        let pending = PendingArchiveWrite {
            hub: &self.hub,
            store: self.store,
            operation,
        };
        self.runtime
            .block_on_wasm(async {
                loop {
                    if let Some(result) = self.hub.observe_terminal(self.store, operation)? {
                        return if result.terminal == Terminal::Completed {
                            Ok(())
                        } else {
                            Err(HubError::Closed)
                        };
                    }
                    // suspend handles completion between observation and waiter
                    // registration. No hub mutex is held while waiting.
                    self.hub
                        .wait_external_operation(self.store, operation)?
                        .notified()
                        .await;
                }
            })
            .map_err(transfer_error)?;
        drop(pending);
        self.failed = false;
        Ok(count)
    }

    fn flush(&mut self) -> io::Result<()> {
        if self.failed {
            Err(io::ErrorKind::BrokenPipe.into())
        } else {
            Ok(())
        }
    }
}

impl Drop for NativeArchiveSink {
    fn drop(&mut self) {
        if !self.finished {
            // A failed/trapped producer is closure, never successful EOF.
            let _ = self.hub.abandon_blob_wire(self.store, self.blob.wire());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::archive::{authenticated_staging::reader_tests::fixture, ExtractionLimits};
    use crate::async_engine::{timeout, RuntimeBuilder};
    use std::time::Duration;

    const CHUNK: usize = 64 * 1024;
    struct Cleanup(Arc<OperationHub>);
    impl Drop for Cleanup {
        fn drop(&mut self) {
            self.0.close_all(Terminal::Cancelled);
        }
    }

    struct ResumeOnDrop(Arc<Notify>);
    impl Drop for ResumeOnDrop {
        fn drop(&mut self) {
            self.0.notify_one();
        }
    }

    async fn wait_full(hub: &OperationHub) {
        timeout(Duration::from_secs(5), async {
            loop {
                let snapshot = hub.snapshot();
                if snapshot.buffered_blob_bytes == 2 * CHUNK && snapshot.pending_blob_writes == 1 {
                    return;
                }
                crate::async_engine::yield_now().await;
            }
        })
        .await
        .unwrap();
    }

    async fn read(hub: &OperationHub, blob: OpaqueToken) -> Result<usize, HubError> {
        let operation = hub.submit_blob_read(1, blob, CHUNK)?;
        loop {
            let result = hub.collect_blob_read_wire(1, operation.wire(), CHUNK, |bytes| {
                assert!(bytes.iter().all(|byte| *byte == 0x5a));
            })?;
            match result as u8 {
                STATUS_PENDING => hub.wait_external_operation(1, operation)?.notified().await,
                STATUS_COMPLETED => return Ok((result >> 8) as usize),
                _ => return Err(HubError::Closed),
            }
        }
    }

    #[test]
    fn authenticated_blob_stops_at_capacity_and_streams_every_large_entry_byte() {
        const LENGTH: u64 = 17 * 1024 * 1024;
        let (authenticated, storage) = fixture("payload", LENGTH);
        let reader = authenticated
            .into_reader(ExtractionLimits::default())
            .unwrap();
        let limits = BlobLimits::new(CHUNK, 2 * CHUNK, 4 * CHUNK).unwrap();
        let hub = OperationHub::with_blob_limits(8, 2, limits).unwrap();
        let runtime = RuntimeBuilder::current_thread()
            .enable_all()
            .build()
            .unwrap();
        let _cleanup = Cleanup(Arc::clone(&hub));
        let sink = NativeArchiveSink::new(Arc::clone(&hub), runtime.handle(), 1).unwrap();
        let blob = sink.blob();
        assert_eq!(
            hub.submit_blob_write(1, blob, b"forged"),
            Err(HubError::WrongRights)
        );
        assert_eq!(hub.seal_blob(1, blob), Err(HubError::WrongRights));
        let job = runtime
            .handle()
            .launch_blocking(move || sink.copy_archive(reader, 0));
        runtime.run(async {
            wait_full(&hub).await;
            let paused = hub.snapshot();
            assert_eq!(paused.pending_write_bytes, CHUNK);
            assert!(!job.is_finished());
            assert!(storage.used() > 16 * 1024 * 1024);
            crate::async_engine::sleep(Duration::from_millis(20)).await;
            assert_eq!(
                hub.snapshot().buffered_blob_bytes,
                paused.buffered_blob_bytes
            );
            assert_eq!(
                hub.snapshot().pending_write_bytes,
                paused.pending_write_bytes
            );
            let total = timeout(Duration::from_secs(10), async {
                let mut total = 0_u64;
                loop {
                    let count = read(&hub, blob).await.unwrap();
                    if count == 0 {
                        break;
                    }
                    total += count as u64;
                    assert!(total <= LENGTH);
                }
                total
            })
            .await
            .unwrap();
            assert_eq!(total, LENGTH);
            assert_eq!(job.await.unwrap().unwrap(), LENGTH);
        });
        assert_eq!(storage.used(), 0);
        hub.abandon_blob_wire(1, blob.wire()).unwrap();
        let snapshot = hub.snapshot();
        assert_eq!(snapshot.live_resources, 0);
        assert_eq!(snapshot.pending_operations, 0);
        assert_eq!(snapshot.retained_transfer_capacity, 0);
        assert!(snapshot.peak_retained_transfer_capacity <= limits.maximum_transfer_bytes);
        assert!(snapshot.peak_buffered_blob_bytes <= 2 * CHUNK);
    }

    #[test]
    fn authenticated_blob_consumer_drop_and_teardown_unblock_producer() {
        for terminal in [None, Some(Terminal::Trapped), Some(Terminal::TimedOut)] {
            let (authenticated, storage) = fixture("payload", (4 * CHUNK) as u64);
            let reader = authenticated
                .into_reader(ExtractionLimits::default())
                .unwrap();
            let hub = OperationHub::with_blob_limits(
                8,
                2,
                BlobLimits::new(CHUNK, 2 * CHUNK, 4 * CHUNK).unwrap(),
            )
            .unwrap();
            let runtime = RuntimeBuilder::current_thread()
                .enable_all()
                .build()
                .unwrap();
            let _cleanup = Cleanup(Arc::clone(&hub));
            let sink = NativeArchiveSink::new(Arc::clone(&hub), runtime.handle(), 1).unwrap();
            let blob = sink.blob();
            let job = runtime
                .handle()
                .launch_blocking(move || sink.copy_archive(reader, 0));
            runtime.run(async {
                wait_full(&hub).await;
                assert!(storage.used() > 0);
                if let Some(terminal) = terminal {
                    hub.close_all(terminal);
                } else {
                    hub.abandon_blob_wire(1, blob.wire()).unwrap();
                }
                assert!(timeout(Duration::from_secs(5), job)
                    .await
                    .unwrap()
                    .unwrap()
                    .is_err());
            });
            assert_eq!(storage.used(), 0);
            let snapshot = hub.snapshot();
            assert_eq!(snapshot.live_resources, 0);
            assert_eq!(snapshot.pending_operations, 0);
            assert_eq!(snapshot.retained_transfer_capacity, 0);
        }
    }

    #[test]
    fn authenticated_blob_failed_or_panicked_producer_never_publishes_eof() {
        use std::io::Write as _;
        for panic_after_prefix in [false, true] {
            let (authenticated, storage) = fixture("payload", (2 * CHUNK) as u64);
            let reader = authenticated
                .into_reader(ExtractionLimits::default())
                .unwrap();
            let hub = OperationHub::with_blob_limits(
                1,
                2,
                BlobLimits::new(CHUNK, 2 * CHUNK, 4 * CHUNK).unwrap(),
            )
            .unwrap();
            let runtime = RuntimeBuilder::current_thread()
                .enable_all()
                .build()
                .unwrap();
            let _cleanup = Cleanup(Arc::clone(&hub));
            let mut sink = NativeArchiveSink::new(Arc::clone(&hub), runtime.handle(), 1).unwrap();
            let blob = sink.blob();
            let prefix = Arc::new(Notify::new());
            let resume = Arc::new(Notify::new());
            let _resume_on_failure = ResumeOnDrop(Arc::clone(&resume));
            let worker_prefix = Arc::clone(&prefix);
            let worker_resume = Arc::clone(&resume);
            let handle = runtime.handle();
            let job = handle.clone().launch_blocking(move || {
                let _reader = reader;
                sink.write_all(&[0x5a; CHUNK]).unwrap();
                sink.flush().unwrap(); // flush must not seal the stream.
                worker_prefix.notify_one();
                handle.block_on_wasm(worker_resume.notified());
                if panic_after_prefix {
                    panic!("synthetic archive producer unwind");
                }
                // The consumer's pending read occupies the only operation
                // slot. Submission fails without granting reusable EOF.
                assert!(sink.write_all(&[0x5a; CHUNK]).is_err());
                assert!(sink.finish().is_err());
            });
            runtime.run(async {
                timeout(Duration::from_secs(5), prefix.notified())
                    .await
                    .unwrap();
                assert_eq!(read(&hub, blob).await.unwrap(), CHUNK);
                let waiting = hub.submit_blob_read(1, blob, CHUNK).unwrap();
                assert_eq!(
                    hub.collect_blob_read_wire(1, waiting.wire(), CHUNK, |_| panic!(
                        "premature EOF"
                    ))
                    .unwrap(),
                    0
                );
                assert!(storage.used() > 0);
                resume.notify_one();
                let result = timeout(Duration::from_secs(5), job).await.unwrap();
                assert_eq!(result.is_err(), panic_after_prefix);
                let closed = hub
                    .collect_blob_read_wire(1, waiting.wire(), CHUNK, |_| {
                        panic!("failed producer published EOF")
                    })
                    .unwrap();
                assert_eq!(closed as u8, STATUS_CLOSED);
            });
            assert_eq!(storage.used(), 0);
            assert_eq!(hub.snapshot().live_resources, 0);
            assert_eq!(hub.snapshot().pending_operations, 0);
            assert_eq!(hub.snapshot().retained_transfer_capacity, 0);
        }
    }
}