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
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
//! Semantic Rust guest capabilities backed by the private generated core ABI.
//!
//! No native path, URL string, ABI token, or generated type is exposed here.

#[allow(dead_code)]
#[rustfmt::skip] // Generated bytes are checked against the ABI generator.
#[path = "wasm/generated/v1/guest_bindings.rs"]
mod bindings;

std::cfg_select! {
    all(target_family = "wasm", feature = "wasm-component-hash-experiment") => {
        #[path = "guest_component_hash.rs"]
        mod component_hash;
        use component_hash::Blake3Hasher as HashBackend;
    }
    _ => { use bindings::Blake3Hasher as HashBackend; }
}

std::cfg_select! {
    all(target_family = "wasm", feature = "wasm-component-compiler-experiment") => {
        #[path = "guest_component_compiler.rs"]
        mod component_compiler;
        use component_compiler::{CompilerGrant as CompilerGrantBackend, CompilerProcess as CompilerProcessBackend};
    }
    _ => { use bindings::{CompilerGrant as CompilerGrantBackend, CompilerProcess as CompilerProcessBackend}; }
}

/// A kernel operation's terminal failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OperationError {
    Rejected,
    Cancelled,
    Closed,
    Failed,
    TimedOut,
}

impl From<bindings::OperationError> for OperationError {
    fn from(error: bindings::OperationError) -> Self {
        match error {
            bindings::OperationError::Rejected => Self::Rejected,
            bindings::OperationError::Cancelled => Self::Cancelled,
            bindings::OperationError::Closed => Self::Closed,
            bindings::OperationError::Failed => Self::Failed,
            bindings::OperationError::TimedOut => Self::TimedOut,
        }
    }
}

impl From<OperationError> for bindings::OperationError {
    fn from(error: OperationError) -> Self {
        match error {
            OperationError::Rejected => Self::Rejected,
            OperationError::Cancelled => Self::Cancelled,
            OperationError::Closed => Self::Closed,
            OperationError::Failed => Self::Failed,
            OperationError::TimedOut => Self::TimedOut,
        }
    }
}

/// Run a command composed of kernel operations. Foreign futures that return
/// `Pending` are unsupported; kernel operations suspend through the host ABI.
pub fn run<T>(
    future: impl std::future::Future<Output = Result<T, OperationError>>,
) -> Result<T, OperationError> {
    bindings::run(async { future.await.map_err(bindings::OperationError::from) })
        .map_err(OperationError::from)
}

/// Wait on the host's monotonic timer without granting a guest clock import.
pub async fn sleep(milliseconds: u32) -> Result<(), OperationError> {
    bindings::clock_sleep(milliseconds)?.wait().await?;
    Ok(())
}

/// Kernel-owned incremental BLAKE3 state. Updates are bounded to 64 KiB.
pub struct Blake3Hasher {
    inner: HashBackend,
}

impl Blake3Hasher {
    pub async fn new() -> Result<Self, OperationError> {
        Ok(Self {
            inner: HashBackend::new().await?,
        })
    }

    /// Feed one bounded chunk. After an update fails or is abandoned, dispose
    /// of this hasher: cancellation does not roll back committed bytes.
    pub async fn update(&mut self, bytes: &[u8]) -> Result<(), OperationError> {
        self.inner.update(bytes).await?;
        Ok(())
    }

    /// Consume the hasher and return its canonical 32-byte digest.
    pub async fn finalize(self) -> Result<[u8; 32], OperationError> {
        Ok(self.inner.finalize().await?)
    }
}

/// One exact executable/argument/environment/deadline grant chosen by the host.
/// The guest cannot substitute a command, working directory, or environment.
pub struct CompilerGrant {
    inner: CompilerGrantBackend,
}
pub struct CompilerProcess {
    inner: CompilerProcessBackend,
}

