diff --git a/bt-daemon/Cargo.lock b/bt-daemon/Cargo.lock index 47eba34c..d26c5892 100644 --- a/bt-daemon/Cargo.lock +++ b/bt-daemon/Cargo.lock @@ -274,7 +274,7 @@ dependencies = [ [[package]] name = "braintrust-api-client" version = "0.1.0-alpha.2" -source = "git+https://github.com/braintrustdata/braintrust-sdk-rust?rev=cb231d5785987a3143361cc846227f3ac758ba74#cb231d5785987a3143361cc846227f3ac758ba74" +source = "git+https://github.com/braintrustdata/braintrust-sdk-rust?rev=1c03a8b0739d4de0a985ca350b24e4e52a3a2f8a#1c03a8b0739d4de0a985ca350b24e4e52a3a2f8a" dependencies = [ "anyhow", "backoff", diff --git a/bt-daemon/Cargo.toml b/bt-daemon/Cargo.toml index 765114e9..a4feb34e 100644 --- a/bt-daemon/Cargo.toml +++ b/bt-daemon/Cargo.toml @@ -26,7 +26,7 @@ expect_used = "deny" [dependencies] # Keep this pinned exactly, matching the dependency policy used by `bt`. braintrust-sdk-rust = { git = "https://github.com/braintrustdata/braintrust-sdk-rust", rev = "27f6721e56611d776e12e4cfc81dd1ad5ecd7af4" } -braintrust-api-client = { git = "https://github.com/braintrustdata/braintrust-sdk-rust", rev = "cb231d5785987a3143361cc846227f3ac758ba74" } +braintrust-api-client = { git = "https://github.com/braintrustdata/braintrust-sdk-rust", rev = "1c03a8b0739d4de0a985ca350b24e4e52a3a2f8a" } base64 = "0.22" mime_guess = "2" anyhow = "1" diff --git a/bt-daemon/src/collections/legacy.rs b/bt-daemon/src/collections/legacy.rs index 60853be3..43564bfd 100644 --- a/bt-daemon/src/collections/legacy.rs +++ b/bt-daemon/src/collections/legacy.rs @@ -22,6 +22,10 @@ const IMPORT_RECORDS: usize = 1024; const IMPORT_BYTES: usize = 8 * 1024 * 1024; const PI_MESSAGES_DELTA: &str = "_bt_messages_delta"; +// Recovery and live capture can both discover a legacy journal. Serialize +// reading, committing and removing those files. Modern sessions bypass this. +static IMPORT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + /// Import any legacy journals that hold records for this source session. pub(super) async fn import_session( data_dir: &Path, @@ -30,14 +34,19 @@ pub(super) async fn import_session( events: &SessionStorage, ) -> anyhow::Result<()> { let unqualified = journal_path(data_dir, session_id); - if unqualified + let unqualified_supported = unqualified .file_name() - .is_some_and(|name| name.len() <= crate::journal::MAX_FILE_NAME_BYTES) - && tokio::fs::try_exists(&unqualified).await? + .is_some_and(|name| name.len() <= crate::journal::MAX_FILE_NAME_BYTES); + let qualified = source_journal_path(data_dir, source, session_id); + if !(unqualified_supported && tokio::fs::try_exists(&unqualified).await?) + && !tokio::fs::try_exists(&qualified).await? { + return Ok(()); + } + let _guard = IMPORT_LOCK.lock().await; + if unqualified_supported && tokio::fs::try_exists(&unqualified).await? { import_unqualified(data_dir, &unqualified).await?; } - let qualified = source_journal_path(data_dir, source, session_id); if tokio::fs::try_exists(&qualified).await? { import_file(&qualified, source, events, None).await?; tokio::fs::remove_file(&qualified).await?; @@ -57,11 +66,18 @@ pub(crate) async fn import_all(data_dir: &Path) { continue; } let result = async { - let owners = sessions(&path).await?; - if owners.is_empty() { - // Nothing was ever acknowledged from a file without events. - tokio::fs::remove_file(&path).await?; - } + let owners = { + let _guard = IMPORT_LOCK.lock().await; + if !tokio::fs::try_exists(&path).await? { + return Ok(()); + } + let owners = sessions(&path).await?; + if owners.is_empty() { + // Nothing was ever acknowledged from a file without events. + tokio::fs::remove_file(&path).await?; + } + owners + }; for (source, session_id) in owners { SessionStorage::open(data_dir, &source, &session_id).await?; } diff --git a/bt-daemon/src/collections/tests.rs b/bt-daemon/src/collections/tests.rs index e3de1129..1974cc99 100644 --- a/bt-daemon/src/collections/tests.rs +++ b/bt-daemon/src/collections/tests.rs @@ -434,3 +434,30 @@ async fn compaction_returns_deleted_space_to_the_file_system() { assert_eq!(pragma("freelist_count"), 0); assert!(size() < bloated / 4, "{} of {bloated} bytes remain", size()); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn simultaneous_legacy_open_preserves_capture() { + for qualified in [true, false] { + let temp = tempfile::tempdir().unwrap(); + let path = if qualified { + source_journal_path(temp.path(), "debug", "session") + } else { + journal_path(temp.path(), "session") + }; + let record = line( + &json!({"source":"debug","session_id":"session","event":"e","ts_ms":1,"payload":{}}), + ); + write_legacy(&path, &record).await; + let outcomes = futures::future::join_all( + (0..16).map(|_| SessionStorage::open(temp.path(), "debug", "session")), + ) + .await; + for storage in outcomes { + assert_eq!( + storage.unwrap().status().await.unwrap().event_tail, + record.len() as u64 + ); + } + assert!(!path.exists()); + } +} diff --git a/bt-daemon/src/pipeline/attachment_tests.rs b/bt-daemon/src/pipeline/attachment_tests.rs index 05af5e4b..180c552a 100644 --- a/bt-daemon/src/pipeline/attachment_tests.rs +++ b/bt-daemon/src/pipeline/attachment_tests.rs @@ -11,7 +11,7 @@ use crate::{ wire::{Envelope, SessionConfig}, }; use serde_json::{json, Value}; -use wiremock::matchers::{method, path, path_regex}; +use wiremock::matchers::{header, method, path, path_regex, query_param}; use wiremock::{Mock, MockServer, ResponseTemplate}; fn event(source: &str, name: &str, ts: i64, payload: Value) -> Envelope { @@ -28,6 +28,15 @@ fn reference(value: &Value, mime: &str) -> bool { } } async fn upload(source: &str, events: Vec) -> Vec { + upload_sessions(source, events, None).await +} + +async fn upload_sessions( + source: &str, + events: Vec, + existing_status: Option<&str>, +) -> Vec { + let repeat = existing_status.is_some(); let server = MockServer::start().await; let storage = MockServer::start().await; Mock::given(method("GET")) @@ -46,12 +55,38 @@ async fn upload(source: &str, events: Vec) -> Vec { .mount(&server) .await; let storage_url = storage.uri(); + if let Some(status) = existing_status { + Mock::given(method("POST")) + .and(path("/attachment")) + .respond_with(ResponseTemplate::new(409).set_body_json(json!({ + "Code":"HTTPError","Message":"Attachment key already exists" + }))) + .with_priority(2) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/attachment")) + .and(header("authorization", "Bearer test-key")) + .and(query_param("content_type", "image/png")) + .and(query_param("org_id", "org")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "status":{"upload_status":status}, + "contentLength":11, + "downloadUrl":format!("{storage_url}/download"), + "embedUrl":format!("{storage_url}/embed") + }))) + .expect(1) + .mount(&server) + .await; + } Mock::given(method("POST")) .and(path("/attachment")) .respond_with(move |request: &wiremock::Request| { let metadata: Value = serde_json::from_slice(&request.body).unwrap(); ResponseTemplate::new(200).set_body_json(json!({"signedUrl":format!("{storage_url}/bytes/{}",metadata["key"].as_str().unwrap()),"headers":{}})) }) + .with_priority(1) + .up_to_n_times(if repeat { 1 } else { u64::MAX }) .mount(&server).await; Mock::given(method("POST")) .and(path("/attachment/status")) @@ -96,6 +131,27 @@ async fn upload(source: &str, events: Vec) -> Vec { sink.emit(&[op]).await.unwrap(); } sink.flush().await.unwrap(); + if repeat { + let mut other = BraintrustSinkFactory::new(BraintrustSinkConfig::default()) + .create("another-session", source) + .unwrap(); + other.configure(&config); + for mut op in session.stored().await { + let row = op.row_mut(); + row.span_id = format!("second-{}", row.span_id); + row.root_span_id = format!("second-{}", row.root_span_id); + for parent in &mut row.parent_span_ids { + *parent = format!("second-{parent}"); + } + if let Err(error) = other.emit(&[op]).await { + assert_eq!(existing_status, Some("uploading"), "{error:#}"); + assert!(error.to_string().contains("409 Conflict"), "{error:#}"); + return Vec::new(); + } + } + other.flush().await.unwrap(); + assert_eq!(existing_status, Some("done")); + } let uploaded = storage.received_requests().await.unwrap(); assert!(!uploaded.is_empty(), "{source} uploaded no attachments"); let requests = server.received_requests().await.unwrap(); @@ -302,3 +358,38 @@ async fn claude_uploads_prompt_documents_and_tool_images() { "missing tool image: {rows:?}" ); } + +fn image_session() -> Vec { + vec![ + event( + "pi", + "before_agent_start", + 1, + json!({ + "prompt":"describe","images":[{"type":"image","mimeType":"image/png","data":"aW1hZ2UgYnl0ZXM="}] + }), + ), + event("pi", "agent_end", 2, json!({})), + ] +} + +#[tokio::test] +async fn repeated_image_does_not_block_a_fresh_sink() { + let rows = upload_sessions("pi", image_session(), Some("done")).await; + let mut second = rows.iter().filter(|row| { + row["span_id"] + .as_str() + .is_some_and(|id| id.starts_with("second-")) + }); + assert!(second + .clone() + .any(|row| reference(&row["input"], "image/png"))); + assert!(second.any(|row| row["metrics"]["end"].is_number())); +} + +#[tokio::test] +async fn reserved_key_without_completed_upload_is_not_reused() { + assert!(upload_sessions("pi", image_session(), Some("uploading")) + .await + .is_empty()); +} diff --git a/bt-daemon/src/sink/braintrust.rs b/bt-daemon/src/sink/braintrust.rs index fb739f61..f3110b0a 100644 --- a/bt-daemon/src/sink/braintrust.rs +++ b/bt-daemon/src/sink/braintrust.rs @@ -11,10 +11,15 @@ use super::{Sink, SinkFactory}; use crate::translate::{SpanOp, SpanRow, SpanType}; use crate::wire::{SessionConfig, TraceDestination}; +use braintrust_api_client::backend::{ + extensions::{AttachmentRequest, AttachmentUploadStatus}, + BackendClient, HttpError, +}; use braintrust_sdk_rust::{ BraintrustClient, ParentSpanInfo, SpanComponents, SpanHandle, SpanLog, SpanObjectType, SpanType as SdkSpanType, DEFAULT_API_URL, DEFAULT_APP_URL, }; +use serde::Deserialize; use serde_json::{json, Map, Value}; use std::collections::{HashMap, VecDeque}; use std::io::Write; @@ -186,12 +191,44 @@ impl Creds { } /// Only completed keys are retained, never attachment bytes. This bounded -/// optimization may miss after eviction/restart; re-uploading remains safe. +/// optimization may miss after eviction or restart; check conflicts with the API. struct AttachmentUploads { - backend: braintrust_api_client::backend::BackendClient, + backend: BackendClient, completed: crate::translate::recent::RecentSet, } +#[derive(Deserialize)] +struct AttachmentConflict { + #[serde(rename = "Message")] + message: String, +} + +impl AttachmentUploads { + async fn upload(&mut self, request: &AttachmentRequest, data: &[u8]) -> anyhow::Result<()> { + if let Err(error) = self.backend.upload_attachment(request, data.to_vec()).await { + let duplicate = error.downcast_ref::().is_some_and(|http| { + http.status.as_u16() == 409 + && serde_json::from_str::(&http.body) + .is_ok_and(|body| body.message.starts_with("Attachment key already exists")) + }); + if !duplicate { + return Err(error); + } + + // A key is reserved before the object is uploaded. Require both + // a completed status and an object of the expected size. + let metadata = self.backend.get_attachment(request).await?; + if !matches!(metadata.status, AttachmentUploadStatus::Done) + || metadata.content_length != Some(data.len() as u64) + { + return Err(error); + } + } + self.completed.insert(request.key.clone()); + Ok(()) + } +} + struct BraintrustSink { cache: Arc, default_api_url: Option, @@ -377,7 +414,7 @@ impl BraintrustSink { .ok_or_else(|| anyhow::anyhow!("missing attachment backend"))?; if self.attachment_uploads.is_none() { self.attachment_uploads = Some(AttachmentUploads { - backend: braintrust_api_client::backend::BackendClient::new( + backend: BackendClient::new( api, app, &creds.token, @@ -392,7 +429,6 @@ impl BraintrustSink { .attachment_uploads .as_mut() .ok_or_else(|| anyhow::anyhow!("missing attachment upload client"))?; - use braintrust_api_client::backend::extensions::AttachmentRequest; let mut references = HashMap::new(); for attachment in &row.attachments { let key = uuid::Uuid::new_v5( @@ -404,19 +440,16 @@ impl BraintrustSink { crate::attachments::AttachmentReference::uploaded(key.clone(), attachment); if !uploads.completed.contains(&key) { uploads - .backend - .upload_attachment( + .upload( &AttachmentRequest::new( - key.clone(), + key, attachment.filename.clone(), attachment.content_type.clone(), creds.org_id.clone(), ), - attachment.data.clone(), + &attachment.data, ) .await?; - // A failed PUT or status acknowledgment must remain retryable. - uploads.completed.insert(key); } references.insert(attachment.digest.clone(), reference); }