From 605a3a01e83fa51e2f2be152ad22af7ece22f2a5 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 25 Nov 2026 22:10:25 +0800 Subject: [PATCH 1/4] Reuse completed attachments in trace delivery --- bt-daemon/Cargo.lock | 1 + bt-daemon/Cargo.toml | 1 + bt-daemon/src/pipeline/attachment_tests.rs | 85 +++++++++++++++++++ bt-daemon/src/sink/braintrust.rs | 94 ++++++++++++++++++++-- 4 files changed, 173 insertions(+), 8 deletions(-) diff --git a/bt-daemon/Cargo.lock b/bt-daemon/Cargo.lock index 47eba34c..e351fa5c 100644 --- a/bt-daemon/Cargo.lock +++ b/bt-daemon/Cargo.lock @@ -349,6 +349,7 @@ dependencies = [ "parking_lot", "regex", "reqwest 0.12.28", + "reqwest 0.13.5", "rquickjs", "rquickjs-serde", "rusqlite", diff --git a/bt-daemon/Cargo.toml b/bt-daemon/Cargo.toml index 765114e9..2e48df25 100644 --- a/bt-daemon/Cargo.toml +++ b/bt-daemon/Cargo.toml @@ -38,6 +38,7 @@ clap = { version = "4", features = ["derive", "env"] } fs2 = "0.4" futures = { version = "0.3", default-features = false, features = ["std"] } regex = "1" +reqwest13 = { package = "reqwest", version = "0.13", default-features = false, features = ["json", "query", "rustls"] } rquickjs = "0.12.2" rquickjs-serde = "0.6.1" serde = { version = "1", features = ["derive", "rc"] } diff --git a/bt-daemon/src/pipeline/attachment_tests.rs b/bt-daemon/src/pipeline/attachment_tests.rs index 05af5e4b..ac94ec01 100644 --- a/bt-daemon/src/pipeline/attachment_tests.rs +++ b/bt-daemon/src/pipeline/attachment_tests.rs @@ -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,32 @@ 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")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "status":{"upload_status":status},"contentLength":11 + }))) + .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 +125,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 +352,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..4930ad89 100644 --- a/bt-daemon/src/sink/braintrust.rs +++ b/bt-daemon/src/sink/braintrust.rs @@ -11,10 +11,13 @@ use super::{Sink, SinkFactory}; use crate::translate::{SpanOp, SpanRow, SpanType}; use crate::wire::{SessionConfig, TraceDestination}; +use braintrust_api_client::backend::{extensions::AttachmentRequest, HttpError}; use braintrust_sdk_rust::{ BraintrustClient, ParentSpanInfo, SpanComponents, SpanHandle, SpanLog, SpanObjectType, SpanType as SdkSpanType, DEFAULT_API_URL, DEFAULT_APP_URL, }; +use reqwest13 as reqwest; +use serde::Deserialize; use serde_json::{json, Map, Value}; use std::collections::{HashMap, VecDeque}; use std::io::Write; @@ -186,10 +189,86 @@ 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, completed: crate::translate::recent::RecentSet, + lookup: Option, +} + +#[derive(Deserialize)] +struct AttachmentMetadata { + status: AttachmentUploadStatus, + #[serde(rename = "contentLength")] + content_length: Option, +} + +#[derive(Deserialize)] +#[serde(tag = "upload_status", rename_all = "snake_case")] +enum AttachmentUploadStatus { + Done, + #[serde(other)] + Incomplete, +} + +#[derive(Deserialize)] +struct AttachmentConflict { + #[serde(rename = "Message")] + message: String, +} + +impl AttachmentUploads { + async fn upload( + &mut self, + request: &AttachmentRequest, + data: &[u8], + api: &str, + token: &str, + ) -> 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 == reqwest::StatusCode::CONFLICT + && 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. + if self.lookup.is_none() { + let mut builder = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(30)) + .redirect(reqwest::redirect::Policy::none()); + if let Some(pem) = crate::env::var("BRAINTRUST_CUSTOM_CA_BUNDLE") { + for certificate in reqwest::Certificate::from_pem_bundle(pem.as_bytes())? { + builder = builder.add_root_certificate(certificate); + } + } + self.lookup = Some(builder.build()?); + } + let Some(client) = &self.lookup else { + return Err(error); + }; + let metadata: AttachmentMetadata = client + .get(format!("{}/attachment", api.trim_end_matches('/'))) + .bearer_auth(token) + .query(request) + .send() + .await? + .error_for_status()? + .json() + .await?; + if !matches!(metadata.status, AttachmentUploadStatus::Done) + || metadata.content_length != Some(data.len()) + { + return Err(error); + } + } + self.completed.insert(request.key.clone()); + Ok(()) + } } struct BraintrustSink { @@ -386,13 +465,13 @@ impl BraintrustSink { concat!("bt-daemon/", env!("CARGO_PKG_VERSION")), )?, completed: Default::default(), + lookup: None, }); } let uploads = self .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 +483,18 @@ 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, + api, + &creds.token, ) .await?; - // A failed PUT or status acknowledgment must remain retryable. - uploads.completed.insert(key); } references.insert(attachment.digest.clone(), reference); } From 5b5b2aae2b8bc460a06d435eba40cbdfe77eb3a5 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 25 Nov 2026 23:26:20 +0800 Subject: [PATCH 2/4] Serialize legacy journal migration during capture and recovery --- bt-daemon/src/collections/legacy.rs | 34 +++++++++++++++++++++-------- bt-daemon/src/collections/tests.rs | 27 +++++++++++++++++++++++ 2 files changed, 52 insertions(+), 9 deletions(-) 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()); + } +} From edb6c2cd57332b495d03f918967b14e9d72e1590 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 25 Nov 2026 23:26:20 +0800 Subject: [PATCH 3/4] Keep Pi tracing compatible with Oh My Pi 19.2 --- bt-daemon/tests/agent_integration.rs | 7 +++++++ .../pi/content/src/daemon-adapter.test.ts | 18 ++++++------------ src/plugins/pi/content/src/index.ts | 18 ++++++------------ src/plugins/pi/content/src/pi-tui.ts | 18 ++++++++++++++++++ 4 files changed, 37 insertions(+), 24 deletions(-) create mode 100644 src/plugins/pi/content/src/pi-tui.ts diff --git a/bt-daemon/tests/agent_integration.rs b/bt-daemon/tests/agent_integration.rs index df5a5787..b26d3309 100644 --- a/bt-daemon/tests/agent_integration.rs +++ b/bt-daemon/tests/agent_integration.rs @@ -368,6 +368,13 @@ async fn pi_session_emits_traces() { if request.has_function_output("call_pi_1") { return MockReply::response(OpenAiTurn::text("PI_MOCK_OK")); } + // Oh My Pi sends auxiliary requests without tools to the same + // provider before the actual prompt. Only drive the shell turn when + // tools are offered. The assertions below still require the tool + // call, its result, and their delivered trace. + if request.tool_names().is_empty() { + return MockReply::response(OpenAiTurn::text("Integration test")); + } MockReply::response(shell_tool_call( &request, "call_pi_1", diff --git a/src/plugins/pi/content/src/daemon-adapter.test.ts b/src/plugins/pi/content/src/daemon-adapter.test.ts index fc081359..6a189f93 100644 --- a/src/plugins/pi/content/src/daemon-adapter.test.ts +++ b/src/plugins/pi/content/src/daemon-adapter.test.ts @@ -17,18 +17,12 @@ const mockState = vi.hoisted(() => ({ permalink: "https://www.braintrust.dev/trace/1" as string | undefined, })); -vi.mock("@earendil-works/pi-tui", async (importOriginal) => { - const original = await importOriginal(); - return { - ...original, - get getCapabilities() { - return mockState.ompTui ? undefined : () => ({ hyperlinks: mockState.hyperlinks }); - }, - get hyperlink() { - return mockState.ompTui ? undefined : original.hyperlink; - }, - }; -}); +vi.mock("./pi-tui.ts", () => ({ + loadPiHyperlinkHelpers: async () => + mockState.ompTui + ? {} + : { getCapabilities: () => ({ hyperlinks: mockState.hyperlinks }), hyperlink }, +})); vi.mock("./runtime/daemon-client.ts", () => ({ claimManagedTracingInstance: () => mockState.claim, diff --git a/src/plugins/pi/content/src/index.ts b/src/plugins/pi/content/src/index.ts index 96525040..21d82e68 100644 --- a/src/plugins/pi/content/src/index.ts +++ b/src/plugins/pi/content/src/index.ts @@ -1,10 +1,10 @@ import { createHash, randomUUID } from "node:crypto"; import { resolve } from "node:path"; import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; -import * as piTui from "@earendil-works/pi-tui"; import { loadConfig } from "./config.ts"; import { legacyContinuationFor, type LegacyContinuation } from "./legacy-session.ts"; import { runningPiPackage } from "./pi-package.ts"; +import { loadPiHyperlinkHelpers } from "./pi-tui.ts"; import { claimManagedTracingInstance, DaemonClient } from "./runtime/daemon-client.ts"; import { EXTENSION_VERSION } from "./version.ts"; @@ -18,13 +18,8 @@ const TRACE_LINK_POLL_TIMEOUT_MS = 40_000; const PI_VERSION = runningPiPackage().version; const PI_HOST_NAME = runningPiPackage().name; -/** - * Oh My Pi resolves this package to its own pi-tui, which exports neither - * helper. A named import would fail to link and OMP would silently drop the - * extension, so read them from the namespace and fall back to plain text. - */ -function terminalHyperlink(text: string, url: string): string | undefined { - const { getCapabilities, hyperlink } = piTui as Partial; +async function terminalHyperlink(text: string, url: string): Promise { + const { getCapabilities, hyperlink } = await loadPiHyperlinkHelpers(PI_HOST_NAME); if (typeof getCapabilities !== "function" || typeof hyperlink !== "function") return undefined; return getCapabilities().hyperlinks ? hyperlink(text, url) : undefined; } @@ -149,10 +144,9 @@ export default function braintrustPiExtension(pi: ExtensionAPI): void { if (daemonSession?.last_error) { ctx.ui.setStatus(STATUS_KEY, `Braintrust: ${daemonSession.last_error}`); } else { - ctx.ui.setStatus( - STATUS_KEY, - (permalink && terminalHyperlink(traceLabel, permalink)) || "Braintrust: connected", - ); + const label = permalink ? await terminalHyperlink(traceLabel, permalink) : undefined; + if (uiGeneration !== refreshGeneration || sessionId !== refreshSessionId) return; + ctx.ui.setStatus(STATUS_KEY, label ?? "Braintrust: connected"); } traceLinkShown = Boolean(permalink); }; diff --git a/src/plugins/pi/content/src/pi-tui.ts b/src/plugins/pi/content/src/pi-tui.ts new file mode 100644 index 00000000..6f9ecb53 --- /dev/null +++ b/src/plugins/pi/content/src/pi-tui.ts @@ -0,0 +1,18 @@ +type PiTui = typeof import("@earendil-works/pi-tui"); +type HyperlinkHelpers = Pick; + +/** Pi's UI helpers are optional for a tracing extension and unavailable in Oh My Pi. */ +export async function loadPiHyperlinkHelpers( + host: string | undefined, +): Promise> { + if (host === "@oh-my-pi/pi-coding-agent") return {}; + try { + // Resolve only in the Pi UI path. Oh My Pi rejects package imports of + // the old TUI at extension load time, including literal dynamic imports. + const url = import.meta.resolve("@earendil-works/pi-tui"); + return (await import(url)) as PiTui; + } catch { + // Some hosts supply the extension API without Pi's optional UI helpers. + return {}; + } +} From 2274e885b534293cede3ff67fb94d0569a0f5947 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 26 Nov 2026 00:58:35 +0800 Subject: [PATCH 4/4] Use the Rust API client to verify existing attachments --- bt-daemon/Cargo.lock | 3 +- bt-daemon/Cargo.toml | 3 +- bt-daemon/src/pipeline/attachment_tests.rs | 10 +++- bt-daemon/src/sink/braintrust.rs | 65 ++++------------------ 4 files changed, 20 insertions(+), 61 deletions(-) diff --git a/bt-daemon/Cargo.lock b/bt-daemon/Cargo.lock index e351fa5c..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", @@ -349,7 +349,6 @@ dependencies = [ "parking_lot", "regex", "reqwest 0.12.28", - "reqwest 0.13.5", "rquickjs", "rquickjs-serde", "rusqlite", diff --git a/bt-daemon/Cargo.toml b/bt-daemon/Cargo.toml index 2e48df25..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" @@ -38,7 +38,6 @@ clap = { version = "4", features = ["derive", "env"] } fs2 = "0.4" futures = { version = "0.3", default-features = false, features = ["std"] } regex = "1" -reqwest13 = { package = "reqwest", version = "0.13", default-features = false, features = ["json", "query", "rustls"] } rquickjs = "0.12.2" rquickjs-serde = "0.6.1" serde = { version = "1", features = ["derive", "rc"] } diff --git a/bt-daemon/src/pipeline/attachment_tests.rs b/bt-daemon/src/pipeline/attachment_tests.rs index ac94ec01..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 { @@ -66,8 +66,14 @@ async fn upload_sessions( .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 + "status":{"upload_status":status}, + "contentLength":11, + "downloadUrl":format!("{storage_url}/download"), + "embedUrl":format!("{storage_url}/embed") }))) .expect(1) .mount(&server) diff --git a/bt-daemon/src/sink/braintrust.rs b/bt-daemon/src/sink/braintrust.rs index 4930ad89..f3110b0a 100644 --- a/bt-daemon/src/sink/braintrust.rs +++ b/bt-daemon/src/sink/braintrust.rs @@ -11,12 +11,14 @@ use super::{Sink, SinkFactory}; use crate::translate::{SpanOp, SpanRow, SpanType}; use crate::wire::{SessionConfig, TraceDestination}; -use braintrust_api_client::backend::{extensions::AttachmentRequest, HttpError}; +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 reqwest13 as reqwest; use serde::Deserialize; use serde_json::{json, Map, Value}; use std::collections::{HashMap, VecDeque}; @@ -191,24 +193,8 @@ impl Creds { /// Only completed keys are retained, never attachment bytes. This bounded /// 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, - lookup: Option, -} - -#[derive(Deserialize)] -struct AttachmentMetadata { - status: AttachmentUploadStatus, - #[serde(rename = "contentLength")] - content_length: Option, -} - -#[derive(Deserialize)] -#[serde(tag = "upload_status", rename_all = "snake_case")] -enum AttachmentUploadStatus { - Done, - #[serde(other)] - Incomplete, } #[derive(Deserialize)] @@ -218,16 +204,10 @@ struct AttachmentConflict { } impl AttachmentUploads { - async fn upload( - &mut self, - request: &AttachmentRequest, - data: &[u8], - api: &str, - token: &str, - ) -> anyhow::Result<()> { + 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 == reqwest::StatusCode::CONFLICT + http.status.as_u16() == 409 && serde_json::from_str::(&http.body) .is_ok_and(|body| body.message.starts_with("Attachment key already exists")) }); @@ -237,31 +217,9 @@ impl AttachmentUploads { // A key is reserved before the object is uploaded. Require both // a completed status and an object of the expected size. - if self.lookup.is_none() { - let mut builder = reqwest::Client::builder() - .timeout(std::time::Duration::from_secs(30)) - .redirect(reqwest::redirect::Policy::none()); - if let Some(pem) = crate::env::var("BRAINTRUST_CUSTOM_CA_BUNDLE") { - for certificate in reqwest::Certificate::from_pem_bundle(pem.as_bytes())? { - builder = builder.add_root_certificate(certificate); - } - } - self.lookup = Some(builder.build()?); - } - let Some(client) = &self.lookup else { - return Err(error); - }; - let metadata: AttachmentMetadata = client - .get(format!("{}/attachment", api.trim_end_matches('/'))) - .bearer_auth(token) - .query(request) - .send() - .await? - .error_for_status()? - .json() - .await?; + let metadata = self.backend.get_attachment(request).await?; if !matches!(metadata.status, AttachmentUploadStatus::Done) - || metadata.content_length != Some(data.len()) + || metadata.content_length != Some(data.len() as u64) { return Err(error); } @@ -456,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, @@ -465,7 +423,6 @@ impl BraintrustSink { concat!("bt-daemon/", env!("CARGO_PKG_VERSION")), )?, completed: Default::default(), - lookup: None, }); } let uploads = self @@ -491,8 +448,6 @@ impl BraintrustSink { creds.org_id.clone(), ), &attachment.data, - api, - &creds.token, ) .await?; }