/// A host-authorized decision for one guest-derived compiler cache key.
/// Cache contents and locations never cross the guest boundary.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompilerCacheStatus {
    Hit,
    Miss,
}

/// A tagged event; only chunk variants refer to bytes in the read destination.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompilerOutputEvent {
    Stdout(usize),
    Stderr(usize),
    StdoutEof,
    StderrEof,
    StdoutAbandoned,
    StderrAbandoned,
    StdoutError,
    StderrError,
    Exhausted,
}

/// Host-neutral termination meaning, without native backend status types.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CompilerExit {
    pub code: Option<i32>,
    pub success: bool,
}

impl CompilerGrant {
    pub fn granted() -> Result<Option<Self>, OperationError> {
        Ok(CompilerGrantBackend::granted()?.map(|inner| Self { inner }))
    }
    pub async fn spawn(self) -> Result<CompilerProcess, OperationError> {
        Ok(CompilerProcess {
            inner: self.inner.spawn().await?,
        })
    }
    pub fn cache_status(&self, key: &[u8; 32]) -> Result<CompilerCacheStatus, OperationError> {
        Ok(if self.inner.cache_status(key)? {
            CompilerCacheStatus::Hit
        } else {
            CompilerCacheStatus::Miss
        })
    }
}

impl CompilerProcess {
    /// Pull one event into a destination of at least 64 KiB. Drain output
    /// before waiting for exit: a full pipe can keep the compiler from exiting.
    pub async fn read_output(
        &mut self,
        destination: &mut [u8],
    ) -> Result<CompilerOutputEvent, OperationError> {
        use bindings::CompilerOutputEvent as Event;
        Ok(match self.inner.read_output(destination).await? {
            Event::Stdout(count) => CompilerOutputEvent::Stdout(count),
            Event::Stderr(count) => CompilerOutputEvent::Stderr(count),
            Event::StdoutEof => CompilerOutputEvent::StdoutEof,
            Event::StderrEof => CompilerOutputEvent::StderrEof,
            Event::StdoutAbandoned => CompilerOutputEvent::StdoutAbandoned,
            Event::StderrAbandoned => CompilerOutputEvent::StderrAbandoned,
            Event::StdoutError => CompilerOutputEvent::StdoutError,
            Event::StderrError => CompilerOutputEvent::StderrError,
            Event::Exhausted => CompilerOutputEvent::Exhausted,
        })
    }
    /// Cancelling this observer does not revoke the compiler or consume output.
    pub async fn wait(&self) -> Result<CompilerExit, OperationError> {
        let exit = self.inner.wait().await?;
        Ok(CompilerExit {
            code: exit.code,
            success: exit.success,
        })
    }
    /// Revoke authority and await acknowledged native output cleanup and reaping.
    pub async fn close(self) -> Result<(), OperationError> {
        Ok(self.inner.close().await?)
    }
}

/// Host-granted encrypted input for the archive experiment. Only its bounded
/// public envelope metadata is readable; no path, key, or plaintext is exposed.
/// Native input grants currently exist only in the test-support experiment.
pub struct EncryptedArchive {
    inner: bindings::EncryptedArchive,
}

impl EncryptedArchive {
    /// Take the input grant once. Subsequent calls return `None`.
    pub fn granted() -> Result<Option<Self>, OperationError> {
        Ok(bindings::EncryptedArchive::granted()?.map(|inner| Self { inner }))
    }

    /// Copy the original bounded prefix/header. An undersized destination is
    /// rejected without consuming the grant, so the caller may retry.
    pub async fn read_header(&self, destination: &mut [u8]) -> Result<usize, OperationError> {
        self.inner
            .read_header(destination)
            .map_err(OperationError::from)
    }

    /// Consume this input and authenticate using the nonce decoded by guest
    /// policy. The host retains the key and authenticates the original header.
    /// Dropping this future abandons its operation and any uncollected result.
    pub async fn authenticate(
        self,
        nonce: [u8; 12],
    ) -> Result<AuthenticatedArchive, OperationError> {
        let inner = self.inner.authenticate(&nonce)?.wait().await?;
        Ok(AuthenticatedArchive { inner })
    }
}

