Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Heuristic:2giosangmitom Sqmeow nvim Cancellation Safety Patterns

From Leeroopedia
Knowledge Sources
Domains Debugging, Cancellation, Query_Execution, Editing
Last Updated 2026-10-16 14:00 GMT

Overview

Tribal knowledge for the await_sent and cancelled_after patterns that ensure cancelled writes report their true outcome rather than assuming a rollback, preventing data corruption from blind retries.

Description

When a user cancels a running query or edit application, the engine must distinguish between work that was stopped before any effect and work that partially completed. Two patterns enforce this:

  • await_sent: Before awaiting a non-transactional write, check the cancel token. If already cancelled, return Error::Cancelled without sending. If not cancelled, await the write — even if cancellation arrives mid-flight, the write's actual outcome (not an assumed rollback) is reported. A sent non-transactional write cannot be rolled back by dropping its reply.
  • cancelled_after: When a batch of changes is partially applied before cancellation, construct an error naming how many changes succeeded: "3 of 5 changes were applied before the rest were cancelled." This tells the user the data is in a partially-applied state.

The Deadline struct complements these by enforcing time-based cancellation. Its passed() flag distinguishes a timeout (the deadline tripped the token) from a user cancel, so the error message can say which.

Usage

Use this heuristic when:

  • Diagnosing partial applies: If an edit apply was cancelled, check the error message for "N of M changes were applied" — the database may be in a partial state.
  • Understanding write cancel messages: "query/write outcome may be unknown, verify before retrying" means a write was sent but its response was lost — check the data before re-running.
  • Distinguishing timeout vs cancel: The engine reports "the query ran past the N ms timeout" for deadlines and "cancelled" for user-initiated cancels.
  • Implementing adapter cancellation: Adapters must respect the CancellationToken and report actual outcomes, not assumed rollbacks.

The Insight (Rule of Thumb)

  • Action: Use await_sent for non-transactional writes — check cancel before sending, but always report the actual outcome. Use cancelled_after for partial batch applies.
  • Value: STOP_TIMEOUT = 2s (how long to wait for a server to acknowledge a cancel before leaving it be). Deadline::passed() distinguishes timeout from user cancel.
  • Trade-off: Honest cancellation reporting means the user may need to manually verify data state after a partial apply. The alternative — assuming rollback — would be incorrect and could cause data loss from blind retries.
  • Compatibility: Write statements are never cancelled mid-flight; only read-shaped batches are interruptible. Transactional applies roll back cleanly; non-transactional applies may leave partial state.

Reasoning

The fundamental insight is that a sent write cannot be un-sent. If the engine sends an INSERT and the user cancels before the response arrives, the row may already be in the table. Reporting Cancelled and assuming a rollback would be wrong — the user might re-run the apply, duplicating the insert.

Instead, await_sent checks the token before awaiting the write future. If the token is already tripped, it returns immediately without sending. If not, it awaits the write — the write's actual result (success or error) is what gets reported, not Cancelled.

For batch applies, cancelled_after(done, total) constructs a descriptive error. If 3 of 5 statements ran before the cancel, the user knows exactly what state the database is in and can decide whether to retry, rollback manually, or proceed.

The Deadline adds time-based cancellation. When timeout_ms passes, the deadline's timer trips the same CancellationToken. The passed() atomic flag records that it was the deadline (not the user) that tripped it, so the engine can emit "ran past the timeout" instead of "cancelled."

Code Evidence

await_sent from core/sqmeow-adapters/src/lib.rs:58-68:

/// A sent nontransactional write cannot be rolled back by dropping its reply.
/// Cancellation stops the next write, not the observation of this one's outcome.
pub(crate) async fn await_sent<T>(
    cancel: &CancellationToken,
    work: impl std::future::Future<Output = T>,
) -> Result<T> {
    if cancel.is_cancelled() {
        return Err(Error::Cancelled);
    }
    Ok(work.await)
}

cancelled_after from core/sqmeow-adapters/src/lib.rs:48-56:

/// A cancel that stopped an apply without transactions, which keeps what ran before it.
pub(crate) fn cancelled_after(done: usize, total: usize) -> Error {
    if done == 0 {
        return Error::Cancelled;
    }
    Error::driver(format!(
        "{done} of {total} changes were applied before the rest were cancelled"
    ))
}

STOP_TIMEOUT from core/sqmeow-adapters/src/lib.rs:46:

/// How long to spend telling a server to stop a cancelled query before leaving it be.
pub(crate) const STOP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);

Deadline passed() flag from core/sqmeow-core/src/server/calls.rs:36-60:

pub(super) struct Deadline {
    timer: Option<tokio::task::JoinHandle<()>>,
    passed: Arc<AtomicBool>,
}

impl Deadline {
    pub(super) fn start(token: CancellationToken, timeout_ms: u64) -> Self {
        let passed = Arc::new(AtomicBool::new(false));
        let timer = (timeout_ms > 0).then(|| {
            let passed = Arc::clone(&passed);
            tokio::spawn(async move {
                tokio::time::sleep(Duration::from_millis(timeout_ms)).await;
                passed.store(true, Ordering::Relaxed);
                token.cancel();
            })
        });
        Self { timer, passed }
    }

    /// Whether the deadline, rather than a cancel, tripped the token.
    pub(super) fn passed(&self) -> bool {
        self.passed.load(Ordering::Relaxed)
    }
}

Timeout vs cancel distinction from core/sqmeow-core/src/server/calls.rs:427-436:

let (state, error) = match error {
    DbError::Cancelled if deadline.passed() => (
        "error",
        Some(format!(
            "the query ran past the {} ms timeout, so it was cancelled",
            options.timeout_ms
        )),
    ),
    DbError::Cancelled => ("cancelled", None),
    error => ("error", Some(error.to_string())),
};

MySQL cancel-cleanup warning from core/sqmeow-adapters/src/mysql.rs:184:

Err(Error::driver("cancel cleanup timed out; query/write outcome may be unknown, verify before retrying"))

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment