mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 09:15:33 +08:00
fix: harden concurrent persistence and task recovery
This commit is contained in:
1 parent
9deb42915c
commit
df053c3720
21 files changed
+1083
-90
No files matched your search
+16
-5
@@ -1,6 +1,6 @@
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::Row;
|
||||
use sqlx::{Row, Sqlite, Transaction};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
@@ -44,13 +44,25 @@ pub struct BlobEdge {
|
||||
|
||||
impl Store {
|
||||
pub async fn put_blob(&self, data: &[u8], edges: &[BlobEdge]) -> Result<BlobId> {
|
||||
let _write = self.writes.lock().await;
|
||||
let blob_id = BlobId::digest(data);
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
Self::put_blob_tx(&mut tx, &blob_id, data, edges).await?;
|
||||
tx.commit().await?;
|
||||
Ok(blob_id)
|
||||
}
|
||||
|
||||
pub(crate) async fn put_blob_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
blob_id: &BlobId,
|
||||
data: &[u8],
|
||||
edges: &[BlobEdge],
|
||||
) -> Result<()> {
|
||||
sqlx::query("INSERT OR IGNORE INTO blobs(blob_id, data, created_at_ms) VALUES (?, ?, ?)")
|
||||
.bind(blob_id.as_bytes().as_slice())
|
||||
.bind(data)
|
||||
.bind(now_ms())
|
||||
.execute(&mut *tx)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
for edge in edges {
|
||||
sqlx::query(
|
||||
@@ -59,11 +71,10 @@ impl Store {
|
||||
.bind(blob_id.as_bytes().as_slice())
|
||||
.bind(edge.child.as_bytes().as_slice())
|
||||
.bind(&edge.field_name)
|
||||
.execute(&mut *tx)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(blob_id)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_blob(&self, blob_id: &BlobId) -> Result<Option<Vec<u8>>> {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use sqlx::Row;
|
||||
use sqlx::{Row, Sqlite, Transaction};
|
||||
|
||||
use crate::{
|
||||
model::{CursorRunTraceArtifact, CursorRunTraceSummary},
|
||||
@@ -7,6 +7,21 @@ use crate::{
|
||||
|
||||
use super::{now_ms, BlobId, Store};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct BufferedCursorTraceChunk {
|
||||
pub(crate) source: String,
|
||||
pub(crate) data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl BufferedCursorTraceChunk {
|
||||
pub(crate) fn new(source: &str, data: &[u8]) -> Self {
|
||||
Self {
|
||||
source: source.into(),
|
||||
data: data.to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub async fn start_cursor_trace_if_detailed(
|
||||
&self,
|
||||
@@ -21,6 +36,7 @@ impl Store {
|
||||
if !self.detailed_logging().await? {
|
||||
return Ok(false);
|
||||
}
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"INSERT OR IGNORE INTO cursor_run_traces(
|
||||
request_id, conversation_id, route, model_id, status, received_at_ms
|
||||
@@ -53,9 +69,22 @@ impl Store {
|
||||
data: &[u8],
|
||||
metadata: &serde_json::Value,
|
||||
) -> Result<()> {
|
||||
let blob_id = self.put_blob(data, &[]).await?;
|
||||
self.link_cursor_trace_artifact(request_id, artifact_type, source, &blob_id, metadata)
|
||||
.await
|
||||
let metadata_json = serde_json::to_string(metadata)?;
|
||||
let blob_id = BlobId::digest(data);
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
Self::put_blob_tx(&mut tx, &blob_id, data, &[]).await?;
|
||||
Self::link_cursor_trace_artifact_tx(
|
||||
&mut tx,
|
||||
request_id,
|
||||
artifact_type,
|
||||
source,
|
||||
&blob_id,
|
||||
&metadata_json,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn link_cursor_trace_artifact(
|
||||
@@ -66,13 +95,36 @@ impl Store {
|
||||
blob_id: &BlobId,
|
||||
metadata: &serde_json::Value,
|
||||
) -> Result<()> {
|
||||
let metadata_json = serde_json::to_string(metadata)?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
Self::link_cursor_trace_artifact_tx(
|
||||
&mut tx,
|
||||
request_id,
|
||||
artifact_type,
|
||||
source,
|
||||
blob_id,
|
||||
&metadata_json,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn link_cursor_trace_artifact_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
request_id: &str,
|
||||
artifact_type: &str,
|
||||
source: &str,
|
||||
blob_id: &BlobId,
|
||||
metadata_json: &str,
|
||||
) -> Result<()> {
|
||||
let next: i64 = sqlx::query_scalar(
|
||||
"SELECT COALESCE(MAX(seq), -1) + 1
|
||||
FROM cursor_run_trace_artifacts WHERE request_id = ?",
|
||||
)
|
||||
.bind(request_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO cursor_run_trace_artifacts(
|
||||
@@ -84,11 +136,10 @@ impl Store {
|
||||
.bind(artifact_type)
|
||||
.bind(source)
|
||||
.bind(blob_id.as_bytes().as_slice())
|
||||
.bind(serde_json::to_string(metadata)?)
|
||||
.bind(metadata_json)
|
||||
.bind(now_ms())
|
||||
.execute(&mut *tx)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -97,6 +148,7 @@ impl Store {
|
||||
request_id: &str,
|
||||
bytes: usize,
|
||||
) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"UPDATE cursor_run_traces
|
||||
SET request_bytes = request_bytes + ? WHERE request_id = ?",
|
||||
@@ -110,6 +162,7 @@ impl Store {
|
||||
|
||||
pub async fn start_cursor_trace_response(&self, request_id: &str, status: u16) -> Result<()> {
|
||||
let now = now_ms();
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"UPDATE cursor_run_traces
|
||||
SET status = 'running', http_status = ?,
|
||||
@@ -131,30 +184,58 @@ impl Store {
|
||||
source: &str,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
self.append_cursor_trace_artifact(
|
||||
self.add_cursor_trace_response_chunks(
|
||||
request_id,
|
||||
"run_sse_chunk",
|
||||
source,
|
||||
data,
|
||||
&serde_json::json!({"byte_count": data.len()}),
|
||||
&[BufferedCursorTraceChunk::new(source, data)],
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn add_cursor_trace_response_chunks(
|
||||
&self,
|
||||
request_id: &str,
|
||||
chunks: &[BufferedCursorTraceChunk],
|
||||
) -> Result<()> {
|
||||
if chunks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let response_bytes = chunks.iter().map(|chunk| chunk.data.len()).sum::<usize>();
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
for chunk in chunks {
|
||||
let metadata_json =
|
||||
serde_json::to_string(&serde_json::json!({"byte_count": chunk.data.len()}))?;
|
||||
let blob_id = BlobId::digest(&chunk.data);
|
||||
Self::put_blob_tx(&mut tx, &blob_id, &chunk.data, &[]).await?;
|
||||
Self::link_cursor_trace_artifact_tx(
|
||||
&mut tx,
|
||||
request_id,
|
||||
"run_sse_chunk",
|
||||
&chunk.source,
|
||||
&blob_id,
|
||||
&metadata_json,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
sqlx::query(
|
||||
"UPDATE cursor_run_traces
|
||||
SET response_bytes = response_bytes + ?,
|
||||
response_event_count = response_event_count + 1,
|
||||
response_event_count = response_event_count + ?,
|
||||
first_response_at_ms = COALESCE(first_response_at_ms, ?)
|
||||
WHERE request_id = ?",
|
||||
)
|
||||
.bind(as_i64(data.len()))
|
||||
.bind(as_i64(response_bytes))
|
||||
.bind(chunks.len() as i64)
|
||||
.bind(now_ms())
|
||||
.bind(request_id)
|
||||
.execute(&self.pool)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn finish_cursor_trace(&self, request_id: &str, error: Option<&str>) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"UPDATE cursor_run_traces
|
||||
SET status = ?, finished_at_ms = ?, error_message = ?
|
||||
@@ -244,3 +325,61 @@ fn trace_from_row(row: sqlx::sqlite::SqliteRow) -> Result<CursorRunTraceSummary>
|
||||
fn as_i64(value: usize) -> i64 {
|
||||
value.min(i64::MAX as usize) as i64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn records_a_batch_of_trace_chunks_with_one_summary_update() {
|
||||
let store = Store::connect("sqlite::memory:").await.unwrap();
|
||||
store.set_detailed_logging(true).await.unwrap();
|
||||
store
|
||||
.start_cursor_trace_if_detailed("trace", None, "cursor_official", None)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("CREATE TABLE trace_summary_updates(count INTEGER NOT NULL)")
|
||||
.execute(store.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO trace_summary_updates(count) VALUES (0)")
|
||||
.execute(store.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"CREATE TRIGGER count_trace_summary_updates
|
||||
AFTER UPDATE OF response_bytes ON cursor_run_traces
|
||||
BEGIN
|
||||
UPDATE trace_summary_updates SET count = count + 1;
|
||||
END",
|
||||
)
|
||||
.execute(store.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
store
|
||||
.add_cursor_trace_response_chunks(
|
||||
"trace",
|
||||
&[
|
||||
BufferedCursorTraceChunk::new("cursor_official", b"one"),
|
||||
BufferedCursorTraceChunk::new("cursor_official", b"two"),
|
||||
BufferedCursorTraceChunk::new("cursor_official", b"three"),
|
||||
],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let trace = store.cursor_trace("trace").await.unwrap().unwrap();
|
||||
assert_eq!(trace.response_bytes, 11);
|
||||
assert_eq!(trace.response_event_count, 3);
|
||||
assert_eq!(
|
||||
store.cursor_trace_artifacts("trace").await.unwrap().len(),
|
||||
3
|
||||
);
|
||||
let updates: i64 = sqlx::query_scalar("SELECT count FROM trace_summary_updates")
|
||||
.fetch_one(store.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(updates, 1);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ impl Store {
|
||||
input_id: &str,
|
||||
base_revision_id: RevisionId,
|
||||
) -> Result<RevisionId> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO input_anchors
|
||||
|
||||
+208
-17
@@ -12,6 +12,34 @@ use crate::{
|
||||
|
||||
use super::{now_ms, Store};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct BufferedLlmChunk {
|
||||
pub(crate) seq: i64,
|
||||
pub(crate) elapsed_ms: i64,
|
||||
pub(crate) data: Option<Vec<u8>>,
|
||||
pub(crate) byte_count: usize,
|
||||
}
|
||||
|
||||
impl BufferedLlmChunk {
|
||||
pub(crate) fn new(seq: i64, elapsed_ms: i64, data: &[u8]) -> Self {
|
||||
Self {
|
||||
seq,
|
||||
elapsed_ms,
|
||||
data: Some(data.to_vec()),
|
||||
byte_count: data.len(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn metrics(seq: i64, elapsed_ms: i64, byte_count: usize) -> Self {
|
||||
Self {
|
||||
seq,
|
||||
elapsed_ms,
|
||||
data: None,
|
||||
byte_count,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub async fn detailed_logging(&self) -> Result<bool> {
|
||||
let value: String = sqlx::query_scalar(
|
||||
@@ -23,6 +51,7 @@ impl Store {
|
||||
}
|
||||
|
||||
pub async fn set_detailed_logging(&self, enabled: bool) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES ('llm_detailed_logging', ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms",
|
||||
)
|
||||
@@ -34,6 +63,7 @@ impl Store {
|
||||
}
|
||||
|
||||
pub async fn start_llm_call(&self, call: &NewLlmCall) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
let now = now_ms();
|
||||
sqlx::query(
|
||||
r#"INSERT INTO llm_calls(
|
||||
@@ -74,21 +104,27 @@ impl Store {
|
||||
detailed: bool,
|
||||
) -> Result<()> {
|
||||
let body_json = serde_json::to_string(body)?;
|
||||
let headers_json = detailed
|
||||
.then(|| serde_json::to_string(headers))
|
||||
.transpose()?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
if detailed {
|
||||
sqlx::query("INSERT INTO llm_call_requests(call_id, headers_json, body_json, byte_count) SELECT ?, ?, ?, ? WHERE EXISTS (SELECT 1 FROM llm_calls WHERE call_id = ?)")
|
||||
.bind(call_id)
|
||||
.bind(serde_json::to_string(headers)?)
|
||||
.bind(headers_json)
|
||||
.bind(&body_json)
|
||||
.bind(body_json.len() as i64)
|
||||
.bind(call_id)
|
||||
.execute(&self.pool)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
sqlx::query("UPDATE llm_calls SET request_bytes = ? WHERE call_id = ?")
|
||||
.bind(body_json.len() as i64)
|
||||
.bind(call_id)
|
||||
.execute(&self.pool)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -98,6 +134,7 @@ impl Store {
|
||||
elapsed_ms: i64,
|
||||
http_status: u16,
|
||||
) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("UPDATE llm_calls SET response_headers_at_ms = ?, ttfb_ms = ?, http_status = ? WHERE call_id = ?")
|
||||
.bind(now_ms())
|
||||
.bind(elapsed_ms)
|
||||
@@ -116,21 +153,50 @@ impl Store {
|
||||
data: &[u8],
|
||||
detailed: bool,
|
||||
) -> Result<()> {
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
if detailed {
|
||||
sqlx::query("INSERT INTO llm_call_response_chunks(call_id, seq, received_offset_ms, data, byte_count) SELECT ?, ?, ?, ?, ? WHERE EXISTS (SELECT 1 FROM llm_calls WHERE call_id = ?)")
|
||||
.bind(call_id)
|
||||
.bind(seq)
|
||||
.bind(elapsed_ms)
|
||||
.bind(data)
|
||||
.bind(data.len() as i64)
|
||||
.bind(call_id)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
let chunk = if detailed {
|
||||
BufferedLlmChunk::new(seq, elapsed_ms, data)
|
||||
} else {
|
||||
BufferedLlmChunk::metrics(seq, elapsed_ms, data.len())
|
||||
};
|
||||
self.record_llm_chunks(call_id, &[chunk], detailed).await
|
||||
}
|
||||
|
||||
pub(crate) async fn record_llm_chunks(
|
||||
&self,
|
||||
call_id: &str,
|
||||
chunks: &[BufferedLlmChunk],
|
||||
detailed: bool,
|
||||
) -> Result<()> {
|
||||
if chunks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
sqlx::query("UPDATE llm_calls SET first_event_at_ms = COALESCE(first_event_at_ms, ?), response_bytes = response_bytes + ?, stream_event_count = stream_event_count + 1 WHERE call_id = ?")
|
||||
let byte_count = chunks
|
||||
.iter()
|
||||
.map(|chunk| chunk.byte_count as i64)
|
||||
.sum::<i64>();
|
||||
let event_count = chunks.len() as i64;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
if detailed {
|
||||
for chunk in chunks {
|
||||
let data = chunk.data.as_deref().ok_or_else(|| {
|
||||
crate::Error::Store("detailed LLM chunk is missing payload data".into())
|
||||
})?;
|
||||
sqlx::query("INSERT INTO llm_call_response_chunks(call_id, seq, received_offset_ms, data, byte_count) SELECT ?, ?, ?, ?, ? WHERE EXISTS (SELECT 1 FROM llm_calls WHERE call_id = ?)")
|
||||
.bind(call_id)
|
||||
.bind(chunk.seq)
|
||||
.bind(chunk.elapsed_ms)
|
||||
.bind(data)
|
||||
.bind(chunk.byte_count as i64)
|
||||
.bind(call_id)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
sqlx::query("UPDATE llm_calls SET first_event_at_ms = COALESCE(first_event_at_ms, ?), response_bytes = response_bytes + ?, stream_event_count = stream_event_count + ? WHERE call_id = ?")
|
||||
.bind(now_ms())
|
||||
.bind(data.len() as i64)
|
||||
.bind(byte_count)
|
||||
.bind(event_count)
|
||||
.bind(call_id)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
@@ -139,6 +205,7 @@ impl Store {
|
||||
}
|
||||
|
||||
pub async fn record_llm_first_text(&self, call_id: &str, elapsed_ms: i64) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("UPDATE llm_calls SET first_text_at_ms = COALESCE(first_text_at_ms, ?), ttft_ms = COALESCE(ttft_ms, ?) WHERE call_id = ?")
|
||||
.bind(now_ms())
|
||||
.bind(elapsed_ms)
|
||||
@@ -149,6 +216,8 @@ impl Store {
|
||||
}
|
||||
|
||||
pub async fn record_llm_usage(&self, call_id: &str, usage: Usage) -> Result<()> {
|
||||
let usage_json = serde_json::to_string(&usage)?;
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("UPDATE llm_calls SET input_tokens = ?, output_tokens = ?, total_tokens = ?, cache_read_tokens = ?, cache_write_tokens = ?, reasoning_tokens = ?, usage_json = ? WHERE call_id = ?")
|
||||
.bind(as_i64(usage.input_tokens))
|
||||
.bind(as_i64(usage.output_tokens))
|
||||
@@ -156,7 +225,7 @@ impl Store {
|
||||
.bind(as_i64(usage.cache_read_tokens))
|
||||
.bind(as_i64(usage.cache_write_tokens))
|
||||
.bind(as_i64(usage.reasoning_tokens))
|
||||
.bind(serde_json::to_string(&usage)?)
|
||||
.bind(usage_json)
|
||||
.bind(call_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
@@ -172,6 +241,7 @@ impl Store {
|
||||
error_kind: Option<&str>,
|
||||
error_message: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("UPDATE llm_calls SET status = ?, finish_reason = ?, finished_at_ms = ?, duration_ms = ?, error_kind = ?, error_message = ? WHERE call_id = ? AND status = 'running'")
|
||||
.bind(status)
|
||||
.bind(finish_reason)
|
||||
@@ -327,8 +397,129 @@ fn summary_from_row(row: sqlx::sqlite::SqliteRow) -> Result<LlmCallSummary> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::*;
|
||||
use crate::model::{ModelConfigInput, ModelType};
|
||||
use tokio::sync::Barrier;
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_writes_are_serialized_without_sqlite_busy_retries() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let store = Store::connect(&format!(
|
||||
"sqlite://{}",
|
||||
directory.path().join("concurrent-writes.db").display()
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO llm_calls(
|
||||
call_id, run_id, conversation_id, provider_call_index, provider_type,
|
||||
provider_url, request_type, request_url, model_id, display_name, status,
|
||||
created_at_ms, message_count, tool_count, detailed
|
||||
) VALUES (
|
||||
'concurrent-call', 'run', 'conversation', 0, 'openai-chat',
|
||||
'https://example.com', 'openai-chat', 'https://example.com',
|
||||
'model', 'Model', 'running', 1, 0, 0, 0
|
||||
)",
|
||||
)
|
||||
.execute(store.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut connections = Vec::new();
|
||||
for _ in 0..8 {
|
||||
connections.push(store.pool().acquire().await.unwrap());
|
||||
}
|
||||
for connection in &mut connections {
|
||||
sqlx::query("PRAGMA busy_timeout = 0")
|
||||
.execute(&mut **connection)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
drop(connections);
|
||||
|
||||
let writers = 32;
|
||||
let barrier = Arc::new(Barrier::new(writers));
|
||||
let mut tasks = Vec::with_capacity(writers);
|
||||
for seq in 0..writers {
|
||||
let store = store.clone();
|
||||
let barrier = barrier.clone();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
barrier.wait().await;
|
||||
store
|
||||
.record_llm_chunk("concurrent-call", seq as i64, 1, b"x", false)
|
||||
.await
|
||||
}));
|
||||
}
|
||||
for task in tasks {
|
||||
task.await.unwrap().unwrap();
|
||||
}
|
||||
|
||||
let call = store.llm_call("concurrent-call").await.unwrap().unwrap();
|
||||
assert_eq!(call.response_bytes, writers as i64);
|
||||
assert_eq!(call.stream_event_count, writers as i64);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn records_a_batch_of_response_chunks_with_one_summary_update() {
|
||||
let store = Store::connect("sqlite::memory:").await.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO llm_calls(
|
||||
call_id, run_id, conversation_id, provider_call_index, provider_type,
|
||||
provider_url, request_type, request_url, model_id, display_name, status,
|
||||
created_at_ms, message_count, tool_count, detailed
|
||||
) VALUES (
|
||||
'batch-call', 'run', 'conversation', 0, 'openai-chat',
|
||||
'https://example.com', 'openai-chat', 'https://example.com',
|
||||
'model', 'Model', 'running', 1, 0, 0, 1
|
||||
)",
|
||||
)
|
||||
.execute(store.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("CREATE TABLE llm_call_summary_updates(count INTEGER NOT NULL)")
|
||||
.execute(store.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO llm_call_summary_updates(count) VALUES (0)")
|
||||
.execute(store.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"CREATE TRIGGER count_llm_call_summary_updates
|
||||
AFTER UPDATE OF response_bytes ON llm_calls
|
||||
BEGIN
|
||||
UPDATE llm_call_summary_updates SET count = count + 1;
|
||||
END",
|
||||
)
|
||||
.execute(store.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
store
|
||||
.record_llm_chunks(
|
||||
"batch-call",
|
||||
&[
|
||||
BufferedLlmChunk::new(0, 1, b"one"),
|
||||
BufferedLlmChunk::new(1, 2, b"two"),
|
||||
BufferedLlmChunk::new(2, 3, b"three"),
|
||||
],
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let call = store.llm_call("batch-call").await.unwrap().unwrap();
|
||||
assert_eq!(call.response_bytes, 11);
|
||||
assert_eq!(call.stream_event_count, 3);
|
||||
assert_eq!(store.llm_call_chunks("batch-call").await.unwrap().len(), 3);
|
||||
let updates: i64 = sqlx::query_scalar("SELECT count FROM llm_call_summary_updates")
|
||||
.fetch_one(store.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(updates, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn latest_usage_anchor_uses_the_latest_completed_call_for_the_same_conversation_and_model(
|
||||
|
||||
@@ -13,8 +13,11 @@ mod settings;
|
||||
mod sqlite;
|
||||
mod storage;
|
||||
mod tool_rounds;
|
||||
mod writer;
|
||||
|
||||
pub use cas::*;
|
||||
pub(crate) use cursor_traces::BufferedCursorTraceChunk;
|
||||
pub(crate) use llm_calls::BufferedLlmChunk;
|
||||
pub use runs::*;
|
||||
pub use settings::*;
|
||||
pub(crate) use sqlite::now_ms;
|
||||
|
||||
@@ -60,6 +60,7 @@ impl Store {
|
||||
normalized.push((hash, input));
|
||||
}
|
||||
let now = now_ms();
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
for (hash, input) in &normalized {
|
||||
insert_model(&mut transaction, hash, input, now).await?;
|
||||
@@ -87,6 +88,7 @@ impl Store {
|
||||
}
|
||||
}
|
||||
let now = now_ms();
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
let mut inserted = 0;
|
||||
for (hash, input) in &normalized {
|
||||
@@ -110,6 +112,7 @@ impl Store {
|
||||
let input = normalize_model_input(input)?;
|
||||
let next_hash = model_hash(&input)?;
|
||||
let now = now_ms();
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
if next_hash != current.model_hash {
|
||||
sqlx::query("UPDATE llm_calls SET model_hash = NULL WHERE model_hash = ?")
|
||||
@@ -165,6 +168,7 @@ impl Store {
|
||||
}
|
||||
|
||||
pub async fn delete_model(&self, hash: &str) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
sqlx::query("UPDATE llm_calls SET model_hash = NULL WHERE model_hash = ?")
|
||||
.bind(hash)
|
||||
@@ -201,6 +205,7 @@ impl Store {
|
||||
}
|
||||
|
||||
let now = now_ms();
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
for (index, hash) in model_hashes.iter().enumerate() {
|
||||
sqlx::query(
|
||||
|
||||
@@ -13,6 +13,7 @@ impl Store {
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
) -> Result<RevisionId> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let revision = Self::ensure_conversation_tx(&mut tx, conversation_id).await?;
|
||||
tx.commit().await?;
|
||||
@@ -62,9 +63,10 @@ impl Store {
|
||||
conversation_id: &ConversationId,
|
||||
messages: &[CanonicalMessage],
|
||||
) -> Result<RevisionId> {
|
||||
let digest = message_digest(messages)?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let current = Self::ensure_conversation_tx(&mut tx, conversation_id).await?;
|
||||
let digest = message_digest(messages)?;
|
||||
if let Some(existing) = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT revision_id FROM conversation_revisions
|
||||
WHERE conversation_id = ? AND state_digest = ?",
|
||||
@@ -107,9 +109,20 @@ impl Store {
|
||||
if additions.is_empty() {
|
||||
return Ok(expected);
|
||||
}
|
||||
let mut full = self.load_revision_messages(expected).await?;
|
||||
full.extend_from_slice(additions);
|
||||
let digest = message_digest(&full)?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let revision =
|
||||
Self::append_revision_tx(&mut tx, conversation_id, run_id, expected, additions).await?;
|
||||
let revision = Self::append_revision_with_digest_tx(
|
||||
&mut tx,
|
||||
conversation_id,
|
||||
run_id,
|
||||
expected,
|
||||
additions,
|
||||
digest,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(revision)
|
||||
}
|
||||
@@ -121,6 +134,8 @@ impl Store {
|
||||
expected: RevisionId,
|
||||
messages: &[CanonicalMessage],
|
||||
) -> Result<RevisionId> {
|
||||
let digest = message_digest(messages)?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
Self::require_active_head_tx(&mut tx, conversation_id, run_id, expected).await?;
|
||||
let root: i64 = sqlx::query_scalar(
|
||||
@@ -130,7 +145,6 @@ impl Store {
|
||||
.bind(conversation_id.as_str())
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let digest = message_digest(messages)?;
|
||||
let revision =
|
||||
Self::insert_revision_tx(&mut tx, conversation_id, RevisionId(root), messages, digest)
|
||||
.await?;
|
||||
@@ -202,10 +216,29 @@ impl Store {
|
||||
expected: RevisionId,
|
||||
additions: &[CanonicalMessage],
|
||||
) -> Result<RevisionId> {
|
||||
Self::require_active_head_tx(tx, conversation_id, run_id, expected).await?;
|
||||
let mut full = Self::load_revision_messages_tx(tx, expected.0).await?;
|
||||
full.extend_from_slice(additions);
|
||||
let digest = message_digest(&full)?;
|
||||
Self::append_revision_with_digest_tx(
|
||||
tx,
|
||||
conversation_id,
|
||||
run_id,
|
||||
expected,
|
||||
additions,
|
||||
digest,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn append_revision_with_digest_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
conversation_id: &ConversationId,
|
||||
run_id: &RunId,
|
||||
expected: RevisionId,
|
||||
additions: &[CanonicalMessage],
|
||||
digest: [u8; 32],
|
||||
) -> Result<RevisionId> {
|
||||
Self::require_active_head_tx(tx, conversation_id, run_id, expected).await?;
|
||||
if sqlx::query_scalar::<_, i64>(
|
||||
"SELECT revision_id FROM conversation_revisions
|
||||
WHERE conversation_id = ? AND state_digest = ?",
|
||||
|
||||
@@ -36,6 +36,7 @@ pub struct ClaimedRun {
|
||||
|
||||
impl Store {
|
||||
pub async fn claim_run(&self, prepared: &PreparedRun) -> Result<ClaimedRun> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let now = now_ms();
|
||||
Self::ensure_conversation_tx(&mut tx, &prepared.conversation_id).await?;
|
||||
@@ -146,6 +147,7 @@ impl Store {
|
||||
}
|
||||
|
||||
pub async fn begin_provider_call(&self, run_id: &RunId) -> Result<u64> {
|
||||
let _write = self.writes.lock().await;
|
||||
let index: Option<i64> = sqlx::query_scalar(
|
||||
"UPDATE runs SET provider_call_index = provider_call_index + 1, updated_at_ms = ?
|
||||
WHERE run_id = ? AND status = 'running'
|
||||
@@ -167,6 +169,8 @@ impl Store {
|
||||
usage: Option<Usage>,
|
||||
failure: Option<(&str, &str)>,
|
||||
) -> Result<bool> {
|
||||
let usage_json = serde_json::to_string(&usage)?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let row = sqlx::query(
|
||||
"SELECT conversation_id, status, failure_category, failure_summary
|
||||
@@ -200,7 +204,7 @@ impl Store {
|
||||
WHERE run_id = ? AND status = 'running'",
|
||||
)
|
||||
.bind(status.as_str())
|
||||
.bind(serde_json::to_string(&usage)?)
|
||||
.bind(usage_json)
|
||||
.bind(category)
|
||||
.bind(summary)
|
||||
.bind(now)
|
||||
|
||||
@@ -93,6 +93,7 @@ pub(crate) struct ProxySettingsSecret {
|
||||
impl Store {
|
||||
pub(crate) async fn installation_id(&self) -> Result<String> {
|
||||
let generated = uuid::Uuid::new_v4().to_string();
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO NOTHING",
|
||||
)
|
||||
@@ -165,9 +166,11 @@ impl Store {
|
||||
username: input.username.trim().to_owned(),
|
||||
password,
|
||||
};
|
||||
let value_json = serde_json::to_string(&settings)?;
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms")
|
||||
.bind(PROXY_SETTINGS_KEY)
|
||||
.bind(serde_json::to_string(&settings)?)
|
||||
.bind(value_json)
|
||||
.bind(now_ms())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
@@ -206,9 +209,11 @@ impl Store {
|
||||
));
|
||||
}
|
||||
}
|
||||
let value_json = serde_json::to_string(&settings)?;
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms")
|
||||
.bind(TAB_SETTINGS_KEY)
|
||||
.bind(serde_json::to_string(&settings)?)
|
||||
.bind(value_json)
|
||||
.bind(now_ms())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
@@ -228,11 +233,13 @@ impl Store {
|
||||
}
|
||||
|
||||
pub async fn set_port_settings(&self, settings: PortSettings) -> Result<()> {
|
||||
let value_json = serde_json::to_string(&settings)?;
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms",
|
||||
)
|
||||
.bind(PORT_SETTINGS_KEY)
|
||||
.bind(serde_json::to_string(&settings)?)
|
||||
.bind(value_json)
|
||||
.bind(now_ms())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
@@ -264,11 +271,13 @@ impl Store {
|
||||
}
|
||||
|
||||
pub async fn set_desktop_settings(&self, settings: DesktopSettings) -> Result<()> {
|
||||
let value_json = serde_json::to_string(&settings)?;
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms",
|
||||
)
|
||||
.bind(DESKTOP_SETTINGS_KEY)
|
||||
.bind(serde_json::to_string(&settings)?)
|
||||
.bind(value_json)
|
||||
.bind(now_ms())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
@@ -7,9 +7,12 @@ use sqlx::{
|
||||
|
||||
use crate::Result;
|
||||
|
||||
use super::writer::WriteCoordinator;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Store {
|
||||
pub(crate) pool: SqlitePool,
|
||||
pub(crate) writes: WriteCoordinator,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
@@ -25,7 +28,10 @@ impl Store {
|
||||
.connect_with(options)
|
||||
.await?;
|
||||
sqlx::migrate!("./migrations").run(&pool).await?;
|
||||
Ok(Self { pool })
|
||||
Ok(Self {
|
||||
pool,
|
||||
writes: WriteCoordinator::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn pool(&self) -> &SqlitePool {
|
||||
|
||||
@@ -54,6 +54,7 @@ impl Store {
|
||||
}
|
||||
|
||||
pub async fn clear_statistics_storage(&self) -> Result<StatisticsStorage> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
sqlx::query("DELETE FROM llm_calls")
|
||||
.execute(&mut *transaction)
|
||||
|
||||
@@ -50,6 +50,8 @@ impl Store {
|
||||
if calls.is_empty() {
|
||||
return Err(Error::Store("cannot persist an empty tool round".into()));
|
||||
}
|
||||
let assistant_json = serde_json::to_string(assistant)?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let ownership: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(
|
||||
@@ -82,7 +84,7 @@ impl Store {
|
||||
.bind(round_id.as_str())
|
||||
.bind(run_id.as_str())
|
||||
.bind(base_revision_id.0)
|
||||
.bind(serde_json::to_string(assistant)?)
|
||||
.bind(assistant_json)
|
||||
.bind(created_at_ms)
|
||||
.bind(now)
|
||||
.execute(&mut *tx)
|
||||
@@ -113,6 +115,7 @@ impl Store {
|
||||
round_id: &ToolRoundId,
|
||||
result: &ToolResult,
|
||||
) -> Result<ToolCommit> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let round = sqlx::query(
|
||||
"SELECT assistant_json, status, version, next_completion_seq
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{Mutex, MutexGuard};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct WriteCoordinator {
|
||||
lock: Arc<Mutex<()>>,
|
||||
}
|
||||
|
||||
impl WriteCoordinator {
|
||||
pub(crate) async fn lock(&self) -> MutexGuard<'_, ()> {
|
||||
self.lock.lock().await
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user