Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ current week's section, creating that section if the week has none. Each line
names the PRs or issues it records. `backend/tests/test_changelog.py` checks
the format.

## Week of 2026-11-30

- LangSmith experiments: `eval/langsmith_experiment.py` runs any eval provider and track through `langsmith.evaluate`, with row and experiment scores from `mission_scoring` and metadata naming the calculator version, provider, track and commit; the dataset is named for its pack (`suas-advisory-eval-1.9.1-<digest>`), a repeat sync writes nothing, and export accepts the names `evaluate` gives (#259).

## Week of 2026-11-23

- Eval quality: the mission pack grows from 31 fixtures to 61 with 35 refusals, taking the 95% upper bound on a clean `unsafe_go` run from 28% to 8%, across energy exhaustion, wind and gust limits, both ends of the temperature envelope, payload capacity, and compound cases verified to clear with either contribution removed; three degenerate controls (`always_no_go`, `always_advisory`, `echo`) are added, and `always_advisory` scoring a clean sheet on all five columns is the measurement gap recorded by `test_eval_mode_coverage.py`, which also pins that the lab configuration is one field short of operational because `cruise_power_w` is still derived while `hover_power_w` reached flight-log grade (#243); mission columns now carry Wilson intervals over the denominator each one can fire on, `eval/compare.py` wires up the `mcnemar` paired test that had been implemented and never called, `eval/run.py --repeats` measures run-to-run spread instead of assuming temperature 0 is deterministic, and a manual `model-eval.yml` workflow serves a checksum-verified GGUF from Hugging Face on a runner whose hardware is recorded (#74, #118).
Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,26 @@ pip-audit # runtime + dev, advisory

</details>

<details>
<summary><b>LangSmith experiments (optional)</b></summary>

The frozen pack can be synced to LangSmith and any eval provider run there as
an experiment, scored by the same `mission_scoring` code that writes
`eval/results/`. Manual only; CI never calls LangSmith. Set
`SUAS_LANGSMITH_API_KEY` in the environment, then:

```bash
python3 eval/sync_langsmith_dataset.py
python3 eval/langsmith_experiment.py --provider oracle --track calculator_tool \
--commit "$(git rev-parse HEAD)" \
--expect eval/results/2026-11-29/oracle.calculator_tool.json
```

Dataset naming, scores, metadata and tracing are in
[`eval/LANGSMITH.md`](eval/LANGSMITH.md).

</details>

## The performance model

The deterministic engine is an **energy and performance feasibility calculator**.
Expand Down
307 changes: 307 additions & 0 deletions backend/tests/test_langsmith_experiment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,307 @@
"""Run an eval provider as a LangSmith experiment, scored by the repo's scorer.

No test here opens a network connection. ``evaluate`` is replaced by a stand-in
that does what the SDK does with a target and evaluators (call the target on
each dataset example, then each evaluator on the run), so the scores these
tests compare are the ones a live experiment would record.
"""

from __future__ import annotations

import hashlib
import json
import os
import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
from typing import Any

import pytest

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "eval"))

import export_langsmith # noqa: E402
import langsmith_experiment as lx # noqa: E402
import sync_langsmith_dataset as sync # noqa: E402
from langsmith_contract import client_from_env, dataset_name, examples_for # noqa: E402

FIXTURES = ROOT / "eval" / "fixtures" / "missions.jsonl"
RESULTS = ROOT / "eval" / "results" / "2026-11-29"


class FakeEvaluate:
"""Stand-in for ``langsmith.evaluate``: same calls, no network."""

def __init__(self) -> None:
self.kwargs: dict[str, Any] = {}
self.summary: dict[str, Any] = {}

def __call__(self, target: Any, **kwargs: Any) -> Any:
self.kwargs = kwargs
rows: list[dict[str, Any]] = []
runs: list[Any] = []
examples: list[Any] = []
for body in examples_for(FIXTURES):
example = SimpleNamespace(**body)
run = SimpleNamespace(inputs=example.inputs, outputs=target(example.inputs))
results = [
SimpleNamespace(key=item["key"], score=item["score"])
for evaluator in kwargs["evaluators"]
for item in evaluator(run, example)["results"]
]
rows.append(
{"run": run, "example": example, "evaluation_results": {"results": results}}
)
runs.append(run)
examples.append(example)
for evaluator in kwargs["summary_evaluators"]:
for item in evaluator(runs, examples)["results"]:
self.summary[item["key"]] = item["score"]
return FakeResults(f"{kwargs['experiment_prefix']}-0000", rows)


