Skip to content

Commit f892440

Browse files
authored
Fix wasm integ tests, fix playground not streaming (#2504)
1 parent 6bf3299 commit f892440

8 files changed

Lines changed: 147 additions & 83 deletions

File tree

‎engine/Cargo.lock‎

Lines changed: 21 additions & 17 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎engine/baml-runtime/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ uuid = { workspace = true, features = ["v4", "serde", "js"] }
157157
wasm-bindgen = "^0.2.74"
158158
wasm-bindgen-futures = "0.4"
159159
web-sys.workspace = true
160-
wasmtimer = "0.4.1"
160+
wasmtimer = "0.4.3"
161161
tokio = { version = "1", features = ["rt", "sync"] }
162162

163163

‎engine/baml-runtime/src/internal/llm_client/orchestrator/stream.rs‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ use internal_baml_core::ir::repr::IntermediateRepr;
99
use jsonish::BamlValueWithFlags;
1010
use serde_json::json;
1111
use stream_cancel::Tripwire;
12-
use tokio::time::MissedTickBehavior;
12+
#[cfg(not(target_family = "wasm"))]
13+
use tokio::time::*;
14+
#[cfg(target_family = "wasm")]
15+
use wasmtimer::tokio::*;
1316
use web_time::Duration;
1417

1518
use super::{call::CtxWithHttpRequestId, OrchestrationScope, OrchestratorNodeIterator};
@@ -51,7 +54,7 @@ where
5154
G: Fn(),
5255
{
5356
let mut results = Vec::new();
54-
let mut total_sleep_duration = std::time::Duration::from_secs(0);
57+
let mut total_sleep_duration = web_time::Duration::from_secs(0);
5558

5659
// Create a future that either waits for cancellation or never completes
5760
let cancel_future = match cancel_tripwire {
@@ -104,7 +107,7 @@ where
104107
let mut latest_content_for_parse: Option<String> = None;
105108
// Track last parsed payload surfaced to downstream listeners so we can dedupe events
106109
let mut last_sent_partial_serialized: Option<String> = None;
107-
let mut parse_interval = tokio::time::interval(std::time::Duration::from_millis(20));
110+
let mut parse_interval = interval(web_time::Duration::from_millis(20));
108111
// If parsing falls behind, skip missed ticks so we only parse latest.
109112
parse_interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
110113

‎engine/baml-schema-wasm/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ dissimilar = "1.0.4"
6363
expect-test = "1.1.0"
6464
indoc.workspace = true
6565
either = "1.8.1"
66-
wasm-bindgen-test = "0.3.42"
66+
wasm-bindgen-test = "0.3.43"
6767
walkdir = "2.5.0"
6868
wasm-logger = "0.2.0"
6969
wasmtimer = "0.4.1"

‎engine/baml-schema-wasm/tests/test_file_manager.rs‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@
22
// wasm-pack test --node
33
// and make sure to set rust-analyzer target in vscode settings to: "rust-analyzer.cargo.target": "wasm32-unknown-unknown",
44
#[cfg(target_arch = "wasm32")]
5-
#[cfg(test)]
6-
mod tests {
5+
pub mod tests {
76
use std::collections::HashMap;
87

98
use baml_schema_build::runtime_wasm::WasmProject;
@@ -102,7 +101,7 @@ mod tests {
102101
// Update BAML file
103102
let updated_content = "// A COMMENT".to_string();
104103
project.update_file("main.baml", Some(updated_content.clone()));
105-
let project_files = project.files();
104+
let _project_files = project.files();
106105
assert!(project
107106
.files()
108107
.contains(&"main.bamlBAML_PATH_SPLTTER// A COMMENT".to_string()));

‎engine/baml-schema-wasm/tests/test_log_collector.rs‎

Lines changed: 113 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -2,74 +2,27 @@
22
// RUST_LOG=info wasm-pack test --node --test test_log_collector
33
// and make sure to set rust-analyzer target in vscode settings to: "rust-analyzer.cargo.target": "wasm32-unknown-unknown",
44

5+
// Install wasm bindgen cli: cargo install wasm-bindgen-cli --version 0.2.101
56
// Browser test command is:
67
// RUST_BACKTRACE=1 RUST_LOG=info wasm-pack test --chrome --headless --test test_log_collector -- --nocapture
78
#[cfg(target_arch = "wasm32")]
89
#[cfg(test)]
9-
mod tests {
10+
pub(crate) mod tests {
1011

11-
use std::collections::HashMap;
12+
use std::{cell::RefCell, collections::HashMap, rc::Rc};
1213

1314
use baml_runtime::tracingv2::publisher::publisher::flush;
1415
// pub static GLOBAL_TRACE_STORAGE: Lazy<Mutex<u32>> = Lazy::new(|| Mutex::new(0));
15-
use baml_runtime::{tracingv2::storage::storage::BAML_TRACER, InternalRuntimeInterface};
16+
use baml_runtime::tracingv2::storage::storage::BAML_TRACER;
1617
use baml_schema_build::runtime_wasm::WasmProject;
1718
use serde_wasm_bindgen::to_value;
18-
use wasm_bindgen::JsValue;
19+
use wasm_bindgen::{closure::Closure, JsCast, JsValue};
1920
use wasm_bindgen_test::*;
2021

2122
// instantiate logger
2223

2324
wasm_bindgen_test_configure!(run_in_browser);
2425

25-
fn sample_baml_content() -> String {
26-
r##"
27-
28-
29-
class Email {
30-
subject string
31-
body string
32-
from_address string
33-
}
34-
35-
enum OrderStatus {
36-
ORDERED
37-
SHIPPED
38-
DELIVERED
39-
CANCELLED
40-
}
41-
42-
class OrderInfo {
43-
order_status OrderStatus
44-
tracking_number string?
45-
estimated_arrival_date string?
46-
}
47-
48-
client<llm> GPT4Turbo {
49-
provider baml-openai-chat
50-
options {
51-
model gpt-4-1106-preview
52-
api_key env.OPENAI_API_KEY
53-
}
54-
}
55-
56-
function GetOrderInfo(input: string) -> OrderInfo {
57-
client GPT4Turbo
58-
prompt #"
59-
Extract this info from the email in JSON format:
60-
Before you output the JSON, please explain your
61-
reasoning step-by-step. Here is an example on how to do this:
62-
'If we think step by step we can see that ...
63-
therefore the output JSON is:
64-
{
65-
... the json schema ...
66-
}'
67-
"#
68-
}
69-
"##
70-
.to_string()
71-
}
72-
7326
// TODO: add a flag to run_test that's debug, to attach a collector on every test. The collector can be created inside run_test. Make the collector call track_function(..)
7427
// Then we can check the baml_tracer events since they'll be kept.
7528
#[wasm_bindgen_test]
@@ -90,7 +43,6 @@ mod tests {
9043
}
9144
}
9245
93-
9446
"##;
9547
let mut files = HashMap::new();
9648
files.insert("error.baml".to_string(), sample_baml_content.to_string());
@@ -122,14 +74,120 @@ mod tests {
12274
env_vars_js.clone().into(),
12375
None,
12476
)
125-
.await;
77+
.await
78+
.expect("run_test should succeed");
12679
}
12780

12881
let events = BAML_TRACER.lock().unwrap().events();
12982
log::info!("Events {events:#?}");
13083
// TODO: this makes the test hang on Node, but not in browser.
131-
flush().await;
84+
let _ = flush().await;
13285

13386
log::info!("done!!")
13487
}
88+
89+
#[wasm_bindgen_test]
90+
async fn test_streaming_run_test_with_expr_events() {
91+
let openai_key = match std::env::var("OPENAI_API_KEY") {
92+
Ok(key) if !key.trim().is_empty() => key,
93+
_ => {
94+
log::warn!("Skipping streaming test due to missing OPENAI_API_KEY");
95+
return;
96+
}
97+
};
98+
99+
BAML_TRACER.lock().unwrap().clear();
100+
101+
let sample_baml_content = r##"
102+
function Func(name: string ) -> string {
103+
client "openai/gpt-4o"
104+
prompt #"
105+
Return the name of {{name}}
106+
"#
107+
}
108+
109+
test One {
110+
functions [Func]
111+
args {
112+
name "stream"
113+
}
114+
}
115+
116+
"##;
117+
118+
let mut files = HashMap::new();
119+
files.insert(
120+
"streaming.baml".to_string(),
121+
sample_baml_content.to_string(),
122+
);
123+
let files_js = to_value(&files).unwrap();
124+
let project = WasmProject::new("baml_src", files_js)
125+
.map_err(JsValue::from)
126+
.unwrap();
127+
128+
let env_vars = HashMap::from([("OPENAI_API_KEY".to_string(), openai_key)]);
129+
let env_vars_js = to_value(&env_vars).unwrap();
130+
let undefined_js = JsValue::UNDEFINED;
131+
132+
let mut current_runtime = project.runtime(env_vars_js.clone(), undefined_js).unwrap();
133+
134+
let diagnostics = project.diagnostics(&current_runtime);
135+
assert!(diagnostics.errors().is_empty());
136+
137+
let functions = current_runtime.list_functions();
138+
let partial_results: Rc<RefCell<Vec<JsValue>>> = Rc::new(RefCell::new(Vec::new()));
139+
let expr_events: Rc<RefCell<Vec<JsValue>>> = Rc::new(RefCell::new(Vec::new()));
140+
141+
for f in functions.iter() {
142+
let partial_results_cb = {
143+
let responses = partial_results.clone();
144+
Closure::wrap(Box::new(move |value: JsValue| {
145+
responses.borrow_mut().push(value);
146+
}) as Box<dyn FnMut(JsValue)>)
147+
};
148+
149+
let expr_events_cb = {
150+
let events = expr_events.clone();
151+
Closure::wrap(Box::new(move |value: JsValue| {
152+
events.borrow_mut().push(value);
153+
}) as Box<dyn FnMut(JsValue)>)
154+
};
155+
156+
let on_partial_fn: js_sys::Function = partial_results_cb
157+
.as_ref()
158+
.unchecked_ref::<js_sys::Function>()
159+
.clone();
160+
let on_expr_fn: js_sys::Function = expr_events_cb
161+
.as_ref()
162+
.unchecked_ref::<js_sys::Function>()
163+
.clone();
164+
165+
f.run_test_with_expr_events(
166+
&mut current_runtime,
167+
"One".to_string(),
168+
on_partial_fn,
169+
js_sys::Function::new_no_args(""),
170+
on_expr_fn,
171+
env_vars_js.clone().into(),
172+
None,
173+
)
174+
.await
175+
.expect("streaming run_test_with_expr_events should succeed");
176+
177+
drop(partial_results_cb);
178+
drop(expr_events_cb);
179+
}
180+
181+
let tracer = BAML_TRACER.lock().unwrap();
182+
assert!(tracer.function_call_count() > 0);
183+
}
135184
}
185+
186+
// use wasm_bindgen_test::*;
187+
// wasm_bindgen_test_configure!(run_in_browser);
188+
189+
// #[wasm_bindgen_test]
190+
// fn test_hello_world() {
191+
// wasm_logger::init(wasm_logger::Config::new(log::Level::Info));
192+
// println!("Hello, world!");
193+
// }

‎engine/language_client_python/uv.lock‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎typescript/packages/playground-common/src/shared/baml-project-panel/playground-panel/prompt-preview/test-panel/components/atoms.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export interface TabularViewConfig {
1717
showDuration: boolean
1818
}
1919

20-
export const testPanelViewTypeAtom = atomWithStorage<TestPanelViewType>('testPanelViewType', TestPanelViewType.TABULAR, sessionStore)
20+
export const testPanelViewTypeAtom = atomWithStorage<TestPanelViewType>('testPanelViewType', TestPanelViewType.CARD_EXPANDED, sessionStore)
2121
export const tabularViewConfigAtom = atomWithStorage<TabularViewConfig>('tabularViewConfig', {
2222
showInputs: true,
2323
showModel: false,

0 commit comments

Comments
 (0)