/// Opaque authenticated storage. No plaintext authority exists before the
/// final authentication tag succeeds. Inventory/entry APIs remain experimental.
pub struct AuthenticatedArchive {
    inner: bindings::AuthenticatedArchive,
}

impl AuthenticatedArchive {
    /// Read the next bounded inventory record. Returned entries retain their
    /// authenticated storage independently of this enumeration handle.
    /// Drain or drop an open entry Blob before advancing this sequential reader.
    pub async fn next_entry(&mut self) -> Result<Option<ArchiveEntry>, OperationError> {
        let Some(inner) = self.inner.next_entry()?.wait().await? else {
            return Ok(None);
        };
        let mut record = [0; 4108];
        let count = inner.metadata(&mut record)?;
        let bytes = u64::from_le_bytes(record[..8].try_into().map_err(|_| OperationError::Failed)?);
        let length = u32::from_le_bytes(
            record[8..12]
                .try_into()
                .map_err(|_| OperationError::Failed)?,
        ) as usize;
        if length != count - 12 {
            return Err(OperationError::Failed);
        }
        let name = std::str::from_utf8(&record[12..count])
            .map_err(|_| OperationError::Failed)?
            .to_owned();
        Ok(Some(ArchiveEntry {
            _inner: inner,
            name,
            bytes,
        }))
    }

    pub async fn close(self) -> Result<(), OperationError> {
        self.inner.close().map_err(OperationError::from)
    }
}

/// One bounded inventory record and its independent scoped entry authority.
pub struct ArchiveEntry {
    // Retains scoped authority until opened or dropped.
    _inner: bindings::ArchiveEntry,
    name: String,
    bytes: u64,
}

impl ArchiveEntry {
    /// Consume this entry authority and stream its checked plaintext through a
    /// bounded read-only Blob. Drop the Blob to stop an unfinished producer.
    /// Drain or drop it before opening another entry from the same archive.
    pub async fn open(self) -> Result<Blob, OperationError> {
        Ok(Blob {
            inner: self._inner.open()?.wait().await?,
        })
    }
    pub fn name(&self) -> &str {
        &self.name
    }
    pub fn uncompressed_bytes(&self) -> u64 {
        self.bytes
    }
}

/// An opaque host-owned bulk resource, never an image buffer or ABI token.
/// Drop revokes host authority without suspending or reserving an operation.
pub struct Blob {
    inner: bindings::BlobHandle,
}

impl Blob {
    /// Create a quota-accounted stream without allocating its total payload.
    pub async fn create() -> Result<Self, OperationError> {
        let token = bindings::BlobHandle::create()?.wait().await?;
        if token == 0 {
            return Err(OperationError::Failed);
        }
        Ok(Self {
            inner: bindings::BlobHandle::from_create_payload(token),
        })
    }

    /// Submit one bounded chunk. The host copies the slice before this call
    /// returns, and completion waits for downstream capacity.
    pub fn write_chunk(&self, bytes: &[u8]) -> Result<PendingWrite, OperationError> {
        Ok(PendingWrite {
            inner: self.inner.write_chunk(bytes)?,
            terminal: false,
        })
    }

    /// Transfer one bounded chunk through the generated caller-memory stream
    /// control. The host copies it before this call returns.
    pub fn write(&mut self, bytes: &[u8]) -> Result<usize, OperationError> {
        self.inner.write(bytes).map_err(OperationError::from)
    }

    /// Pull one bounded chunk through the generated caller-memory stream
    /// control. No guest pointer survives this call.
    pub fn read(&mut self, destination: &mut [u8]) -> Result<usize, OperationError> {
        self.inner.read(destination).map_err(OperationError::from)
    }

