Hardened Rust Skills for AI Coding Agents
Generic language models generate Rust code that compiles cleanly but causes catastrophic runtime degradation: threadpool starvation, lock contention across await points, silent cancellation drops, and multi-gigabyte buffer cloning across Python FFI boundaries.
These production-grade skills inject static AST guards, GIL-releasing contracts, and memory-layout verification directly into Antigravity, Claude Code, and Cursor.
tokio-safety-auditor
Static AST and heuristic auditor for Tokio asynchronous Rust. Eliminates worker thread starvation, cross-await Mutex deadlocks, and select! cancellation safety data loss.
- β Generic LLMs frequently call std::fs::read or std::thread::sleep inside async fn, freezing Tokio worker threads and destroying system throughput.
- β Models use std::sync::Mutex across .await points, violating the Send trait or causing deadlocks under high concurrency.
- β AI code generators naively use AsyncReadExt::read in tokio::select! branches, permanently discarding unconsumed stream bytes on branch cancellation.
- β Failure to bind or offload CPU-intensive serialization (>100Β΅s) to spawn_blocking, leading to unexplainable p99 latency spikes.
- β Strict prohibition of std::fs and std::thread::sleep inside async contexts; mandatory replacement with tokio::fs and tokio::time.
- β Scoped mutex guard dropping before await boundaries, or migration to tokio::sync::Mutex when lock spanning is required.
- β Cancellation-safe stream handling using tokio_util::codec::FramedRead or pinned stream futures outside select! loops.
- β Automated delegation of heavy computational workloads to tokio::task::spawn_blocking with Semaphore concurrency bounds.
// [FAULT] Freezes Tokio worker thread
pub async fn read_config(path: &Path) -> Result<Config, Error> {
let raw = std::fs::read_to_string(path)?; // Blocks executor OS thread!
let cfg = serde_json::from_str(&raw)?;
Ok(cfg)
} // [SAFE] Non-blocking cooperative async I/O
pub async fn read_config(path: &Path) -> Result<Config, Error> {
let raw = tokio::fs::read_to_string(path).await?;
let cfg = serde_json::from_str(&raw)?;
Ok(cfg)
} // [FAULT] MutexGuard held across await point
pub async fn update_state(state: &std::sync::Mutex<State>, client: &ApiClient) {
let mut lock = state.lock().unwrap();
let payload = client.fetch().await; // Lock held while awaiting network IO!
lock.records.push(payload);
} // [SAFE] Lock acquired strictly after await point
pub async fn update_state(state: &std::sync::Mutex<State>, client: &ApiClient) {
let payload = client.fetch().await; // Network IO resolved outside critical section
{
let mut lock = state.lock().unwrap();
lock.records.push(payload);
} // Guard dropped immediately
} // [FAULT] Data loss on cancellation
loop {
tokio::select! {
n = stream.read(&mut buf) => { // If timer fires, partial bytes in buffer are dropped!
handle_bytes(&buf[..n?]);
}
_ = timeout.tick() => handle_heartbeat(),
}
} // [SAFE] Framed codec maintains internal buffer across cancellation
let mut framed = tokio_util::codec::FramedRead::new(stream, PacketCodec::new());
loop {
tokio::select! {
biased;
Some(pkt) = framed.next() => handle_packet(pkt?),
_ = timeout.tick() => handle_heartbeat(),
}
} - βΉ Verified all filesystem operations in async call paths utilize tokio::fs or spawn_blocking.
- βΉ Audited all Mutex usage with cargo clippy -- -D clippy::await_holding_lock.
- βΉ Confirmed futures inside tokio::select! are cancellation-safe according to official Tokio contracts.
- βΉ CPU-bound tasks exceeding 100Β΅s isolated via tokio::task::spawn_blocking.
python3 skills/tokio-safety-auditor/scripts/audit_tokio.py --target ./src pyo3-zero-copy-bridge
Production FFI bridge generator connecting Python AI applications with Rust kernels. Enforces GIL release via py.allow_threads, NumPy/Arrow zero-copy contiguous memory sharing, and PyO3 0.21+ Bound lifetime boundary safety.
- β Generic LLMs hold the Python GIL during heavy SIMD or tensor computations, blocking all concurrent Python worker threads.
- β Agents generate naive vector conversions like array.to_vec() or Vec<f32>, triggering 100% heap copying on gigabyte-sized embeddings.
- β Outdated PyO3 code patterns produce raw pointer conversions that trigger segmentation faults when Python's garbage collector frees underlying arrays.
- β Missing Apache Arrow C Data Interface integration, falling back to slow serialized dictionary or pickle payloads.
- β Mandatory py.allow_threads closure for all numerical loops exceeding 50 microseconds.
- β Zero-copy NumPy tensor ingestion via numpy::PyReadonlyArray and .as_slice() with contiguous memory validation.
- β Direct Apache Arrow RecordBatch sharing using arrow::ffi C Data Interface pointers.
- β Strict adherence to PyO3 0.21+ Bound<'py, T> lifetime references with abi3-py310 stable ABI.
// [FAULT] Holds GIL during heavy SIMD computation
#[pyfunction]
pub fn process_embeddings(py: Python, arr: &PyArrayDyn<f32>) -> PyResult<Vec<f32>> {
let slice = arr.to_vec()?; // Copies entire buffer!
// GIL is held during parallel execution, freezing Python threads
let result: Vec<f32> = slice.par_iter().map(|&x| x * 2.0).collect();
Ok(result)
} // [SAFE] Zero-copy slice borrowed, GIL released for Rayon parallelism
#[pyfunction]
pub fn process_embeddings<'py>(
py: Python<'py>,
arr: PyReadonlyArrayDyn<'py, f32>,
) -> PyResult<Bound<'py, PyArrayDyn<f32>>> {
let slice = arr.as_slice()?; // Zero-copy borrow
let mut output = vec![0.0f32; slice.len()];
py.allow_threads(|| { // GIL released: Python threads continue unhindered
output.par_iter_mut().zip(slice.par_iter()).for_each(|(o, i)| *o = *i * 2.0);
});
Ok(PyArrayDyn::from_vec(py, output)) // Ownership transferred to Python GC
} // [FAULT] Serializing table via Python dictionary overhead
#[pyfunction]
pub fn ingest_features(py: Python, dict: &PyDict) -> PyResult<usize> {
// Iterating Python dict induces severe CPython interpreter overhead
let keys = dict.keys();
Ok(keys.len())
} // [SAFE] Direct C Data Interface pointer ingestion
#[pyfunction]
pub fn ingest_features(_py: Python, array_ptr: usize, schema_ptr: usize) -> PyResult<usize> {
let ffi_array = array_ptr as *mut arrow::ffi::FFI_ArrowArray;
let ffi_schema = schema_ptr as *mut arrow::ffi::FFI_ArrowSchema;
let (data, _schema) = unsafe { arrow::ffi::from_ffi(std::ptr::read(ffi_array), &std::ptr::read(ffi_schema))? };
let batch = arrow::record_batch::RecordBatch::from(arrow::array::make_array(data));
Ok(batch.num_rows()) // Zero bytes copied
} - βΉ Verified py.allow_threads wraps all computationally intensive loops.
- βΉ NumPy inputs validated for C-contiguity via .as_slice() prior to pointer extraction.
- βΉ Replaced legacy PyO3 pointer dereferencing with modern Bound<'py, T> types.
- βΉ Configured abi3-py310 stable ABI flags in Cargo.toml and pyproject.toml.
maturin develop --release && python3 skills/pyo3-zero-copy-bridge/template/test_bridge.py Architectural Philosophy: Why Agent Skills Matter for Systems Engineering
Rust enforces memory safety through ownership and borrow semantics at compile time, but it cannot prevent cooperative runtime starvation or FFI boundary mistakes. Specialized agent skills bridge this gap by constraining generative models to proven distributed and low-latency architectural patterns.
Asynchronous executors rely on cooperative yielding. Blocking I/O or mutex contention does not manifest as compiler errors: it manifests as severe latency tail spikes under production load.
In AI model serving and embeddings retrieval, tensor copying destroys throughput. Enforcing PyO3 contiguous slice borrowing and Apache Arrow C Data Interface guarantees zero-overhead interop.
Pairing LLM system prompt directives with strict compiler configurations (clippy.toml and disallowed-methods) creates a self-healing feedback loop for coding agents.