Skip to content

Commit 3a8530f

Browse files
voidstackloopclaude
andcommitted
Reuse one LLM HTTP client across a whole monitor run
Performance improvement, not a new feature: runner::run_one_with (one call per form) reached into llm::run_semantic_checks, which called LlmClient::new() itself on every single call. LlmClient::new() builds a fresh reqwest::Client, i.e. an empty connection pool - so a registry of N forms with --llm enabled paid N separate DNS/TCP/TLS handshakes to the exact same provider host (api.openai.com, api.anthropic.com, ...) instead of reusing one pool of keep-alive connections. This compounds under --max-concurrent, where several of those handshakes happen at once for no reason. Fix: build the LlmClient once per test/monitor invocation (in main.rs, right alongside the browser and HostPacer that are already built once and shared) and thread it through run_one_with/run_semantic_checks as Option<&LlmClient> instead of rebuilding it inside the per-form call. Client-build failure (LlmClient::new only fails if the underlying TLS backend can't initialize, essentially never in practice) is now surfaced once via a single tracing::warn! instead of once per form, and still degrades every form's LLM checks to a Warn rather than failing the run - unchanged behavior, just not repeated pointlessly. Verified with a mutation test: temporarily forced build_llm_client to always return None regardless of input, confirmed the new unit test (build_llm_client_is_none_when_disabled_and_some_when_enabled) failed as predicted, then restored it and confirmed cargo test passes clean. cargo fmt/clippy -D warnings clean, full suite green (153 tests). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 26284f0 commit 3a8530f

6 files changed

Lines changed: 89 additions & 16 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,20 @@ project doesn't have a release yet, so everything below is grouped under
2222
for containers, and per-host request pacing (`--per-host-delay-ms`)
2323
plus an append-only, screenshot-free JSON audit log (`--audit-log`).
2424

25+
### Performance
26+
27+
- **LLM client reuse across a whole `monitor` run.** `--llm` semantic
28+
checks used to build a brand-new HTTP client (`LlmClient::new`) for
29+
every single form, discarding its connection pool immediately after —
30+
so a registry of N forms paid N separate DNS/TCP/TLS handshakes to the
31+
same provider host (openai.com, anthropic.com, ...) even though every
32+
form talks to the identical endpoint. The client is now built once per
33+
`test`/`monitor` invocation and passed by reference into every
34+
concurrent form task (`runner::run_one_with`'s new `llm_client`
35+
parameter), so the connection pool is actually shared. Client-build
36+
failure (rare) is now logged once instead of once per form, and still
37+
degrades every form's LLM checks to a `Warn`, never a dropped run.
38+
2539
### Added
2640

2741
- **GitHub Issues auto-tracking** (`--github-issues-repo owner/repo`,

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,10 @@ Design guarantees:
440440
- **Subjective by nature**, so a low score is a `Warn` by default; use
441441
`--llm-fail` (or `llm.fail: true`) to make it a `Fail`, and
442442
`--llm-threshold N` to set the pass bar.
443+
- **One shared HTTP client per run.** `monitor` builds the LLM client
444+
once and reuses it for every form (including concurrent ones under
445+
`--max-concurrent`), so a large registry pays one connection pool to
446+
the provider instead of a fresh DNS/TCP/TLS handshake per form.
443447
444448
Providers are `openai` (also any OpenAI-compatible endpoint), `anthropic`,
445449
and `mock` (no network — deterministic, for dry runs and CI of the tool

‎src/llm/mod.rs‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -540,8 +540,16 @@ async fn run_one(
540540
/// empty vec when the feature is disabled). A configuration that prevents
541541
/// any call — no API key — yields a single explanatory `Warn` rather than
542542
/// silently doing nothing.
543+
///
544+
/// `client` is built once per `test`/`monitor` invocation (see
545+
/// [`LlmClient::new`]) and shared across every form, so concurrent forms
546+
/// reuse one HTTP connection pool to the provider instead of each paying a
547+
/// fresh DNS/TCP/TLS handshake. `None` means the client failed to build
548+
/// (surfaced once by the caller); this still degrades to a `Warn`, never a
549+
/// dropped run.
543550
pub async fn run_semantic_checks(
544551
page: &Page,
552+
client: Option<&LlmClient>,
545553
options: &LlmOptions,
546554
capture: bool,
547555
) -> Vec<CheckResult> {
@@ -559,6 +567,13 @@ pub async fn run_semantic_checks(
559567
),
560568
)];
561569
}
570+
let Some(client) = client else {
571+
return vec![result(
572+
"LLM review",
573+
Status::Warn,
574+
"could not initialize the LLM client".to_string(),
575+
)];
576+
};
562577

563578
tracing::warn!(
564579
provider = options.provider.label(),
@@ -567,22 +582,11 @@ pub async fn run_semantic_checks(
567582
"LLM semantic checks enabled — page text is sent to the configured provider"
568583
);
569584

570-
let client = match LlmClient::new(options) {
571-
Ok(client) => client,
572-
Err(e) => {
573-
return vec![result(
574-
"LLM review",
575-
Status::Warn,
576-
format!("could not initialize the LLM client: {e:#}"),
577-
)];
578-
}
579-
};
580-
581585
// The two checks are independent; run them concurrently so the LLM
582586
// latency is paid once, not twice.
583587
let (errors, instructions) = tokio::join!(
584-
run_one(page, &client, options, capture, &ERROR_KIND),
585-
run_one(page, &client, options, capture, &INSTRUCTION_KIND),
588+
run_one(page, client, options, capture, &ERROR_KIND),
589+
run_one(page, client, options, capture, &INSTRUCTION_KIND),
586590
);
587591
vec![errors, instructions]
588592
}

‎src/main.rs‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ use clap_complete::Shell;
44
use formwatch::baseline::{self, Baseline};
55
use formwatch::config::{Config, FailOn, LlmConfig, NotifyOn};
66
use formwatch::limiter::host_of;
7-
use formwatch::llm::LlmOptions;
87
use formwatch::llm::provider::Provider;
8+
use formwatch::llm::{LlmClient, LlmOptions};
99
use formwatch::logging::{self, LogFormat};
1010
use formwatch::options::RunOptions;
1111
use formwatch::shard::Shard;
@@ -556,6 +556,7 @@ async fn main() -> Result<()> {
556556

557557
let (browser, _handle) = browser::launch_with(&settings.browser).await?;
558558
let pacer = HostPacer::new(Duration::from_millis(settings.per_host_delay_ms));
559+
let llm_client = build_llm_client(&settings.run.llm);
559560
if let Some(host) = host_of(&url) {
560561
pacer.wait_turn(&host).await;
561562
}
@@ -567,6 +568,7 @@ async fn main() -> Result<()> {
567568
&settings.run,
568569
&settings.open,
569570
settings.checks_dir.as_deref(),
571+
llm_client.as_ref(),
570572
)
571573
.await?;
572574
if let Some(path) = &settings.audit_log {
@@ -653,6 +655,7 @@ async fn main() -> Result<()> {
653655

654656
let (browser, _handle) = browser::launch_with(&settings.browser).await?;
655657
let pacer = HostPacer::new(Duration::from_millis(settings.per_host_delay_ms));
658+
let llm_client = build_llm_client(&settings.run.llm);
656659
let run_opts = &settings.run;
657660
let open_opts = &settings.open;
658661
let checks_dir_ref = settings.checks_dir.as_deref();
@@ -665,6 +668,7 @@ async fn main() -> Result<()> {
665668
.map(|(i, entry)| {
666669
let browser = &browser;
667670
let pacer = &pacer;
671+
let llm_client = llm_client.as_ref();
668672
async move {
669673
if let Some(host) = host_of(&entry.url) {
670674
pacer.wait_turn(&host).await;
@@ -677,6 +681,7 @@ async fn main() -> Result<()> {
677681
run_opts,
678682
open_opts,
679683
checks_dir_ref,
684+
llm_client,
680685
)
681686
.await
682687
{
@@ -908,6 +913,25 @@ fn resolve(
908913
}
909914
}
910915

916+
/// Builds the shared [`LlmClient`] once per `test`/`monitor` invocation, so
917+
/// every form's LLM checks reuse one HTTP connection pool instead of each
918+
/// paying a fresh handshake to the provider. `None` when LLM checks are
919+
/// disabled, or (rare) client construction failed — logged once here
920+
/// rather than once per form.
921+
fn build_llm_client(llm: &Option<LlmOptions>) -> Option<LlmClient> {
922+
let options = llm.as_ref()?;
923+
match LlmClient::new(options) {
924+
Ok(client) => Some(client),
925+
Err(e) => {
926+
tracing::warn!(
927+
error = format!("{e:#}"),
928+
"could not initialize the LLM client; LLM checks will be skipped this run"
929+
);
930+
None
931+
}
932+
}
933+
}
934+
911935
/// Builds [`LlmOptions`] from CLI + config, or `None` when the feature is
912936
/// disabled. API keys are only taken from an explicit flag/config; the
913937
/// provider's environment variable is consulted later, at call time.
@@ -1493,6 +1517,21 @@ mod tests {
14931517
}
14941518
}
14951519

1520+
#[test]
1521+
fn build_llm_client_is_none_when_disabled_and_some_when_enabled() {
1522+
// The client is built once per invocation (not once per form, see
1523+
// runner::run_one_with) — this only checks the wiring itself: no
1524+
// options means no client, and enabled options (Mock needs no API
1525+
// key) build one successfully rather than erroring.
1526+
assert!(build_llm_client(&None).is_none());
1527+
let options = LlmOptions {
1528+
enabled: true,
1529+
provider: Provider::Mock,
1530+
..LlmOptions::default()
1531+
};
1532+
assert!(build_llm_client(&Some(options)).is_some());
1533+
}
1534+
14961535
#[test]
14971536
fn fail_on_policy_controls_which_statuses_breach() {
14981537
// The exit code is the whole point of running this in CI. Under the

‎src/runner.rs‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,19 @@ pub async fn run_one(
3535
},
3636
&browser::OpenOptions::default(),
3737
checks_dir,
38+
None,
3839
)
3940
.await
4041
}
4142

4243
/// [`run_one`], honoring caller-supplied run and browser-open options.
44+
///
45+
/// `llm_client` should be built once per `test`/`monitor` invocation (not
46+
/// once per form) and passed by reference to every call, so concurrent
47+
/// forms share one HTTP connection pool to the LLM provider instead of each
48+
/// paying a fresh handshake. Pass `None` when `opts.llm` is `None` or the
49+
/// client failed to build.
50+
#[allow(clippy::too_many_arguments)]
4351
pub async fn run_one_with(
4452
browser: &Browser,
4553
history_dir: &Path,
@@ -48,6 +56,7 @@ pub async fn run_one_with(
4856
opts: &options::RunOptions,
4957
open_opts: &browser::OpenOptions,
5058
checks_dir: Option<&Path>,
59+
llm_client: Option<&crate::llm::LlmClient>,
5160
) -> Result<history::RunResult> {
5261
let checks = match browser::open_with(browser, &url, open_opts).await {
5362
Ok(page) => {
@@ -64,7 +73,9 @@ pub async fn run_one_with(
6473
}
6574
}
6675
if let Some(llm) = &opts.llm {
67-
checks.extend(crate::llm::run_semantic_checks(&page, llm, opts.screenshots).await);
76+
checks.extend(
77+
crate::llm::run_semantic_checks(&page, llm_client, llm, opts.screenshots).await,
78+
);
6879
}
6980
let _ = page.close().await;
7081
checks

‎tests/checks_test.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -762,7 +762,8 @@ async fn llm_semantic_checks_run_against_a_page_with_the_mock_provider() {
762762
cache: false,
763763
..formwatch::llm::LlmOptions::default()
764764
};
765-
let results = formwatch::llm::run_semantic_checks(&page, &options, false).await;
765+
let client = formwatch::llm::LlmClient::new(&options).expect("client");
766+
let results = formwatch::llm::run_semantic_checks(&page, Some(&client), &options, false).await;
766767

767768
assert_eq!(results.len(), 2, "expected two LLM checks: {results:#?}");
768769
for check in &results {

0 commit comments

Comments
 (0)