    /// Request one bounded pull read; no guest pointer is retained by the host.
    pub fn read_chunk(&self, maximum_bytes: u32) -> Result<PendingRead, OperationError> {
        Ok(PendingRead {
            inner: self.inner.read_chunk(maximum_bytes)?,
            terminal: false,
        })
    }

    /// Publish EOF after completing preceding writes.
    pub async fn seal(&self) -> Result<(), OperationError> {
        self.inner.seal()?.wait().await?;
        Ok(())
    }

    /// Release the blob's host resources explicitly.
    pub async fn close(self) -> Result<(), OperationError> {
        self.inner.close()?;
        Ok(())
    }
}

/// A capacity-awaited write. Dropping it discards any uncollected host result.
pub struct PendingWrite {
    inner: bindings::OperationFuture,
    terminal: bool,
}

impl PendingWrite {
    pub fn poll(&mut self) -> Result<Option<()>, OperationError> {
        let result = self
            .inner
            .poll()
            .map(|value| value.map(|_| ()))
            .map_err(OperationError::from);
        self.terminal |= matches!(result, Ok(Some(_)));
        result
    }

    pub fn cancel(&self) {
        self.inner.cancel();
    }

    /// Suspend this guest execution until the host operation wakes it.
    pub fn yield_now(&self) -> Result<(), OperationError> {
        self.inner.yield_now().map_err(OperationError::from)
    }

    pub async fn wait(mut self) -> Result<(), OperationError> {
        loop {
            if self.poll()?.is_some() {
                return Ok(());
            }
            self.yield_now()?;
        }
    }
}

impl Drop for PendingWrite {
    fn drop(&mut self) {
        if !self.terminal {
            self.inner.abandon_transfer();
        }
    }
}

/// A bounded pull read. A completed zero-byte read denotes EOF.
pub struct PendingRead {
    inner: bindings::BlobReadFuture,
    terminal: bool,
}

impl PendingRead {
    pub fn poll_into(&mut self, destination: &mut [u8]) -> Result<Option<usize>, OperationError> {
        let result = self
            .inner
            .poll_into(destination)
            .map_err(OperationError::from);
        // A local destination-conversion error need not consume the host
        // operation. Retain abandonment-on-drop unless collection succeeded.
        self.terminal |= matches!(result, Ok(Some(_)));
        result
    }

    pub fn cancel(&self) {
        self.inner.cancel();
    }

    pub fn yield_now(&self) -> Result<(), OperationError> {
        self.inner.yield_now().map_err(OperationError::from)
    }

    pub async fn read_into(mut self, destination: &mut [u8]) -> Result<usize, OperationError> {
        loop {
            if let Some(count) = self.poll_into(destination)? {
                return Ok(count);
            }
            self.yield_now()?;
        }
    }
}

impl Drop for PendingRead {
    fn drop(&mut self) {
        if !self.terminal {
            self.inner.abandon_transfer();
        }
    }
}

/// One exact output destination pre-authorized by the embedding host.
pub struct OutputFile {
    inner: bindings::OutputFile,
}

impl OutputFile {
    pub fn granted() -> Result<Option<Self>, OperationError> {
        Ok(bindings::OutputFile::granted()?.map(|inner| Self { inner }))
    }

    /// Commit the blob through the host's exact-output capability. Successful
    /// publication consumes both host authorities; these handles then become
    /// stale. Borrowing preserves the caller's handles on preflight failure,
    /// so an unsealed blob can still be sealed, retried, or explicitly closed.
    pub async fn write_blob(&self, blob: &Blob) -> Result<(), OperationError> {
        self.inner.write_blob(&blob.inner)?.wait().await?;
        Ok(())
    }
}

/// One pre-authorized URL. Guest code cannot construct a new URL grant.
pub struct WebviewUrl {
    inner: bindings::WebviewUrl,
}

