mindreader 0.7.0

Selective durable graph memory MCP server for AI agents, backed by Neo4j
Documentation
//! Cancellation-safe transaction phases for bounded MCP mutations.
//!
//! The pre-commit deadline is safe to cancel because this module still owns
//! the transaction and attempts a bounded rollback. Once commit starts, the
//! transaction moves into a detached task: timing out the acknowledgement can
//! report only an ambiguous outcome and must not cancel the Bolt `COMMIT`.

use crate::error::{Error, Result};
use neo4rs::{Graph, Txn};
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
use tokio::task::JoinHandle;
use tokio::time::{timeout, timeout_at, Instant};

/// Transactional work must finish before this point in an MCP mutation.
const MCP_PRECOMMIT_TIMEOUT: Duration = Duration::from_secs(10);
/// Time reserved for the independently owned Bolt `COMMIT` acknowledgement.
const MCP_COMMIT_ACK_TIMEOUT: Duration = Duration::from_secs(3);
/// Best-effort time reserved to send `ROLLBACK` after a pre-commit timeout.
const MCP_ROLLBACK_TIMEOUT: Duration = Duration::from_secs(1);
/// Post-commit fuzzy review is advisory and may consume only this budget.
const MCP_REVIEW_TIMEOUT: Duration = Duration::from_secs(1);

/// Per-call mutation bounds. In-process tools remain unbounded; MCP supplies [`Self::mcp`].
#[derive(Clone, Copy)]
pub(crate) struct MutationBudget {
    precommit_deadline: Option<Instant>,
    commit_ack_timeout: Option<Duration>,
    rollback_timeout: Option<Duration>,
    review_timeout: Option<Duration>,
}

impl MutationBudget {
    /// Preserve the application boundary's unbounded behavior outside MCP handlers.
    #[cfg(feature = "developer-tools")]
    pub(crate) const fn unbounded() -> Self {
        Self {
            precommit_deadline: None,
            commit_ack_timeout: None,
            rollback_timeout: None,
            review_timeout: None,
        }
    }

    /// Reserve response time inside the MCP adapter's 15-second mutation ceiling.
    pub(crate) fn mcp() -> Self {
        Self {
            precommit_deadline: Some(Instant::now() + MCP_PRECOMMIT_TIMEOUT),
            commit_ack_timeout: Some(MCP_COMMIT_ACK_TIMEOUT),
            rollback_timeout: Some(MCP_ROLLBACK_TIMEOUT),
            review_timeout: Some(MCP_REVIEW_TIMEOUT),
        }
    }

    #[cfg(test)]
    fn test_bounded(
        precommit_timeout: Duration,
        commit_ack_timeout: Duration,
        rollback_timeout: Duration,
        review_timeout: Duration,
    ) -> Self {
        Self {
            precommit_deadline: Some(Instant::now() + precommit_timeout),
            commit_ack_timeout: Some(commit_ack_timeout),
            rollback_timeout: Some(rollback_timeout),
            review_timeout: Some(review_timeout),
        }
    }
}

/// Whether successful pre-commit work should be committed or intentionally rolled back.
pub(crate) enum TransactionDisposition<T> {
    /// The body changed authoritative state and must commit atomically.
    Commit(T),
    /// The body was a no-op and must record no Episode or graph changes.
    Rollback(T),
}

/// Boxed transaction body whose future may borrow the owned transaction.
pub(crate) type TransactionFuture<'a, T> =
    Pin<Box<dyn Future<Output = Result<TransactionDisposition<T>>> + Send + 'a>>;

/// Bound non-transactional preparation that is still known safe to cancel.
pub(crate) async fn run_precommit<T, Fut>(
    operation: &'static str,
    budget: MutationBudget,
    future: Fut,
) -> Result<T>
where
    Fut: Future<Output = Result<T>>,
{
    match budget.precommit_deadline {
        Some(deadline) => match timeout_at(deadline, future).await {
            Ok(result) => result,
            Err(_) => Err(Error::MutationTimeout { operation }),
        },
        None => future.await,
    }
}