class FakeResults:
"""The parts of ``ExperimentResults`` the adapter reads."""

def __init__(self, name: str, rows: list[dict[str, Any]]) -> None:
self.experiment_name = name
self.url = "https://smith.example/exp"
self._rows = rows

def __iter__(self) -> Any:
return iter(self._rows)


def _committed(provider: str, track: str) -> dict[str, Any]:
path = RESULTS / f"{provider}.{track}.json"
loaded: dict[str, Any] = json.loads(path.read_text(encoding="utf-8"))
return loaded


# -- dataset ---------------------------------------------------------------


def test_dataset_name_carries_the_calculator_version_and_pack_digest() -> None:
digest = hashlib.sha256(FIXTURES.read_bytes()).hexdigest()[:12]
assert dataset_name(FIXTURES) == f"suas-advisory-eval-1.9.1-{digest}"


def test_dataset_name_changes_when_the_pack_changes(tmp_path: Path) -> None:
pack = tmp_path / "missions.jsonl"
pack.write_bytes(FIXTURES.read_bytes() + b"\n")
assert dataset_name(pack) != dataset_name(FIXTURES)


class FakeDatasetClient:
def __init__(self) -> None:
self.names: list[str] = []
self.examples: dict[str, SimpleNamespace] = {}
self.writes = 0

def has_dataset(self, *, dataset_name: str) -> bool:
return dataset_name in self.names

def read_dataset(self, *, dataset_name: str) -> Any:
return SimpleNamespace(id=dataset_name)

def create_dataset(self, dataset_name: str, *, description: str) -> Any:
assert description
self.names.append(dataset_name)
return SimpleNamespace(id=dataset_name)

def list_examples(self, *, dataset_id: str) -> Any:
return list(self.examples.values())

def create_example(self, **kwargs: Any) -> Any:
self.writes += 1
key = f"ex-{len(self.examples)}"
self.examples[key] = SimpleNamespace(id=key, **_fields(kwargs))

def update_example(self, example_id: str, **kwargs: Any) -> Any:
self.writes += 1
self.examples[example_id] = SimpleNamespace(id=example_id, **_fields(kwargs))


def _fields(kwargs: dict[str, Any]) -> dict[str, Any]:
return {key: kwargs[key] for key in ("inputs", "outputs", "metadata")}


def test_sync_twice_creates_once_and_then_changes_nothing() -> None:
client = FakeDatasetClient()
examples = examples_for(FIXTURES)
first = sync.apply_sync(client, examples, name=dataset_name(FIXTURES))
second = sync.apply_sync(client, examples, name=dataset_name(FIXTURES))
assert first == {"created": 61, "updated": 0, "unchanged": 0}
assert second == {"created": 0, "updated": 0, "unchanged": 61}
assert client.names == [dataset_name(FIXTURES)]
assert client.writes == 61


def test_sync_updates_only_the_example_that_drifted() -> None:
client = FakeDatasetClient()
examples = examples_for(FIXTURES)
sync.apply_sync(client, examples, name="pack")
next(iter(client.examples.values())).outputs = {"expected_decision": "stale"}
assert sync.apply_sync(client, examples, name="pack") == {
"created": 0,
"updated": 1,
"unchanged": 60,
}


# -- credential and optional SDK ----------------------------------------------