impl WebviewUrl {
    pub fn granted() -> Result<Option<Self>, OperationError> {
        Ok(bindings::WebviewUrl::granted()?.map(|inner| Self { inner }))
    }

    pub async fn open(&self) -> Result<Webview, OperationError> {
        Ok(Webview {
            inner: self.inner.open().await?,
        })
    }
}

/// Opaque capture-only native viewport authority.
pub struct Webview {
    inner: bindings::Webview,
}

impl Webview {
    pub async fn wait_until_loaded(&self) -> Result<(), OperationError> {
        self.inner
            .wait_until_loaded()
            .await
            .map_err(OperationError::from)
    }

    pub async fn capture_visible_png(&self) -> Result<Blob, OperationError> {
        Ok(Blob {
            inner: self.inner.capture_visible_png().await?,
        })
    }

    pub async fn close(self) -> Result<(), OperationError> {
        self.inner.close().await.map_err(OperationError::from)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{
        atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering},
        Mutex,
    };

    static COMPLETED: AtomicBool = AtomicBool::new(false);
    static CANCELLATIONS: AtomicUsize = AtomicUsize::new(0);
    static ABANDONMENTS: AtomicUsize = AtomicUsize::new(0);
    static BLOB_RELEASES: AtomicUsize = AtomicUsize::new(0);
    static LAST_BLOB_RELEASE: AtomicI64 = AtomicI64::new(-1);
    static REJECT_BLOB_TRANSFERS: AtomicBool = AtomicBool::new(false);
    static BLOB_RELEASE_LOCK: Mutex<()> = Mutex::new(());

    // Scalar import shims exercise adapter ownership without a native runtime.
    // Actual ABI execution remains covered by the Cargo-built Wasm fixtures.
    #[export_name = "operation_submit"]
    extern "C" fn submit(kind: i32, _: i64, reserved: i64) -> i64 {
        if kind == 18 {
            assert_eq!(reserved, 0);
            ABANDONMENTS.fetch_add(1, Ordering::SeqCst);
            return 1;
        }
        17
    }
    #[export_name = "operation_poll"]
    extern "C" fn poll(_: i64) -> i64 {
        i64::from(COMPLETED.load(Ordering::SeqCst))
    }
    #[export_name = "operation_cancel"]
    extern "C" fn cancel(_: i64) -> i32 {
        CANCELLATIONS.fetch_add(1, Ordering::SeqCst);
        1
    }
    #[export_name = "operation_yield"]
    extern "C" fn suspend(_: i64) -> i32 {
        1
    }
    #[export_name = "kernel_yield"]
    extern "C" fn kernel_yield() {}
    #[export_name = "stream_close"]
    extern "C" fn stream_close(blob: i64) -> i32 {
        LAST_BLOB_RELEASE.store(blob, Ordering::SeqCst);
        BLOB_RELEASES.fetch_add(1, Ordering::SeqCst);
        0
    }
    #[export_name = "stream_read"]
    extern "C" fn stream_read(_: i64, _: i32, length: i32) -> i32 {
        if REJECT_BLOB_TRANSFERS.load(Ordering::SeqCst) {
            -1
        } else {
            length
        }
    }
    #[export_name = "stream_write"]
    extern "C" fn stream_write(_: i64, _: i32, length: i32) -> i32 {
        if REJECT_BLOB_TRANSFERS.load(Ordering::SeqCst) {
            -1
        } else {
            length
        }
    }
    #[export_name = "resource_release_encrypted_archive"]
    extern "C" fn resource_release_encrypted_archive(_: i64) -> i32 {
        0
    }
    #[export_name = "resource_release_authenticated_archive"]
    extern "C" fn resource_release_authenticated_archive(_: i64) -> i32 {
        0
    }
    #[export_name = "resource_release_archive_entry"]
    extern "C" fn resource_release_archive_entry(_: i64) -> i32 {
        0
    }

