Skip to content

COW Rust Acceleration Analysis

Current Performance Bottlenecks

Even with our optimized Python implementation (10.51x faster), we still have hot paths that could benefit from Rust:

1. Synthesis Hot Paths

  • Dictionary operations: Creating result dict, merging mutations
  • Attribute filtering: Checking against whitelist sets
  • JSON serialization: Converting to final output

2. Token/Output Creation

  • Class instantiation: Creating output accessor classes
  • Cache lookups: Checking _output_cache dictionary
  • Type checking: Runtime type validation

3. Attribute Access

  • Property getters/setters: Python descriptor protocol overhead
  • Mutation tracking: Set operations for _dirty_attrs

Rust Acceleration Opportunities

Phase 1: Core Data Structures (Highest Impact)

use pyo3::prelude::*;
use pyo3::types::{PyDict, PyString, PyAny};
use std::collections::{HashMap, HashSet};
use ahash::AHashMap; // Faster hasher

#[pyclass]
struct ImmutableResourceData {
    // Pre-filtered, immutable attributes
    attrs: AHashMap<String, PyObject>,
    resource_type: String,
    // Pre-computed for fast synthesis
    json_bytes: Option<Vec<u8>>,
}

#[pymethods]
impl ImmutableResourceData {
    #[new]
    fn new(resource_type: String, attrs: &PyDict, whitelist: HashSet<String>) -> PyResult<Self> {
        let py = attrs.py();
        let mut filtered = AHashMap::new();

        // Fast filtering with Rust iteration
        for (key, value) in attrs.iter() {
            let key_str: String = key.extract()?;
            if whitelist.contains(&key_str) {
                filtered.insert(key_str, value.to_object(py));
            }
        }

        Ok(Self {
            attrs: filtered,
            resource_type,
            json_bytes: None,
        })
    }

    fn get(&self, key: &str) -> Option<PyObject> {
        self.attrs.get(key).cloned()
    }

    // Zero-copy synthesis for unmodified resources
    fn synthesize_fast(&mut self, py: Python) -> PyResult<PyObject> {
        if let Some(ref bytes) = self.json_bytes {
            // Return cached JSON bytes directly
            Ok(PyBytes::new(py, bytes).into())
        } else {
            // First time - serialize and cache
            let json = simd_json::to_vec(&self.attrs)?;
            self.json_bytes = Some(json.clone());
            Ok(PyBytes::new(py, &json).into())
        }
    }
}

Expected Performance Gain: 5-10x for synthesis operations

Phase 2: Mutation Tracking

#[pyclass]
struct MutationTracker {
    mutations: AHashMap<String, PyObject>,
    dirty_attrs: HashSet<String>,
    stats: ResourceStats,
}

#[pymethods]
impl MutationTracker {
    fn set_attribute(&mut self, name: String, value: PyObject) {
        self.mutations.insert(name.clone(), value);
        self.dirty_attrs.insert(name);
        self.stats.mutation_count += 1;
    }

    // Merge with immutable base - optimized for COW
    fn merge_with_base(&self, base: &ImmutableResourceData, whitelist: &HashSet<String>) -> PyResult<PyObject> {
        let mut result = base.attrs.clone();

        // Only merge whitelisted mutations
        for (key, value) in &self.mutations {
            if whitelist.contains(key) {
                result.insert(key.clone(), value.clone());
            }
        }

        // Use SIMD JSON for fast serialization
        Python::with_gil(|py| {
            let dict = PyDict::new(py);
            for (k, v) in result {
                dict.set_item(k, v)?;
            }
            Ok(dict.into())
        })
    }
}

Expected Performance Gain: 3-5x for mutated resources

Phase 3: Batch Operations

#[pyfunction]
fn batch_create_resources(
    resource_type: &str,
    resources_data: Vec<HashMap<String, PyObject>>,
    whitelist: HashSet<String>,
) -> PyResult<Vec<ImmutableResourceData>> {
    // Parallel creation using Rayon
    use rayon::prelude::*;

    resources_data
        .into_par_iter()
        .map(|attrs| {
            ImmutableResourceData::new(
                resource_type.to_string(),
                attrs,
                whitelist.clone()
            )
        })
        .collect::<Result<Vec<_>, _>>()
}

#[pyfunction]
fn batch_synthesize(resources: Vec<&mut ImmutableResourceData>) -> PyResult<Vec<PyObject>> {
    // SIMD-accelerated batch synthesis
    use rayon::prelude::*;

    Python::with_gil(|py| {
        resources
            .par_iter_mut()
            .map(|res| res.synthesize_fast(py))
            .collect()
    })
}

Expected Performance Gain: 10-20x for batch operations

Implementation Strategy

Step 1: Minimal Rust Extension (1 week)

# Python wrapper
class RustAcceleratedCowResource(Resource):
    def __init__(self, **kwargs):
        # Use Rust for data storage
        self._rust_data = rust_cow.ImmutableResourceData(self._resource_type, kwargs, self._SYNTH_ATTRS)
        self._mutations = rust_cow.MutationTracker()

    def synthesize_attributes(self):
        if not self._mutations.has_mutations():
            # Fast path: pure Rust
            return self._rust_data.synthesize_fast()
        else:
            # Merge in Rust
            return self._mutations.merge_with_base(self._rust_data, self._SYNTH_ATTRS)

Step 2: Optimize Hot Paths (1 week)

  • Property access via Rust
  • Token caching in Rust
  • Batch synthesis operations

Step 3: Advanced Features (2 weeks)

  • SIMD JSON serialization
  • Memory pooling for allocations
  • Zero-copy Python interop

Performance Projections

Based on similar Rust accelerations in Python projects:

Operation Current (Optimized Python) With Rust Improvement
Resource Creation 0.01ms 0.001ms 10x
Synthesis (no mutations) 0.0004ms 0.00004ms 10x
Synthesis (with mutations) 0.001ms 0.0002ms 5x
Batch Creation (1000) 10ms 0.5ms 20x
JSON Serialization 0.1ms 0.005ms 20x

Overall Expected Improvement

  • Single resource operations: 15-20x faster than standard Python
  • Batch operations: 50-100x faster than standard Python
  • Memory usage: 60-80% reduction

Specific Benefits for COW Pattern

  1. Immutable Data Sharing: Rust's Arc enables true zero-cost sharing
  2. Lock-Free Reads: No GIL contention for read operations
  3. SIMD Operations: Bulk attribute processing
  4. Memory Safety: Guaranteed COW semantics without defensive copies

Recommendation

While our Python optimization achieved excellent results (10.51x), Rust acceleration would provide:

  1. Another 5-10x improvement on top of current gains
  2. Consistent sub-millisecond synthesis for 1000+ resources
  3. True zero-copy operations for unchanged resources
  4. Parallel batch operations without GIL limitations

The highest ROI would be: 1. Start with ImmutableResourceData in Rust 2. Add batch operations 3. Gradually move hot paths as profiling indicates

This would give us 50-100x total improvement over standard implementation while maintaining Python API compatibility.