/// Run one transaction with a cancellable pre-commit phase and uncancellable commit ownership.
pub(crate) async fn run_transaction<T, F>(
    graph: &Graph,
    operation: &'static str,
    budget: MutationBudget,
    body: F,
) -> Result<T>
where
    T: Send,
    F: for<'a> FnOnce(&'a mut Txn) -> TransactionFuture<'a, T>,
{
    let mut txn = match budget.precommit_deadline {
        Some(deadline) => match timeout_at(deadline, graph.start_txn()).await {
            Ok(result) => result?,
            Err(_) => return Err(Error::MutationTimeout { operation }),
        },
        None => graph.start_txn().await?,
    };

    let disposition = match budget.precommit_deadline {
        Some(deadline) => match timeout_at(deadline, body(&mut txn)).await {
            Ok(result) => result,
            Err(_) => {
                rollback(txn, budget.rollback_timeout).await;
                return Err(Error::MutationTimeout { operation });
            }
        },
        None => body(&mut txn).await,
    };

    match disposition {
        Ok(TransactionDisposition::Commit(value)) => {
            commit(txn, operation, budget.commit_ack_timeout).await?;
            Ok(value)
        }
        Ok(TransactionDisposition::Rollback(value)) => {
            rollback(txn, budget.rollback_timeout).await;
            Ok(value)
        }
        Err(error) => {
            rollback(txn, budget.rollback_timeout).await;
            Err(error)
        }
    }
}

/// Run advisory post-commit work without allowing failure or latency to change write success.
pub(crate) async fn best_effort_review<T, Fut, E>(
    budget: MutationBudget,
    review: Fut,
    fallback: T,
) -> T
where
    Fut: Future<Output = std::result::Result<T, E>>,
{
    match budget.review_timeout {
        Some(limit) => match timeout(limit, review).await {
            Ok(Ok(value)) => value,
            Ok(Err(_)) | Err(_) => fallback,
        },
        None => review.await.unwrap_or(fallback),
    }
}

/// Preserve the acknowledged outcome when fallible response work runs after commit.
pub(crate) fn mutation_response<T>(
    operation: &'static str,
    applied: bool,
    response: Result<T>,
) -> Result<T> {
    response.map_err(|source| {
        if applied {
            Error::MutationApplied {
                operation,
                source: Box::new(source),
            }
        } else {
            source
        }
    })
}

/// Attempt rollback within its reserved budget. No `COMMIT` has been sent on this path.
async fn rollback(txn: Txn, rollback_timeout: Option<Duration>) {
    match rollback_timeout {
        Some(limit) => {
            let _ = timeout(limit, txn.rollback()).await;
        }
        None => {
            let _ = txn.rollback().await;
        }
    }
}

/// Commit directly for in-process calls or in a detached task for bounded MCP calls.
async fn commit(
    txn: Txn,
    operation: &'static str,
    commit_ack_timeout: Option<Duration>,
) -> Result<()> {
    let result = match commit_ack_timeout {
        Some(limit) => match await_detached(txn.commit(), limit).await {
            DetachedResult::Completed(result) => result,
            DetachedResult::TimedOut => {
                return Err(Error::CommitOutcomeUnknown {
                    operation,
                    message: "commit acknowledgement timed out; reconciliation is required".into(),
                })
            }
            DetachedResult::TaskFailed(message) => {
                return Err(Error::CommitOutcomeUnknown { operation, message })
            }
        },
        None => txn.commit().await,
    };
    result.map_err(|source| Error::AmbiguousCommit { operation, source })
}

/// Outcome of waiting on an independently owned future without aborting it on timeout.
enum DetachedResult<T> {
    Completed(T),
    TimedOut,
    TaskFailed(String),
}