    #[test]
    fn generated_blob_release_is_exactly_once_for_drop_and_explicit_close() {
        let _release_lock = BLOB_RELEASE_LOCK.lock().unwrap();
        BLOB_RELEASES.store(0, Ordering::SeqCst);
        LAST_BLOB_RELEASE.store(-1, Ordering::SeqCst);
        drop(bindings::BlobHandle::from_create_payload(41));
        assert_eq!(BLOB_RELEASES.load(Ordering::SeqCst), 1);
        assert_eq!(LAST_BLOB_RELEASE.load(Ordering::SeqCst), 41);

        run(async {
            Blob {
                inner: bindings::BlobHandle::from_create_payload(99),
            }
            .close()
            .await
        })
        .unwrap();
        assert_eq!(BLOB_RELEASES.load(Ordering::SeqCst), 2);
        assert_eq!(LAST_BLOB_RELEASE.load(Ordering::SeqCst), 99);
    }

    #[test]
    fn blob_direct_stream_controls_stay_behind_the_guest_facade() {
        let _release_lock = BLOB_RELEASE_LOCK.lock().unwrap();
        let mut blob = Blob {
            inner: bindings::BlobHandle::from_create_payload(7),
        };
        assert_eq!(blob.write(b"ping"), Ok(4));
        let mut destination = [0; 2];
        assert_eq!(blob.read(&mut destination), Ok(2));
    }

    #[test]
    fn blob_stream_rejection_is_a_semantic_guest_error() {
        let _release_lock = BLOB_RELEASE_LOCK.lock().unwrap();
        REJECT_BLOB_TRANSFERS.store(true, Ordering::SeqCst);
        let mut blob = Blob {
            inner: bindings::BlobHandle::from_create_payload(7),
        };
        assert_eq!(blob.write(b"ping"), Err(OperationError::Rejected));
        let mut destination = [0; 2];
        assert_eq!(blob.read(&mut destination), Err(OperationError::Rejected));
        REJECT_BLOB_TRANSFERS.store(false, Ordering::SeqCst);
    }

    #[test]
    fn dropping_transfers_abandons_but_preserves_explicit_cancellation() {
        let _release_lock = BLOB_RELEASE_LOCK.lock().unwrap();
        CANCELLATIONS.store(0, Ordering::SeqCst);
        ABANDONMENTS.store(0, Ordering::SeqCst);
        COMPLETED.store(false, Ordering::SeqCst);
        let mut write = PendingWrite {
            inner: bindings::clock_sleep(1).unwrap(),
            terminal: false,
        };
        assert_eq!(write.poll(), Ok(None));
        write.cancel();
        assert_eq!(CANCELLATIONS.load(Ordering::SeqCst), 1);
        drop(write);
        assert_eq!(ABANDONMENTS.load(Ordering::SeqCst), 1);

        let read = PendingRead {
            inner: bindings::BlobHandle::from_create_payload(1)
                .read_chunk(1)
                .unwrap(),
            terminal: false,
        };
        drop(read);
        assert_eq!(ABANDONMENTS.load(Ordering::SeqCst), 2);

        COMPLETED.store(true, Ordering::SeqCst);
        let mut write = PendingWrite {
            inner: bindings::clock_sleep(1).unwrap(),
            terminal: false,
        };
        assert_eq!(write.poll(), Ok(Some(())));
        drop(write);
        assert_eq!(ABANDONMENTS.load(Ordering::SeqCst), 2);
        assert_eq!(CANCELLATIONS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn terminal_errors_survive_the_private_adapter() {
        for error in [
            OperationError::Rejected,
            OperationError::Cancelled,
            OperationError::Closed,
            OperationError::Failed,
            OperationError::TimedOut,
        ] {
            assert_eq!(
                OperationError::from(bindings::OperationError::from(error)),
                error
            );
            assert_eq!(run::<()>(async { Err(error) }), Err(error));
        }
        assert_eq!(run(async { Ok(42) }), Ok(42));
    }
}