Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-harness/src/wasm/attachment.rs

Raw
//! Scoped attachment ownership (`SMH-SPEC-WASM0001`, `SMH-SPEC-PLUG0001`).
//! Atomics preserve pointer provenance and keep store data transferable between calls.
//! No concurrent invocation is admitted; guards own only invocation-local leases.

use super::{Result, plugin_fault};
use std::sync::Arc;
use std::sync::atomic::{AtomicPtr, Ordering};

#[derive(Default)]
pub(super) struct WorkspaceEffects {
    address: Arc<AtomicPtr<()>>,
}

pub(super) struct Attachment {
    address: Arc<AtomicPtr<()>>,
    effects: *mut (),
}

pub(super) struct Suspension {
    address: Arc<AtomicPtr<()>>,
    effects: *mut (),
}

const fn suspended() -> *mut () {
    std::ptr::NonNull::<()>::dangling().as_ptr()
}

impl WorkspaceEffects {
    pub(super) fn attach(&self, effects: *mut ()) -> Result<Attachment> {
        if effects.is_null() || effects == suspended() {
            return Err(plugin_fault("workspace effect context pointer is invalid"));
        }
        self.address
            .compare_exchange(
                std::ptr::null_mut(),
                effects,
                Ordering::Relaxed,
                Ordering::Relaxed,
            )
            .map_err(|_| plugin_fault("workspace effect context is already attached"))?;
        Ok(Attachment {
            address: Arc::clone(&self.address),
            effects,
        })
    }

    #[expect(
        clippy::needless_pass_by_ref_mut,
        reason = "exclusive store borrow serializes pointer checkout despite atomic storage"
    )]
    pub(super) fn suspend(&mut self) -> std::result::Result<Suspension, String> {
        let effects = self
            .get()
            .ok_or_else(|| "workspace capability is not configured or is suspended".to_string())?;
        self.address.store(suspended(), Ordering::Relaxed);
        Ok(Suspension {
            address: Arc::clone(&self.address),
            effects,
        })
    }

    pub(super) fn get(&self) -> Option<*mut ()> {
        let effects = self.address.load(Ordering::Relaxed);
        (!effects.is_null() && effects != suspended()).then_some(effects)
    }

    #[cfg(test)]
    pub(super) fn set(&self, effects: Option<*mut ()>) {
        self.address
            .store(effects.unwrap_or(std::ptr::null_mut()), Ordering::Relaxed);
    }
}

impl Suspension {
    pub(super) const fn effects(&self) -> *mut () {
        self.effects
    }
}

impl Drop for Suspension {
    fn drop(&mut self) {
        // An outer guard dropped during unwinding must never be resurrected.
        let _restored = self.address.compare_exchange(
            suspended(),
            self.effects,
            Ordering::Relaxed,
            Ordering::Relaxed,
        );
    }
}

impl Drop for Attachment {
    fn drop(&mut self) {
        let current = self.address.load(Ordering::Relaxed);
        if current == self.effects || current == suspended() {
            self.address.store(std::ptr::null_mut(), Ordering::Relaxed);
        }
    }
}

#[cfg(test)]
mod tests {
    //! SMH-SPEC-WASM0001: suspension never permits parent reentry or resurrection.
    use super::*;

    #[test]
    fn suspension_excludes_parent_and_restores_on_unwind() {
        let mut attachment = WorkspaceEffects::default();
        let mut context = 0_u64;
        let pointer = std::ptr::from_mut(&mut context).cast();
        let outer = attachment.attach(pointer).unwrap();
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _suspension = attachment.suspend().unwrap();
            assert!(attachment.get().is_none());
            assert!(attachment.attach(pointer).is_err());
            assert!(attachment.suspend().is_err());
            panic!("child unwind");
        }));
        assert!(result.is_err());
        assert_eq!(attachment.get(), Some(pointer));
        let suspension = attachment.suspend().unwrap();
        drop(outer);
        drop(suspension);
        assert!(attachment.get().is_none());
    }

    #[test]
    fn attachment_leases_allocate_only_once_at_store_creation() {
        let (mut attachment, creation) =
            smith_alloc::measure(smith_alloc::Scope::KernelCall, WorkspaceEffects::default);
        assert_eq!(creation.allocations, 1);
        assert_eq!(creation.bytes, 3 * std::mem::size_of::<usize>() as u64);
        let mut context = 0_u64;
        let (_, invocation) = smith_alloc::measure(smith_alloc::Scope::KernelCall, || {
            let _outer = attachment
                .attach(std::ptr::from_mut(&mut context).cast())
                .unwrap();
            let _suspension = attachment.suspend().unwrap();
        });
        assert_eq!(invocation.allocations, 0);
    }

    #[test]
    fn attachment_layout_is_two_words_per_lease() {
        assert_eq!(
            std::mem::size_of::<WorkspaceEffects>(),
            std::mem::size_of::<usize>()
        );
        assert_eq!(
            std::mem::size_of::<Attachment>(),
            2 * std::mem::size_of::<usize>()
        );
        assert_eq!(
            std::mem::size_of::<Suspension>(),
            2 * std::mem::size_of::<usize>()
        );
    }
}