/// Spawn first, then bound only the acknowledgement wait; dropping the handle detaches the task.
async fn await_detached<F, T>(future: F, limit: Duration) -> DetachedResult<T>
where
    F: Future<Output = T> + Send + 'static,
    T: Send + 'static,
{
    let mut task: JoinHandle<T> = tokio::spawn(future);
    match timeout(limit, &mut task).await {
        Ok(Ok(value)) => DetachedResult::Completed(value),
        Ok(Err(error)) => DetachedResult::TaskFailed(error.to_string()),
        Err(_) => DetachedResult::TimedOut,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;
    use tokio::sync::oneshot;
    use tokio::time::advance;

    struct DropSignal(Arc<AtomicBool>);

    impl Drop for DropSignal {
        fn drop(&mut self) {
            self.0.store(true, Ordering::SeqCst);
        }
    }

    #[test]
    fn mcp_phase_budgets_fit_the_fifteen_second_ceiling() {
        assert_eq!(MCP_PRECOMMIT_TIMEOUT, Duration::from_secs(10));
        assert_eq!(MCP_COMMIT_ACK_TIMEOUT, Duration::from_secs(3));
        assert_eq!(MCP_ROLLBACK_TIMEOUT, Duration::from_secs(1));
        assert_eq!(MCP_REVIEW_TIMEOUT, Duration::from_secs(1));
        assert!(
            MCP_PRECOMMIT_TIMEOUT + MCP_COMMIT_ACK_TIMEOUT + MCP_REVIEW_TIMEOUT
                < Duration::from_secs(15)
        );
    }

    #[tokio::test(start_paused = true)]
    async fn precommit_timeout_drops_work_before_commit_can_start() {
        let dropped = Arc::new(AtomicBool::new(false));
        let signal = DropSignal(dropped.clone());
        let budget = MutationBudget::test_bounded(
            Duration::from_secs(10),
            Duration::from_secs(1),
            Duration::from_secs(1),
            Duration::from_secs(1),
        );
        let task = tokio::spawn(async move {
            run_precommit("write", budget, async move {
                let _signal = signal;
                std::future::pending::<Result<()>>().await
            })
            .await
        });

        tokio::task::yield_now().await;
        advance(Duration::from_secs(10)).await;
        assert!(matches!(
            task.await.unwrap(),
            Err(Error::MutationTimeout { operation: "write" })
        ));
        assert!(dropped.load(Ordering::SeqCst));
    }

    #[tokio::test(start_paused = true)]
    async fn commit_timeout_detaches_in_flight_commit_instead_of_cancelling_it() {
        let (release_tx, release_rx) = oneshot::channel();
        let completed = Arc::new(AtomicBool::new(false));
        let committed = completed.clone();
        let wait = tokio::spawn(async move {
            await_detached(
                async move {
                    let _ = release_rx.await;
                    committed.store(true, Ordering::SeqCst);
                },
                Duration::from_secs(5),
            )
            .await
        });

        tokio::task::yield_now().await;
        advance(Duration::from_secs(5)).await;
        assert!(matches!(wait.await.unwrap(), DetachedResult::TimedOut));
        assert!(!completed.load(Ordering::SeqCst));

        release_tx.send(()).unwrap();
        tokio::task::yield_now().await;
        assert!(completed.load(Ordering::SeqCst));
    }

    #[tokio::test(start_paused = true)]
    async fn commit_acknowledged_near_deadline_still_succeeds() {
        let (release_tx, release_rx) = oneshot::channel();
        let wait = tokio::spawn(async move {
            await_detached(
                async move {
                    release_rx.await.unwrap();
                    "committed"
                },
                Duration::from_secs(5),
            )
            .await
        });

        tokio::task::yield_now().await;
        advance(Duration::from_millis(4_999)).await;
        release_tx.send(()).unwrap();
        tokio::task::yield_now().await;
        assert!(matches!(
            wait.await.unwrap(),
            DetachedResult::Completed("committed")
        ));
    }

    #[tokio::test(start_paused = true)]
    async fn stalled_advisory_review_cannot_change_authoritative_success() {
        let budget = MutationBudget::test_bounded(
            Duration::from_secs(1),
            Duration::from_secs(1),
            Duration::from_secs(1),
            Duration::from_secs(2),
        );
        let dropped = Arc::new(AtomicBool::new(false));
        let signal = DropSignal(dropped.clone());
        let task = tokio::spawn(async move {
            let authoritative = "committed";
            let review = best_effort_review(
                budget,
                async move {
                    let _signal = signal;
                    std::future::pending::<std::result::Result<Vec<String>, ()>>().await
                },
                Vec::new(),
            )
            .await;
            (authoritative, review)
        });

        tokio::task::yield_now().await;
        advance(Duration::from_secs(2)).await;
        let (authoritative, review) = task.await.unwrap();
        assert_eq!(authoritative, "committed");
        assert!(review.is_empty());
        assert!(dropped.load(Ordering::SeqCst));
    }

    #[test]
    fn postcommit_response_failure_preserves_applied_outcome() {
        let applied = mutation_response::<()>(
            "write",
            true,
            Err(Error::Operation("malformed response".into())),
        )
        .unwrap_err();
        assert!(matches!(
            applied,
            Error::MutationApplied {
                operation: "write",
                ..
            }
        ));

        let noop = mutation_response::<()>(
            "write",
            false,
            Err(Error::Operation("malformed response".into())),
        )
        .unwrap_err();
        assert!(matches!(noop, Error::Operation(_)));
    }
}