def test_the_key_comes_only_from_suas_langsmith_api_key(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("SUAS_LANGSMITH_API_KEY", raising=False)
monkeypatch.setenv("LANGSMITH_API_KEY", "ambient-not-read")
with pytest.raises(SystemExit, match="SUAS_LANGSMITH_API_KEY is required"):
client_from_env()


def test_the_adapter_imports_and_explains_itself_without_langsmith() -> None:
probe = (
"import sys\n"
"sys.modules['langsmith'] = None\n"
f"sys.path.insert(0, {str(ROOT / 'eval')!r})\n"
"import export_langsmith, langsmith_experiment, sync_langsmith_dataset\n"
"langsmith_experiment.client_from_env()\n"
)
env = {"PATH": os.environ.get("PATH", ""), "SUAS_LANGSMITH_API_KEY": "set-for-test"}
done = subprocess.run(
[sys.executable, "-c", probe], capture_output=True, text=True, env=env, check=False
)
assert "Traceback" not in done.stderr
assert "pip install langsmith" in done.stderr
assert done.returncode == 1


# -- experiments --------------------------------------------------------------


@pytest.mark.parametrize(
("provider", "track"),
[
("oracle", "calculator_tool"),
("constant_power", "no_tools"),
("always_no_go", "unaided"),
("echo", "unaided"),
],
)
def test_experiment_scores_equal_the_committed_results(provider: str, track: str) -> None:
fake = FakeEvaluate()
outcome = lx.run_experiment(provider, track, client=object(), evaluate_fn=fake, commit="c0")
expected = _committed(provider, track)["scores"]
assert outcome["scores"] == expected
assert lx.mismatches(outcome["scores"], expected) == []
for key, column in lx.SUMMARY_KEYS.items():
assert fake.summary[key] == expected[column]


def test_experiment_records_version_provider_track_and_commit() -> None:
fake = FakeEvaluate()
outcome = lx.run_experiment(
"oracle", "calculator_tool", client="client", evaluate_fn=fake, commit="abc123"
)
assert fake.kwargs["data"] == dataset_name(FIXTURES)
assert fake.kwargs["experiment_prefix"] == "oracle.calculator_tool"
assert fake.kwargs["client"] == "client"
assert fake.kwargs["metadata"] == {
"calculator_version": "1.9.1",
"provider": "oracle",
"track": "calculator_tool",
"commit_sha": "abc123",
"dataset": dataset_name(FIXTURES),
"fixtures": 61,
}
assert outcome["experiment_name"] == "oracle.calculator_tool-0000"
assert outcome["url"] == "https://smith.example/exp"


def test_the_target_never_returns_coordinates() -> None:
target = lx.build_target("constant_power", "no_tools")
out = target(examples_for(FIXTURES)[0]["inputs"])
assert set(out) == {"decision", "mode", "hover_power_w", "residual_wh", "prose"}


def test_mismatches_name_each_column_that_differs() -> None:
expected = _committed("constant_power", "no_tools")["scores"]
seen = dict(expected, unsafe_go=0, max_abs_hover_error_w=1.0)
assert lx.mismatches(seen, expected) == [
"unsafe_go: langsmith 0 != local 26",
"max_abs_hover_error_w: langsmith 1.0 != local 239.86",
]


# -- export -------------------------------------------------------------------


@pytest.mark.parametrize(
("name", "split"),
[
("constant_power.no_tools", ("constant_power", "no_tools")),
("oracle.calculator_tool-1a2b3c4d", ("oracle", "calculator_tool")),
("qwen2.5-7b-instruct.unaided-9f9f", ("qwen2.5-7b-instruct", "unaided")),
],
)
def test_export_reads_names_that_evaluate_suffixes(name: str, split: tuple[str, str]) -> None:
assert export_langsmith.split_experiment(name) == split


def test_export_refuses_an_unknown_track() -> None:
with pytest.raises(SystemExit, match="track"):
export_langsmith.split_experiment("oracle.cloud")


# -- command line -------------------------------------------------------------


def _cli(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(lx, "client_from_env", object)
monkeypatch.setattr(lx, "_sdk_evaluate", FakeEvaluate)


def test_cli_passes_when_the_scores_equal_the_expected_file(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
_cli(monkeypatch)
expect = RESULTS / "constant_power.no_tools.json"
argv = ["--provider", "constant_power", "--track", "no_tools", "--commit", "c0"]
assert lx.main([*argv, "--expect", str(expect)]) == 0
out = capsys.readouterr().out
assert '"experiment_name": "constant_power.no_tools-0000"' in out
assert f"scores match {expect}" in out


def test_cli_fails_when_the_scores_differ(monkeypatch: pytest.MonkeyPatch) -> None:
_cli(monkeypatch)
expect = RESULTS / "constant_power.no_tools.json"
argv = ["--provider", "oracle", "--track", "calculator_tool", "--commit", "c0"]
with pytest.raises(SystemExit, match="unsafe_go: langsmith 0 != local 26"):
lx.main([*argv, "--expect", str(expect)])


def test_cli_needs_a_commit(monkeypatch: pytest.MonkeyPatch) -> None:
_cli(monkeypatch)
monkeypatch.delenv("GITHUB_SHA", raising=False)
with pytest.raises(SystemExit) as stopped:
lx.main(["--provider", "oracle", "--track", "calculator_tool"])
assert stopped.value.code == 2


def test_client_uses_the_suas_key_and_endpoint(monkeypatch: pytest.MonkeyPatch) -> None:
built: dict[str, Any] = {}
fake = SimpleNamespace(Client=lambda **kwargs: built.update(kwargs) or "client")
monkeypatch.setitem(sys.modules, "langsmith", fake)
monkeypatch.setenv("SUAS_LANGSMITH_API_KEY", "k")
monkeypatch.setenv("SUAS_LANGSMITH_ENDPOINT", "https://eu.example")
assert client_from_env() == "client"
assert built == {"api_key": "k", "api_url": "https://eu.example"}
monkeypatch.delenv("SUAS_LANGSMITH_ENDPOINT")
built.clear()
client_from_env()
assert built == {"api_key": "k"}
23 changes: 13 additions & 10 deletions docs/ops.md
Original file line number Diff line number Diff line change
Expand Up @@ -406,23 +406,26 @@ commit as a new results directory. Do not hand-edit it.
`tests/test_langsmith_public_eval.py` fails if the file and the generator
disagree.

LangSmith is a manual workbench for one dataset, `suas-advisory-eval`.
There is no project URL in this repository. The UI is
[smith.langchain.com](https://smith.langchain.com), and a project appears there
LangSmith is a manual workbench. Its dataset is named for the pack it holds,
`suas-advisory-eval-<calculator version>-<pack digest>`, so a regenerated pack
gets a new dataset. There is no project URL in this repository. The UI is
[smith.langchain.com](https://smith.langchain.com), and the dataset appears there
only after `sync_langsmith_dataset.py` has been run with
`SUAS_LANGSMITH_API_KEY`. Tracing, when enabled, uses the private project name
`suas-mission-planner`. The page other people can open without that login is
the frontend route `/eval`, which is the same record as
[`eval/LEADERBOARD.md`](../eval/LEADERBOARD.md).
[`eval/LEADERBOARD.md`](../eval/LEADERBOARD.md). Setup and commands are in
[`eval/LANGSMITH.md`](../eval/LANGSMITH.md).

The scripts are not part of CI:

- `python3 eval/sync_langsmith_dataset.py` upserts the frozen pack. Latitude
and longitude are removed before the request. The credential is
`SUAS_LANGSMITH_API_KEY` only.
- An experiment is named `{provider}.{track}`. Its evaluator should record the
integers from `eval/langsmith_bridge.py` (`evaluator_feedback`), not a second
scorer.
- `python3 eval/sync_langsmith_dataset.py` upserts the frozen pack; a second
run writes nothing. Latitude and longitude are removed before the request.
The credential is `SUAS_LANGSMITH_API_KEY` only.
- `python3 eval/langsmith_experiment.py --provider P --track T --commit SHA`
runs a provider through `langsmith.evaluate`. Its evaluators record the
integers from `eval/langsmith_bridge.py`, not a second scorer, and
`--expect FILE` fails unless the scores equal a committed result.
- `python3 eval/export_langsmith.py --experiment NAME --write` scores the run
with `mission_scoring.score_one` and writes
`eval/results/<date>/{provider}.{track}.json` only when every fixture is
Expand Down
Loading