mirror of
https://github.com/baserow/baserow.git
synced 2026-12-04 00:08:25 +00:00
[4/4] test: harden assistant evals and tool contracts (#6007)
* test: bring Kuma eval baseline and dataset updates from #6006 * test: harden assistant evals and tool contracts Add production-replay datasets, resilient eval execution and comparison UI, a committed baseline, and broad tool contract and chain coverage on top of the runtime behavior changes. * test: align tool contracts with #6006 list_tables and permission output * fix: restore the eval runner results tab and pin it structurally The Results tab shipped unable to execute: the closing brace of usageCell was dropped, renderResults read an undeclared totals, the cost cell still called the old four-argument usageCell, and a second pane clear wiped the dataset errors appended just above it. Two tests covered the tab by asserting substrings of the page, so all four passed against dead script. Check the page structurally instead, with a small tokenizer, because the backend CI image has no JavaScript engine and a node-based test would silently skip there. Replace the sampled tool-visibility assertions with the full routed-tool map, so adding a tool has to state its reach rather than inherit one. * test: score eval checks against the call that actually ran An incomplete cross-mode call is answered with a re-call redirect, so the first create_workflows call can hold a pre-switch guess rather than the arguments that executed. Score the executed call instead, recognising the redirect through the router's own helper in both its retry and tool-result forms. * test: score the update_row target from the database, not the first draft The check read row_id out of the recorded create_workflows arguments, which are the model's raw output. When those arguments fail validation the toolset's argument-repair agent fixes them and the tool runs with the repaired payload, so a workflow that correctly names its row still scored as missing one. Measured over ten repetitions this produced one false failure; the trace shows execute_tool succeeding and a fix_agent span right behind it. Read the persisted service instead, like the neighbouring trigger and action checks already do. * test: check saved values in the prod-replay evals Replay checks now verify the form collects the order fields, the page was inspected, the requested tables have rows, ISO week numbers and signed amounts are correct for seeded rows, no broken formula is left behind, and all 30 employee rows carry typed values. * fix: compare eval results only across the same case population A baseline captured on an older dataset version ran a different set of cases, so its means are not comparable. The Results tab now requires the experiment and baseline to share a dataset version and says when they do not. * test: expect Kuma to ask when an implied app table is missing #6006 decided that a request to show records refers to workspace data, so Kuma asks where the projects come from instead of inventing a table. The eval had been flipped to expect building; restore the ask expectation while the explicit example-app case still builds. * test: accept date subtraction as a correct date-difference answer Subtracting two date fields returns a duration (verified: 5 days for 2026-01-01 to 2026-01-06), so an answer that subtracts the dates is correct even when it does not name date_diff. Retrieval rarely surfaces the reference-guide passage for date_diff, which made this case fail three times in four on an accurate answer. * test: expect Kuma to offer a sample-data table when app records are missing When no table holds the records an app should show, Kuma should create nothing and ask, offering a table with sample data among the next steps. * test: accept a plain-text question when Kuma must ask ask_user only records a question for the final answer, so a run that asks in its reply and builds nothing behaves the same for the user. The ask checks still require that nothing was created. * test: match docs keywords through Markdown emphasis Answers bold feature names, so '**File** field' missed 'file field'. Keyword matching now ignores emphasis markers, and the OCR case accepts 'AI prompt', the field type's name in the product. * chore: recapture the Kuma eval baseline on the final stack Three repetitions of all 122 cases on 3ca6497591 with Groq GPT-OSS 120B (harness v5): 355/366 passed. Docs 192/192, core 9/9, database 61/63, builder 55/60, automation 20/21, prod-replay 18/21. * chore: drop an import the develop rebase left unused * test: expect docs search in every mode * test: require complete tracker and employee replay data * fix: compare Kuma eval results using recorded cases and checks * fix: correct Kuma eval scoring and preserve baseline runs * test: reuse the seeded user in Kuma builder contracts * test: isolate async docs-search database fixtures Create users and workspaces in synchronous pytest fixtures so their writes stay inside the rollback transaction. Async setup previously used a separate autocommit connection and leaked users, causing later data-sync tests to fail on duplicate usernames. Remove the global async-safety bypass, enforce Django's guard locally, and keep the real database hybrid test synchronous around its async tool call. Verified the seeded two-test reproduction fails before and passes after with no leaked users. All 71 focused tests and 1,742 broader tests pass; one existing test is skipped. Scoped pre-commit checks pass. * docs: update Builder eval count after rebase * fix: grade saved assistant results and preserve eval errors
This commit is contained in:
1 parent
4187dbb2c8
commit
dc62052c97
33 files changed
+8854
-8839
No files matched your search
+4
-1
@@ -6,4 +6,7 @@
|
||||
# Prettier does not allow windows file endings by default
|
||||
*.js text eol=lf
|
||||
*.vue text eol=lf
|
||||
*.scss text eol=lf
|
||||
*.scss text eol=lf
|
||||
|
||||
# Machine-captured eval baseline snapshot: collapsed in PR review
|
||||
enterprise/backend/src/baserow_enterprise/assistant/evals/baseline.json linguist-generated=true
|
||||
@@ -147,3 +147,13 @@ and current-turn evidence. Domain
|
||||
tool tests verify saved state and reconciliation. For live model runs, use the
|
||||
[eval platform](../testing/ai-assistant-evals.md) with a disposable database and
|
||||
record the source revision, model settings, case population, and failures.
|
||||
Generated eval user identities use UUIDs because the database persists across
|
||||
scenarios and Faker's per-instance uniqueness cache does not.
|
||||
Eval harness version 5 preserves version 3's exclusion of required mode-switch
|
||||
redirects from the tool-error budget. Genuine argument and output-validation
|
||||
failures still count. It also matches production's sequential tool execution,
|
||||
records request-limit, model/tool retry exhaustion, and other case errors as
|
||||
failures without retrying or aborting the suite, and checks
|
||||
saved Builder navigation and card values across multiple records. Metadata records
|
||||
the evaluator source hash. Older score totals must be interpreted with their
|
||||
recorded checks, harness version, and configuration.
|
||||
@@ -10,7 +10,7 @@ The baseline is a committed snapshot of a full-suite run (default model,
|
||||
current branch) at
|
||||
`enterprise/backend/src/baserow_enterprise/assistant/evals/baseline.json`.
|
||||
The eval runner imports it automatically on startup, so every Phoenix
|
||||
instance — a fresh dev stack or the team one — has a `baseline` experiment
|
||||
instance — a fresh dev stack or the team one — has a `baseline (imported)` experiment
|
||||
on each dataset without re-running anything. Manually: `just b eval-baseline
|
||||
import`.
|
||||
|
||||
@@ -27,8 +27,9 @@ Commit the regenerated `baseline.json` with the change that earned it.
|
||||
|
||||
## Comparing a run to the baseline
|
||||
|
||||
Open the dataset in Phoenix → select the `baseline` experiment and yours →
|
||||
**Compare**. The three scores:
|
||||
Open the dataset in Phoenix → select your live `baseline` experiment and yours →
|
||||
**Compare**. Select `baseline (imported)` for historical inspection, checking its
|
||||
case and scoring compatibility before drawing conclusions. The three scores:
|
||||
|
||||
- `checklist` — fraction of the case's checks that passed (the explanation
|
||||
lists exactly which failed, with hints).
|
||||
@@ -41,14 +42,18 @@ Phoenix compares within one dataset. For **all datasets in one view**, use
|
||||
the runner page's **Results** tab: pick an experiment name (a run started
|
||||
from the page lands under the same name in every dataset it touched) and see
|
||||
each dataset's mean scores, execution status, and recorded run count. Baseline
|
||||
deltas and the overall aggregate are deferred; use Phoenix for per-case
|
||||
comparisons. Skipped and ungraded cases are excluded from scores, so check their
|
||||
coverage in Phoenix even when the selected cases match.
|
||||
deltas require complete live experiments with matching dataset versions,
|
||||
recorded case counts, and check implementation hashes (`evaluator_source_hash`).
|
||||
Imported snapshots remain available for individual inspection, but are excluded
|
||||
from automatic deltas and Overall comparisons: the importer assigns the current
|
||||
Phoenix dataset version, so matching version IDs cannot prove that historical
|
||||
cases and checks match. Use Phoenix to inspect the per-case evidence before
|
||||
drawing conclusions from an imported baseline.
|
||||
|
||||
The committed snapshot predates the fix that applies production orchestrator
|
||||
settings and retries in evals. Its settings are unverified. A fresh baseline is
|
||||
part of the comparison follow-up; the old snapshot remains useful as historical
|
||||
per-case output.
|
||||
The committed snapshot holds three repetitions of every case, with the source
|
||||
commit, model settings, and harness version in its metadata. Recapture it from a
|
||||
clean commit whenever cases, checks, or prompts change. Automatic deltas require
|
||||
a compatible live baseline experiment, even after importing a refreshed snapshot.
|
||||
|
||||
The tab also shows **time and cost** per dataset: time is the
|
||||
sum of run latencies (the runner executes sequentially, so it approximates
|
||||
@@ -57,10 +62,15 @@ wall clock), cost and tokens come from Phoenix's per-model token prices
|
||||
cost or latency is a win too — and a score improvement that triples cost is
|
||||
a trade-off to state explicitly. The baseline's time/cost are frozen into
|
||||
the snapshot at capture time, since imported baselines carry no traces to
|
||||
price. Note
|
||||
that whole-dataset experiments include UI-added examples in their mean while
|
||||
the baseline holds code cases only, so a small delta on such datasets can be
|
||||
composition, not regression — the per-case compare settles it.
|
||||
price. Partial and all-skipped experiments are marked incomplete and excluded
|
||||
from deltas and the Overall row, which only compares compatible complete datasets.
|
||||
Overall uses each experiment's recorded case count (expected runs divided by
|
||||
repetitions), not today's registry, and includes only cases covered by each metric.
|
||||
Skipped and ungraded cases do not contribute to scores; inspect their coverage
|
||||
in Phoenix. Compatible runs may use different `--runs` counts: scores are means,
|
||||
and time/cost are normalised per pass over the dataset. Whole-dataset experiments include
|
||||
UI-added examples while the committed baseline holds code cases only; check
|
||||
their per-case coverage before making a manual comparison.
|
||||
|
||||
Look at **per-case deltas, not the aggregate**: a +0.02 mean can hide one
|
||||
real regression cancelled by two flaky recoveries. Suspected flakiness?
|
||||
|
||||
@@ -13,7 +13,8 @@ trace. Why this platform: [ADR 007](../decisions/007-ai-assistant-eval-platform.
|
||||
[AI assistant tracing](../development/ai-assistant-tracing.md) for the
|
||||
Phoenix side.
|
||||
2. `just dc-dev up -d` — the `assistant-eval-runner` service migrates its own
|
||||
`baserow_evals` database, syncs the datasets into Phoenix, and serves
|
||||
`baserow_evals` database, seeds its knowledge base when embeddings are
|
||||
configured, syncs the datasets into Phoenix, and serves
|
||||
`http://localhost:8090`.
|
||||
3. Pick a whole dataset or individual cases, a model (pick **Custom…** to
|
||||
type any pydantic-ai model string), a repeat count, optional notes, and Run.
|
||||
@@ -48,8 +49,8 @@ chatter (httpx, pydantic-ai retries) still goes to
|
||||
### Timeouts
|
||||
|
||||
Every case has a wall-clock budget — `BASEROW_EVAL_CASE_TIMEOUT`, default
|
||||
120s. For scale: across the committed baseline's 111 runs the slowest case
|
||||
takes 16.4s and the median 5.8s, so the budget only ever fires on a genuine
|
||||
120s. For scale: across the committed baseline's 366 runs the slowest
|
||||
case takes 44s and the median 6s, so the budget only ever fires on a genuine
|
||||
hang. Without it a single stuck case blocks the one worker indefinitely, and
|
||||
the per-request timeouts don't bound it: `max_iters` requests times the
|
||||
per-request timeout, plus retries, runs into several minutes.
|
||||
@@ -66,6 +67,22 @@ and the runner refuses further cases. In-flight threads cannot safely be
|
||||
stopped, so prompt overrides remain in place. Restart the eval runner before
|
||||
running another experiment (`just dc-dev restart assistant-eval-runner`).
|
||||
|
||||
Each case also has an intentional request budget (`max_iters`). Exhausting it
|
||||
is recorded as a failed case rather than aborting the dataset, so a genuine
|
||||
agent loop stays visible while the remaining cases still run. Transient
|
||||
provider rate limits are retried at the individual request boundary, honoring
|
||||
`Retry-After` when the provider supplies it.
|
||||
|
||||
Unexpected setup, tool-code, check and explicit provider errors are recorded as
|
||||
ungraded Phoenix errors and keep the experiment incomplete. A full-dataset run
|
||||
logs the error and continues without retrying the whole case. A subset run
|
||||
records the error and stops. Provider request retries remain separate.
|
||||
|
||||
Pydantic AI's `UnexpectedModelBehavior` remains a scored failure: it includes
|
||||
exhausted model validation, but also some malformed provider responses. The
|
||||
library does not reliably distinguish these cases; finer classification is
|
||||
deferred rather than inferred from provider error messages.
|
||||
|
||||
**Stop** is cooperative and lands at the next case boundary, because the
|
||||
worker sits inside a blocking LLM call that Python cannot interrupt. Queued
|
||||
runs stop immediately; a running one finishes its current case first and ends
|
||||
@@ -78,13 +95,45 @@ all** when an error is going to sink every remaining case anyway.
|
||||
A selection spanning several datasets fans out to one experiment per dataset,
|
||||
and the Results tab groups experiments by name. Leaving **Experiment name**
|
||||
blank generates one shared `run-<timestamp>-<id>` name for the whole fan-out,
|
||||
so the Results tab compares every dataset against the baseline in one view.
|
||||
so the Results tab shows every dataset in one view.
|
||||
Type a name instead to group runs yourself — reusing a name across separate
|
||||
submissions merges them into one group.
|
||||
|
||||
Experiments created before this grouping existed each carry their own
|
||||
Phoenix-generated name, so they stay ungrouped.
|
||||
|
||||
The Results tab marks a dataset incomplete unless every expected run has both
|
||||
mandatory scores. Incomplete datasets show no baseline deltas and are excluded
|
||||
from the overall row; that prevents a stopped, skipped, or partially logged run
|
||||
from looking like a quality, latency, or cost improvement.
|
||||
|
||||
Automatic baseline comparisons require complete live experiments with matching
|
||||
dataset versions, recorded case counts, and check implementation hashes
|
||||
(`evaluator_source_hash`). Imported baseline snapshots remain available for
|
||||
individual inspection, but show no automatic deltas or Overall comparisons:
|
||||
the importer uses the current Phoenix dataset version, which cannot establish
|
||||
that the historical cases and checks match.
|
||||
To enable automatic deltas, run a fresh experiment named `baseline` with the same
|
||||
cases and checks as the candidate.
|
||||
|
||||
Snapshots are imported as `baseline (imported)`, keeping live `baseline` runs
|
||||
separate. Startup replaces only imports, after the replacement's runs and scores
|
||||
are saved. Removed snapshot cases are skipped without repeating the import on
|
||||
every restart; interrupted imports are retried.
|
||||
Failed imports remove only their new partial experiment, preserving the previous
|
||||
baseline. Capturing a baseline rejects experiments with execution errors before
|
||||
replacing the snapshot; scored model failures remain valid baseline results.
|
||||
|
||||
Overall weights scores by each experiment's recorded case count (expected runs
|
||||
divided by repetitions), not today's registry. It includes only comparable
|
||||
datasets and the cases covered by each metric.
|
||||
|
||||
Repetition counts may differ between the run and the baseline. Scores are means,
|
||||
so a `--runs 3` experiment can compare with a compatible single-pass baseline; time
|
||||
and cost are totals, so both sides are divided by their repetitions and shown
|
||||
per pass over the dataset. The model cell notes the two counts whenever they are
|
||||
not both 1.
|
||||
|
||||
### Recording why a run differed
|
||||
|
||||
Every experiment is stamped with its model, the resolved orchestrator
|
||||
@@ -94,6 +143,11 @@ configuration that produced it without writing anything down. The **Notes**
|
||||
field adds free text for whatever that does not cover; both the settings and
|
||||
the note show under the model in the Results tab.
|
||||
|
||||
The Docker runner receives the branch and commit label when its container is
|
||||
created. After changing commits, wait for active runs to finish, then run
|
||||
`just dc-dev up -d --no-deps assistant-eval-runner` to refresh that label before
|
||||
starting another experiment.
|
||||
|
||||
> **Warning:** the runner hot-reloads on any mounted `.py` change (including
|
||||
> a lint/format pass), which kills queued and running experiments — don't
|
||||
> edit backend Python while a run is in flight.
|
||||
@@ -134,8 +188,9 @@ hashes, so branch/model comparisons are filterable in Phoenix.
|
||||
|---------|-------|--------|
|
||||
| `kuma-core` | 3 | creating/listing databases and automations |
|
||||
| `kuma-database` | 21 | tables, fields, views, filters, rows |
|
||||
| `kuma-builder` | 16 | pages, elements, data sources, themes, user sources |
|
||||
| `kuma-builder` | 21 | pages, elements, data sources, themes, user sources |
|
||||
| `kuma-automation` | 7 | workflows, triggers, nodes |
|
||||
| `kuma-prod-replay` | 7 | invented prompts for failure classes that used to end the turn |
|
||||
| `kuma-docs` | 64 | docs Q&A via `search_user_docs`, incl. cannot-do guardrail cases |
|
||||
|
||||
`kuma-docs` needs the `embeddings` service (`ai` profile) and a knowledge base
|
||||
@@ -152,8 +207,10 @@ just dc-dev exec assistant-eval-runner just b manage sync_knowledge_base
|
||||
The command indexes the repository's `enterprise/backend/website_export.csv`.
|
||||
Wait for it to finish before running docs cases. If it reports unavailable
|
||||
embeddings or pgvector, fix that prerequisite and run it again. When the knowledge
|
||||
base is unavailable, docs cases are skipped: a finished executor does not mean
|
||||
the evals passed. Check the run log and per-case Phoenix results.
|
||||
base is unavailable, a docs run fails before creating an experiment and its log
|
||||
shows the setup command. Historical runs may contain skipped cases: a finished
|
||||
executor does not mean the evals passed. Check the run log and per-case Phoenix
|
||||
results.
|
||||
|
||||
## Writing a new eval
|
||||
|
||||
|
||||
+389
-7934
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,6 @@
|
||||
"""Committed baseline snapshot: capture experiment results from Phoenix and
|
||||
import them into any (fresh) instance as a ``baseline`` experiment per
|
||||
dataset, so every later run has a stable comparison column without re-running
|
||||
the suite.
|
||||
import them into any (fresh) instance as a ``baseline (imported)`` experiment
|
||||
per dataset for historical inspection without re-running the suite.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,7 +19,7 @@ from loguru import logger
|
||||
from baserow_enterprise.assistant.evals.registry import cases_by_dataset
|
||||
|
||||
BASELINE_PATH = Path(__file__).with_name("baseline.json")
|
||||
BASELINE_EXPERIMENT_NAME = "baseline"
|
||||
BASELINE_EXPERIMENT_NAME = "baseline (imported)"
|
||||
|
||||
_ANNOTATIONS_QUERY = """
|
||||
query ($runId: ID!) {
|
||||
@@ -114,6 +113,44 @@ def _delete_experiments(experiment_ids: list[str]) -> None:
|
||||
_graphql(_DELETE_EXPERIMENTS_MUTATION, {"ids": experiment_ids})
|
||||
|
||||
|
||||
def _mark_import_complete(experiment_id: str, metadata: dict[str, Any]) -> None:
|
||||
"""Mark an import complete only after its runs and annotations were saved."""
|
||||
|
||||
response = httpx.patch(
|
||||
f"{_api_base()}/v1/experiments/{experiment_id}",
|
||||
json={"metadata": {**metadata, "baseline_import_complete": True}},
|
||||
headers=_headers(),
|
||||
timeout=30,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
def _delete_stale_imports(
|
||||
experiments: list[dict[str, Any]], dataset_name: str, keep_id: str
|
||||
) -> None:
|
||||
"""Remove replaced imports, preserving live experiments regardless of name."""
|
||||
|
||||
stale_ids = [
|
||||
experiment["id"]
|
||||
for experiment in experiments
|
||||
if experiment["id"] != keep_id
|
||||
and (experiment.get("metadata") or {}).get("baseline_snapshot_hash")
|
||||
]
|
||||
if not stale_ids:
|
||||
return
|
||||
try:
|
||||
_delete_experiments(stale_ids)
|
||||
logger.info(
|
||||
"Superseded {} imported baseline experiment(s) for '{}'",
|
||||
len(stale_ids),
|
||||
dataset_name,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Could not delete stale baseline imports for '{}': {}", dataset_name, exc
|
||||
)
|
||||
|
||||
|
||||
def _snapshot_hash(snapshot: dict[str, Any]) -> str:
|
||||
canonical = json.dumps(snapshot["datasets"], sort_keys=True)
|
||||
return hashlib.sha256(canonical.encode()).hexdigest()[:12]
|
||||
@@ -124,7 +161,8 @@ def capture_baseline(client: Any, experiment_name: str | None = None) -> dict[st
|
||||
|
||||
``experiment_name`` restricts the pick to experiments with that name —
|
||||
use it to capture a deliberate baseline run rather than whatever ran
|
||||
last. Registry must be loaded (``load_all``) before calling.
|
||||
last. Errored code runs abort capture without replacing the snapshot.
|
||||
Registry must be loaded (``load_all``) before calling.
|
||||
"""
|
||||
|
||||
snapshot: dict[str, Any] = {
|
||||
@@ -135,7 +173,7 @@ def capture_baseline(client: Any, experiment_name: str | None = None) -> dict[st
|
||||
|
||||
for dataset_name in cases_by_dataset():
|
||||
dataset = client.datasets.get_dataset(dataset=dataset_name)
|
||||
experiments = _get(f"/v1/datasets/{dataset.id}/experiments")
|
||||
experiments = client.experiments.list(dataset_id=dataset.id)
|
||||
if experiment_name:
|
||||
experiments = [e for e in experiments if e.get("name") == experiment_name]
|
||||
if not experiments:
|
||||
@@ -156,6 +194,12 @@ def capture_baseline(client: Any, experiment_name: str | None = None) -> dict[st
|
||||
if not case_id:
|
||||
skipped += 1
|
||||
continue
|
||||
if run.get("error") is not None:
|
||||
raise ValueError(
|
||||
f"Cannot capture baseline for '{dataset_name}': experiment "
|
||||
f"'{experiment['id']}' has an errored run for '{case_id}': "
|
||||
f"{run['error']}"
|
||||
)
|
||||
runs.append(
|
||||
{
|
||||
"case_id": case_id,
|
||||
@@ -178,17 +222,45 @@ def capture_baseline(client: Any, experiment_name: str | None = None) -> dict[st
|
||||
+ (f" ({skipped} non-code runs skipped)" if skipped else "")
|
||||
)
|
||||
|
||||
BASELINE_PATH.write_text(json.dumps(snapshot, indent=2) + "\n")
|
||||
BASELINE_PATH.write_text(_dump_snapshot(snapshot))
|
||||
results["file"] = str(BASELINE_PATH)
|
||||
return results
|
||||
|
||||
|
||||
def import_baseline(client: Any) -> dict[str, str]:
|
||||
"""Create a ``baseline`` experiment per dataset from ``baseline.json``.
|
||||
def _dump_snapshot(snapshot: dict[str, Any]) -> str:
|
||||
"""Serialize with one compact line per run.
|
||||
|
||||
Idempotent: a dataset already holding an experiment stamped with this
|
||||
snapshot's content hash is left alone. Cases that no longer exist in the
|
||||
live dataset are skipped with a count.
|
||||
:param snapshot: The captured baseline snapshot.
|
||||
:return: JSON text that parses back to *snapshot* exactly.
|
||||
"""
|
||||
|
||||
compact = (",", ":")
|
||||
lines = ["{", f' "captured_at": {json.dumps(snapshot["captured_at"])},']
|
||||
lines.append(' "datasets": {')
|
||||
ds_items = list(snapshot["datasets"].items())
|
||||
for di, (name, data) in enumerate(ds_items):
|
||||
lines.append(f" {json.dumps(name)}: {{")
|
||||
for key in ("experiment_name", "metadata", "totals"):
|
||||
value = json.dumps(data[key], separators=compact)
|
||||
lines.append(f" {json.dumps(key)}: {value},")
|
||||
lines.append(' "runs": [')
|
||||
for ri, run in enumerate(data["runs"]):
|
||||
comma = "," if ri < len(data["runs"]) - 1 else ""
|
||||
lines.append(f" {json.dumps(run, separators=compact)}{comma}")
|
||||
lines.append(" ]")
|
||||
lines.append(" }" + ("," if di < len(ds_items) - 1 else ""))
|
||||
lines.append(" }")
|
||||
lines.append("}")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def import_baseline(client: Any) -> dict[str, str]:
|
||||
"""Create historical experiments from ``baseline.json``, separate from live runs.
|
||||
|
||||
Completed imports for the same snapshot and dataset version are retained.
|
||||
Removed cases are skipped. Interrupted and legacy imports are replaced only
|
||||
after the new import has saved every applicable run and annotation.
|
||||
A failed attempt deletes only its own newly created experiment.
|
||||
"""
|
||||
|
||||
if not BASELINE_PATH.exists():
|
||||
@@ -204,82 +276,92 @@ def import_baseline(client: Any) -> dict[str, str]:
|
||||
results[dataset_name] = "dataset not found in Phoenix"
|
||||
continue
|
||||
|
||||
# Complete-only idempotency: a hash-stamped experiment that crashed
|
||||
# mid-import (fewer runs than the snapshot) is superseded, not kept.
|
||||
experiments = _get(f"/v1/datasets/{dataset.id}/experiments")
|
||||
if any(
|
||||
(e.get("metadata") or {}).get("baseline_snapshot_hash") == content_hash
|
||||
and (e.get("successful_run_count") or 0) >= len(data["runs"])
|
||||
for e in experiments
|
||||
):
|
||||
results[dataset_name] = "already imported"
|
||||
continue
|
||||
|
||||
stale_ids = [
|
||||
e["id"] for e in experiments if e.get("name") == BASELINE_EXPERIMENT_NAME
|
||||
]
|
||||
if stale_ids:
|
||||
try:
|
||||
_delete_experiments(stale_ids)
|
||||
logger.info(
|
||||
"Superseded {} stale baseline experiment(s) for '{}'",
|
||||
len(stale_ids),
|
||||
dataset_name,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Could not delete stale baseline for '{}': {}", dataset_name, exc
|
||||
)
|
||||
|
||||
node_by_case_id = {
|
||||
example["metadata"]["case_id"]: example.get("node_id") or example["id"]
|
||||
for example in dataset.examples
|
||||
if example.get("metadata", {}).get("case_id")
|
||||
}
|
||||
applicable_runs = [
|
||||
run for run in data["runs"] if run["case_id"] in node_by_case_id
|
||||
]
|
||||
skipped = len(data["runs"]) - len(applicable_runs)
|
||||
if not applicable_runs:
|
||||
results[dataset_name] = "no snapshot cases in the current dataset"
|
||||
continue
|
||||
|
||||
experiments = client.experiments.list(dataset_id=dataset.id)
|
||||
completed_import = next(
|
||||
(
|
||||
experiment
|
||||
for experiment in experiments
|
||||
if experiment.get("name") == BASELINE_EXPERIMENT_NAME
|
||||
and experiment.get("dataset_version_id") == dataset.version_id
|
||||
and (experiment.get("metadata") or {}).get("baseline_snapshot_hash")
|
||||
== content_hash
|
||||
and (experiment.get("metadata") or {}).get("baseline_import_complete")
|
||||
is True
|
||||
and (experiment.get("successful_run_count") or 0)
|
||||
>= len(applicable_runs)
|
||||
),
|
||||
None,
|
||||
)
|
||||
if completed_import is not None:
|
||||
# A previous import may have finished before its cleanup was interrupted.
|
||||
_delete_stale_imports(experiments, dataset_name, completed_import["id"])
|
||||
results[dataset_name] = "already imported"
|
||||
continue
|
||||
|
||||
import_metadata = {
|
||||
**data.get("metadata", {}),
|
||||
"baseline": True,
|
||||
"baseline_snapshot_hash": content_hash,
|
||||
"baseline_import_complete": False,
|
||||
"baseline_totals": data.get("totals") or {},
|
||||
"captured_at": snapshot.get("captured_at"),
|
||||
}
|
||||
experiment = client.experiments.create(
|
||||
dataset_id=dataset.id,
|
||||
dataset_version_id=dataset.version_id,
|
||||
experiment_name=BASELINE_EXPERIMENT_NAME,
|
||||
experiment_metadata={
|
||||
**data.get("metadata", {}),
|
||||
"baseline": True,
|
||||
"baseline_snapshot_hash": content_hash,
|
||||
"baseline_totals": data.get("totals") or {},
|
||||
"captured_at": snapshot.get("captured_at"),
|
||||
},
|
||||
repetitions=max(
|
||||
(run["repetition_number"] for run in data["runs"]), default=1
|
||||
),
|
||||
experiment_metadata=import_metadata,
|
||||
repetitions=max(run["repetition_number"] for run in applicable_runs),
|
||||
)
|
||||
|
||||
imported = skipped = 0
|
||||
for run in data["runs"]:
|
||||
node_id = node_by_case_id.get(run["case_id"])
|
||||
if node_id is None:
|
||||
skipped += 1
|
||||
continue
|
||||
logged = client.experiments.log_run(
|
||||
experiment_id=experiment["id"],
|
||||
dataset_example_id=node_id,
|
||||
output=run["output"],
|
||||
start_time=datetime.fromisoformat(run["start_time"]),
|
||||
end_time=datetime.fromisoformat(run["end_time"]),
|
||||
repetition_number=run["repetition_number"],
|
||||
)
|
||||
for annotation in run.get("annotations", []):
|
||||
if not _has_result(annotation):
|
||||
continue
|
||||
client.experiments.log_evaluation(
|
||||
experiment_run_id=logged["id"],
|
||||
name=annotation["name"],
|
||||
score=annotation.get("score"),
|
||||
label=annotation.get("label"),
|
||||
explanation=annotation.get("explanation"),
|
||||
try:
|
||||
for run in applicable_runs:
|
||||
logged = client.experiments.log_run(
|
||||
experiment_id=experiment["id"],
|
||||
dataset_example_id=node_by_case_id[run["case_id"]],
|
||||
output=run["output"],
|
||||
start_time=datetime.fromisoformat(run["start_time"]),
|
||||
end_time=datetime.fromisoformat(run["end_time"]),
|
||||
repetition_number=run["repetition_number"],
|
||||
)
|
||||
imported += 1
|
||||
for annotation in run.get("annotations", []):
|
||||
if not _has_result(annotation):
|
||||
continue
|
||||
client.experiments.log_evaluation(
|
||||
experiment_run_id=logged["id"],
|
||||
name=annotation["name"],
|
||||
score=annotation.get("score"),
|
||||
label=annotation.get("label"),
|
||||
explanation=annotation.get("explanation"),
|
||||
)
|
||||
_mark_import_complete(experiment["id"], import_metadata)
|
||||
except Exception:
|
||||
try:
|
||||
client.experiments.delete(experiment_id=experiment["id"])
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Could not delete failed baseline import '{}' for '{}': {}",
|
||||
experiment["id"],
|
||||
dataset_name,
|
||||
exc,
|
||||
)
|
||||
raise
|
||||
_delete_stale_imports(experiments, dataset_name, experiment["id"])
|
||||
|
||||
results[dataset_name] = f"imported {imported} runs" + (
|
||||
results[dataset_name] = f"imported {len(applicable_runs)} runs" + (
|
||||
f" ({skipped} removed cases skipped)" if skipped else ""
|
||||
)
|
||||
logger.info("Baseline import for '{}': {}", dataset_name, results[dataset_name])
|
||||
|
||||
+285
-412
@@ -9,9 +9,15 @@ and invalidate any existing baseline.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
from baserow.contrib.automation.models import Automation
|
||||
from baserow.contrib.automation.nodes.models import AutomationNode
|
||||
from baserow.contrib.automation.workflows.models import AutomationWorkflow
|
||||
from baserow.core.cache import local_cache
|
||||
from baserow.core.formula import resolve_formula
|
||||
from baserow.core.formula.registries import formula_runtime_function_registry
|
||||
from baserow.core.formula.validator import ensure_boolean
|
||||
from baserow.test_utils.fixtures import Fixtures
|
||||
from baserow_enterprise.assistant.evals.harness import tool_called
|
||||
from baserow_enterprise.assistant.evals.registry import (
|
||||
@@ -25,6 +31,7 @@ from baserow_enterprise.assistant.evals.types import (
|
||||
EvalRunOutput,
|
||||
EvalScenario,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.automation.agents import AssistantFormulaContext
|
||||
|
||||
# Names the automation instead of a live DB id, since prompts are fixed before creation.
|
||||
PROMPT_LISTS_WORKFLOWS = "List the workflows in automation '{automation_name}'."
|
||||
@@ -71,35 +78,117 @@ PROMPT_CREATES_EMAIL_NOTIFICATION_WORKFLOW = (
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Local helpers — args inspection over output.messages (assistant-side entries)
|
||||
# Local helpers — inspect saved configuration, including repaired tool calls.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _get_create_workflows_args(output: EvalRunOutput) -> list[dict]:
|
||||
"""Return the parsed ``args`` dicts of every ``create_workflows`` call."""
|
||||
def _check_saved_workflows(
|
||||
automation: Automation,
|
||||
output: EvalRunOutput,
|
||||
check: Callable[[AutomationNode | None, list[AutomationNode]], list[CheckResult]],
|
||||
) -> list[CheckResult]:
|
||||
"""Score one whole workflow, allowing an earlier incomplete draft to remain."""
|
||||
|
||||
candidates = []
|
||||
# Read graph relationships fresh after the agent's mutations.
|
||||
with local_cache.context():
|
||||
for workflow in AutomationWorkflow.objects.filter(automation=automation):
|
||||
trigger = workflow.get_trigger()
|
||||
actions = list(
|
||||
workflow.automation_workflow_nodes.exclude(
|
||||
id=trigger.id if trigger else None
|
||||
)
|
||||
)
|
||||
candidates.append(check(trigger, actions))
|
||||
# Keep useful partial-failure details, but never combine checks from different
|
||||
# workflows into a passing result.
|
||||
best = (
|
||||
max(candidates, key=lambda checks: sum(c.passed for c in checks))
|
||||
if candidates
|
||||
else check(None, [])
|
||||
)
|
||||
return [
|
||||
e["args"]
|
||||
for e in output.messages
|
||||
if e["role"] == "assistant"
|
||||
and e.get("tool_name") == "create_workflows"
|
||||
and "args" in e
|
||||
CheckResult(
|
||||
"called create_workflows", bool(tool_called(output, "create_workflows"))
|
||||
),
|
||||
CheckResult("workflow created in DB", bool(candidates)),
|
||||
*best,
|
||||
]
|
||||
|
||||
|
||||
def _get_workflow_nodes(
|
||||
automation: Automation,
|
||||
) -> tuple[AutomationWorkflow | None, AutomationNode | None, list[AutomationNode]]:
|
||||
"""Return (workflow, trigger, action_nodes) for the first workflow, or Nones."""
|
||||
_UNRESOLVED = object()
|
||||
|
||||
workflow = AutomationWorkflow.objects.filter(automation=automation).first()
|
||||
if workflow is None:
|
||||
return None, None, []
|
||||
trigger = workflow.get_trigger()
|
||||
action_nodes = list(
|
||||
workflow.automation_workflow_nodes.exclude(id=trigger.id).order_by("id")
|
||||
)
|
||||
return workflow, trigger, action_nodes
|
||||
|
||||
def _resolve_saved_formula(formula, trigger=None, row=None):
|
||||
context = AssistantFormulaContext()
|
||||
if trigger is not None and row is not None:
|
||||
context.add_node_context(trigger.id, [row])
|
||||
try:
|
||||
return resolve_formula(formula, formula_runtime_function_registry, context)
|
||||
except Exception:
|
||||
return _UNRESOLVED
|
||||
|
||||
|
||||
def _row_values_match(service, trigger, samples, *, update: bool) -> bool:
|
||||
"""Check row identity and named mappings against two different trigger rows."""
|
||||
|
||||
if trigger is None:
|
||||
return False
|
||||
mappings = {
|
||||
mapping.field_id: mapping.value
|
||||
for mapping in service.field_mappings.filter(enabled=True)
|
||||
}
|
||||
for row, expected in samples:
|
||||
row_id = _resolve_saved_formula(service.row_id, trigger, row)
|
||||
if row_id not in ((row["id"], str(row["id"])) if update else (None, "")):
|
||||
return False
|
||||
if any(
|
||||
field_id not in mappings
|
||||
or _resolve_saved_formula(mappings[field_id], trigger, row) != value
|
||||
for field_id, value in expected.items()
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _check_updates_trigger_row(scenario, output, trigger_type, values):
|
||||
table = scenario.refs["table"]
|
||||
expected = {
|
||||
table.field_set.get(name=name).id: value for name, value in values.items()
|
||||
}
|
||||
samples = [({"id": row_id}, expected) for row_id in (101, 202)]
|
||||
|
||||
def check(trigger, actions):
|
||||
service = trigger.service.specific if trigger else None
|
||||
updates = [
|
||||
node.service.specific
|
||||
for node in actions
|
||||
if node.get_type().type == "local_baserow_update_row"
|
||||
]
|
||||
targets = [service for service in updates if service.table_id == table.id]
|
||||
return [
|
||||
CheckResult(
|
||||
f"DB trigger is {trigger_type}",
|
||||
service is not None
|
||||
and service.get_type().type == f"local_baserow_{trigger_type}",
|
||||
),
|
||||
CheckResult(
|
||||
f"trigger table is {table.name}",
|
||||
service is not None and getattr(service, "table_id", None) == table.id,
|
||||
),
|
||||
CheckResult("update_row action in DB", bool(updates)),
|
||||
CheckResult(f"update_row targets {table.name} table", bool(targets)),
|
||||
CheckResult(
|
||||
"saved update targets the trigger row with the requested field values",
|
||||
any(
|
||||
_row_values_match(service, trigger, samples, update=True)
|
||||
for service in targets
|
||||
),
|
||||
hint=f"expected field values: {values}",
|
||||
),
|
||||
]
|
||||
|
||||
return _check_saved_workflows(scenario.refs["automation"], output, check)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -171,69 +260,10 @@ def _creates_workflow_scenario(fx: Fixtures) -> EvalScenario:
|
||||
def _check_creates_workflow(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
automation = scenario.refs["automation"]
|
||||
table = scenario.refs["table"]
|
||||
|
||||
workflows = AutomationWorkflow.objects.filter(automation=automation)
|
||||
|
||||
call_args_list = _get_create_workflows_args(output)
|
||||
args = call_args_list[0] if call_args_list else {}
|
||||
wf_args = args.get("workflows", [{}])[0] if args.get("workflows") else {}
|
||||
trigger_args = wf_args.get("trigger", {})
|
||||
nodes_args = wf_args.get("nodes", [])
|
||||
trigger_table_id = trigger_args.get("rows_triggers_settings", {}).get("table_id")
|
||||
update_nodes_args = [n for n in nodes_args if n.get("type") == "update_row"]
|
||||
ur_values = update_nodes_args[0].get("values", []) if update_nodes_args else []
|
||||
ur_has_processing = any(
|
||||
"processing" in str(v.get("value", "")).lower() for v in ur_values
|
||||
return _check_updates_trigger_row(
|
||||
scenario, output, "rows_created", {"Status": "Processing"}
|
||||
)
|
||||
|
||||
db_ok = workflows.exists()
|
||||
if db_ok:
|
||||
_, trigger_node, action_nodes = _get_workflow_nodes(automation)
|
||||
db_trigger_type = trigger_node.service.get_type().type
|
||||
db_update_actions = [
|
||||
n
|
||||
for n in action_nodes
|
||||
if n.service.get_type().type == "local_baserow_upsert_row"
|
||||
]
|
||||
else:
|
||||
db_trigger_type = None
|
||||
db_update_actions = []
|
||||
|
||||
return [
|
||||
CheckResult(
|
||||
"called create_workflows", tool_called(output, "create_workflows") >= 1
|
||||
),
|
||||
CheckResult("workflow created in DB", db_ok),
|
||||
CheckResult(
|
||||
"trigger is rows_created",
|
||||
trigger_args.get("type") == "rows_created",
|
||||
hint=f"got {trigger_args.get('type')}",
|
||||
),
|
||||
CheckResult(
|
||||
"trigger table is Orders",
|
||||
trigger_table_id == table.id,
|
||||
hint=f"got table_id={trigger_table_id}, expected={table.id}",
|
||||
),
|
||||
CheckResult(
|
||||
"update_row node in args",
|
||||
len(update_nodes_args) >= 1,
|
||||
hint=f"node types: {[n.get('type') for n in nodes_args]}",
|
||||
),
|
||||
CheckResult(
|
||||
"update_row sets field to 'Processing'",
|
||||
ur_has_processing,
|
||||
hint=f"values: {ur_values}",
|
||||
),
|
||||
CheckResult(
|
||||
"DB trigger is rows_created",
|
||||
db_trigger_type == "local_baserow_rows_created",
|
||||
hint=f"got {db_trigger_type}",
|
||||
),
|
||||
CheckResult("update_row action in DB", len(db_update_actions) >= 1),
|
||||
]
|
||||
|
||||
|
||||
register_case(
|
||||
EvalCase(
|
||||
@@ -272,74 +302,51 @@ def _creates_weekly_slack_reminder_scenario(fx: Fixtures) -> EvalScenario:
|
||||
def _check_creates_weekly_slack_reminder(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
automation = scenario.refs["automation"]
|
||||
|
||||
call_args_list = _get_create_workflows_args(output)
|
||||
args = call_args_list[0] if call_args_list else {}
|
||||
wf_args = args.get("workflows", [{}])[0] if args.get("workflows") else {}
|
||||
trigger_args = wf_args.get("trigger", {})
|
||||
interval_args = trigger_args.get("periodic_interval", {})
|
||||
nodes_args = wf_args.get("nodes", [])
|
||||
slack_nodes_args = [n for n in nodes_args if n.get("type") == "slack_write_message"]
|
||||
|
||||
db_ok = AutomationWorkflow.objects.filter(automation=automation).exists()
|
||||
if db_ok:
|
||||
# Deliberately trigger_node.get_type() here (not .service.get_type()),
|
||||
# unlike every other case in this dataset — ported as-is from the legacy test.
|
||||
_, trigger_node, action_nodes = _get_workflow_nodes(automation)
|
||||
db_trigger_type = trigger_node.get_type().type
|
||||
db_slack_actions = [
|
||||
n
|
||||
for n in action_nodes
|
||||
if n.service.get_type().type == "slack_write_message"
|
||||
def check(trigger, actions):
|
||||
periodic = (
|
||||
trigger.service.specific
|
||||
if trigger and trigger.get_type().type == "periodic"
|
||||
else None
|
||||
)
|
||||
slack = [
|
||||
node.service.specific
|
||||
for node in actions
|
||||
if node.service.get_type().type == "slack_write_message"
|
||||
]
|
||||
else:
|
||||
db_trigger_type = None
|
||||
db_slack_actions = []
|
||||
targets = [
|
||||
service for service in slack if service.channel.lstrip("#") == "general"
|
||||
]
|
||||
checks = [
|
||||
CheckResult("workflow created with periodic trigger", periodic is not None),
|
||||
CheckResult("Slack action exists in DB", bool(slack)),
|
||||
CheckResult("Slack channel is #general", bool(targets)),
|
||||
CheckResult(
|
||||
"Slack action sends the exact requested message to #general",
|
||||
any(
|
||||
_resolve_saved_formula(service.text)
|
||||
== "Is there anything to demo this week?"
|
||||
for service in targets
|
||||
),
|
||||
),
|
||||
]
|
||||
for name, expected in (
|
||||
("interval", "WEEK"),
|
||||
("day_of_week", 1),
|
||||
("hour", 9),
|
||||
("minute", 0),
|
||||
("timezone", "UTC"),
|
||||
):
|
||||
actual = getattr(periodic, name, None)
|
||||
checks.append(
|
||||
CheckResult(
|
||||
f"saved {name} is {expected}",
|
||||
actual == expected,
|
||||
hint=f"got {actual}",
|
||||
)
|
||||
)
|
||||
return checks
|
||||
|
||||
slack_node = slack_nodes_args[0] if slack_nodes_args else {}
|
||||
slack_channel = slack_node.get("channel", "")
|
||||
slack_text = slack_node.get("text", "")
|
||||
|
||||
return [
|
||||
CheckResult("called create_workflows", len(call_args_list) >= 1),
|
||||
CheckResult(
|
||||
"trigger type is periodic",
|
||||
trigger_args.get("type") == "periodic",
|
||||
hint=f"got {trigger_args.get('type')}",
|
||||
),
|
||||
CheckResult(
|
||||
"interval is WEEK",
|
||||
interval_args.get("interval") == "WEEK",
|
||||
hint=f"got {interval_args.get('interval')}",
|
||||
),
|
||||
CheckResult(
|
||||
"day_of_week is 1 (Tuesday)",
|
||||
interval_args.get("day_of_week") == 1,
|
||||
hint=f"got {interval_args.get('day_of_week')}",
|
||||
),
|
||||
CheckResult(
|
||||
"slack_write_message node in args",
|
||||
len(slack_nodes_args) >= 1,
|
||||
hint=f"node types: {[n.get('type') for n in nodes_args]}",
|
||||
),
|
||||
CheckResult(
|
||||
"workflow created in DB with periodic trigger",
|
||||
db_trigger_type == "periodic",
|
||||
hint=f"got {db_trigger_type}",
|
||||
),
|
||||
CheckResult("Slack action exists in DB", len(db_slack_actions) >= 1),
|
||||
CheckResult(
|
||||
"Slack channel is #general",
|
||||
"general" in slack_channel.lower(),
|
||||
hint=f"got channel: '{slack_channel}'",
|
||||
),
|
||||
CheckResult(
|
||||
"Slack message mentions demo",
|
||||
"demo" in slack_text.lower(),
|
||||
hint=f"got text: '{slack_text}'",
|
||||
),
|
||||
]
|
||||
return _check_saved_workflows(scenario.refs["automation"], output, check)
|
||||
|
||||
|
||||
register_case(
|
||||
@@ -384,81 +391,67 @@ def _creates_router_workflow_scenario(fx: Fixtures) -> EvalScenario:
|
||||
def _check_creates_router_workflow(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
automation = scenario.refs["automation"]
|
||||
table = scenario.refs["table"]
|
||||
priority = table.field_set.get(name="Priority")
|
||||
options = {
|
||||
option.value: {"id": option.id, "value": option.value, "color": option.color}
|
||||
for option in priority.select_options.all()
|
||||
}
|
||||
|
||||
call_args_list = _get_create_workflows_args(output)
|
||||
args = call_args_list[0] if call_args_list else {}
|
||||
wf_args = args.get("workflows", [{}])[0] if args.get("workflows") else {}
|
||||
nodes_args = wf_args.get("nodes", [])
|
||||
router_nodes_args = [n for n in nodes_args if n.get("type") == "router"]
|
||||
router_edges_args = (
|
||||
router_nodes_args[0].get("edges", []) if router_nodes_args else []
|
||||
)
|
||||
|
||||
db_ok = AutomationWorkflow.objects.filter(automation=automation).exists()
|
||||
if db_ok:
|
||||
_, trigger_node, action_nodes = _get_workflow_nodes(automation)
|
||||
db_router_actions = [
|
||||
n for n in action_nodes if n.service.get_type().type == "router"
|
||||
]
|
||||
db_edges_count = (
|
||||
db_router_actions[0].service.specific.edges.count()
|
||||
if db_router_actions
|
||||
else 0
|
||||
def branches_match(router, trigger):
|
||||
if trigger is None:
|
||||
return False
|
||||
edges = list(router.service.specific.edges.all())
|
||||
selected = {}
|
||||
for value in ("High", "Low"):
|
||||
row = {priority.db_column: options[value]}
|
||||
# Runtime resolves every condition before choosing the first match.
|
||||
resolved = [
|
||||
_resolve_saved_formula(edge.condition, trigger, row) for edge in edges
|
||||
]
|
||||
if any(result is _UNRESOLVED for result in resolved):
|
||||
return False
|
||||
selected[value] = next(
|
||||
(
|
||||
str(edge.uid)
|
||||
for edge, result in zip(edges, resolved)
|
||||
if ensure_boolean(result, False)
|
||||
),
|
||||
"",
|
||||
)
|
||||
if selected["High"] == selected["Low"]:
|
||||
return False
|
||||
high_nodes = router.get_next_points(selected["High"])
|
||||
low_nodes = router.get_next_points(selected["Low"])
|
||||
return not low_nodes and any(
|
||||
node.service.get_type().type == "slack_write_message"
|
||||
and node.service.specific.channel.lstrip("#") == "urgent"
|
||||
and _resolve_saved_formula(node.service.specific.text)
|
||||
== "High priority ticket created"
|
||||
for node in high_nodes
|
||||
)
|
||||
else:
|
||||
db_router_actions = []
|
||||
db_edges_count = 0
|
||||
|
||||
trigger_args = wf_args.get("trigger", {})
|
||||
trigger_table_id = trigger_args.get("rows_triggers_settings", {}).get("table_id")
|
||||
slack_nodes_in_nodes = [
|
||||
n for n in nodes_args if n.get("type") == "slack_write_message"
|
||||
]
|
||||
slack_channel = (
|
||||
slack_nodes_in_nodes[0].get("channel", "") if slack_nodes_in_nodes else ""
|
||||
)
|
||||
def check(trigger, actions):
|
||||
service = trigger.service.specific if trigger else None
|
||||
routers = [node for node in actions if node.service.get_type().type == "router"]
|
||||
return [
|
||||
CheckResult(
|
||||
"trigger is rows_created",
|
||||
service is not None
|
||||
and service.get_type().type == "local_baserow_rows_created",
|
||||
),
|
||||
CheckResult(
|
||||
"trigger table is Tickets",
|
||||
service is not None and getattr(service, "table_id", None) == table.id,
|
||||
),
|
||||
CheckResult("router node in DB", bool(routers)),
|
||||
CheckResult(
|
||||
"saved High branch sends the requested Slack message; Low does nothing",
|
||||
any(branches_match(router, trigger) for router in routers),
|
||||
),
|
||||
]
|
||||
|
||||
return [
|
||||
CheckResult("called create_workflows", len(call_args_list) >= 1),
|
||||
CheckResult(
|
||||
"trigger is rows_created",
|
||||
trigger_args.get("type") == "rows_created",
|
||||
hint=f"got {trigger_args.get('type')}",
|
||||
),
|
||||
CheckResult(
|
||||
"trigger table is Tickets",
|
||||
trigger_table_id == table.id,
|
||||
hint=f"got table_id={trigger_table_id}, expected={table.id}",
|
||||
),
|
||||
CheckResult(
|
||||
"router node in args",
|
||||
len(router_nodes_args) >= 1,
|
||||
hint=f"node types: {[n.get('type') for n in nodes_args]}",
|
||||
),
|
||||
CheckResult(
|
||||
"router has >=2 edges in args",
|
||||
len(router_edges_args) >= 2,
|
||||
hint=f"got {len(router_edges_args)}",
|
||||
),
|
||||
CheckResult("router node in DB", len(db_router_actions) >= 1),
|
||||
CheckResult(
|
||||
"router has >=2 edges in DB",
|
||||
db_edges_count >= 2,
|
||||
hint=f"got {db_edges_count}",
|
||||
),
|
||||
CheckResult(
|
||||
"Slack node exists for High branch",
|
||||
len(slack_nodes_in_nodes) >= 1,
|
||||
hint=f"node types: {[n.get('type') for n in nodes_args]}",
|
||||
),
|
||||
CheckResult(
|
||||
"Slack channel is #urgent",
|
||||
"urgent" in slack_channel.lower(),
|
||||
hint=f"got channel: '{slack_channel}'",
|
||||
),
|
||||
]
|
||||
return _check_saved_workflows(scenario.refs["automation"], output, check)
|
||||
|
||||
|
||||
register_case(
|
||||
@@ -508,80 +501,51 @@ def _creates_row_with_field_values_scenario(fx: Fixtures) -> EvalScenario:
|
||||
def _check_creates_row_with_field_values(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
automation = scenario.refs["automation"]
|
||||
source_table = scenario.refs["source_table"]
|
||||
log_table = scenario.refs["log_table"]
|
||||
|
||||
call_args_list = _get_create_workflows_args(output)
|
||||
args = call_args_list[0] if call_args_list else {}
|
||||
wf_args = args.get("workflows", [{}])[0] if args.get("workflows") else {}
|
||||
trigger_args = wf_args.get("trigger", {})
|
||||
nodes_args = wf_args.get("nodes", [])
|
||||
create_row_nodes_args = [n for n in nodes_args if n.get("type") == "create_row"]
|
||||
cr_values = (
|
||||
create_row_nodes_args[0].get("values", []) if create_row_nodes_args else []
|
||||
)
|
||||
|
||||
db_ok = AutomationWorkflow.objects.filter(automation=automation).exists()
|
||||
if db_ok:
|
||||
_, trigger_node, action_nodes = _get_workflow_nodes(automation)
|
||||
db_trigger_type = trigger_node.service.get_type().type
|
||||
db_create_actions = [
|
||||
n
|
||||
for n in action_nodes
|
||||
if n.service.get_type().type == "local_baserow_upsert_row"
|
||||
]
|
||||
else:
|
||||
db_trigger_type = None
|
||||
db_create_actions = []
|
||||
|
||||
trigger_table_id = trigger_args.get("rows_triggers_settings", {}).get("table_id")
|
||||
cr_node = create_row_nodes_args[0] if create_row_nodes_args else {}
|
||||
cr_table_id = cr_node.get("table_id")
|
||||
cr_has_literal_automation = any(
|
||||
"automation" in str(v.get("value", "")).lower() for v in cr_values
|
||||
)
|
||||
|
||||
return [
|
||||
CheckResult("called create_workflows", len(call_args_list) >= 1),
|
||||
CheckResult(
|
||||
"trigger is rows_created",
|
||||
trigger_args.get("type") == "rows_created",
|
||||
hint=f"got {trigger_args.get('type')}",
|
||||
),
|
||||
CheckResult(
|
||||
"trigger table is Contacts (source_table)",
|
||||
trigger_table_id == source_table.id,
|
||||
hint=f"got table_id={trigger_table_id}, expected={source_table.id}",
|
||||
),
|
||||
CheckResult(
|
||||
"create_row node in args",
|
||||
len(create_row_nodes_args) >= 1,
|
||||
hint=f"node types: {[n.get('type') for n in nodes_args]}",
|
||||
),
|
||||
CheckResult(
|
||||
"create_row targets Log table",
|
||||
cr_table_id == log_table.id,
|
||||
hint=f"got table_id={cr_table_id}, expected={log_table.id}",
|
||||
),
|
||||
CheckResult(
|
||||
"create_row has >=1 field value",
|
||||
len(cr_values) >= 1,
|
||||
hint=f"got {len(cr_values)}",
|
||||
),
|
||||
CheckResult(
|
||||
"create_row has 'automation' literal value (Source field)",
|
||||
cr_has_literal_automation,
|
||||
hint=f"values: {cr_values}",
|
||||
),
|
||||
CheckResult(
|
||||
"DB trigger is rows_created",
|
||||
db_trigger_type == "local_baserow_rows_created",
|
||||
hint=f"got {db_trigger_type}",
|
||||
),
|
||||
CheckResult("create_row action in DB", len(db_create_actions) >= 1),
|
||||
name_field = source_table.field_set.get(name="Name")
|
||||
entry_field = log_table.field_set.get(name="Entry")
|
||||
source_field = log_table.field_set.get(name="Source")
|
||||
samples = [
|
||||
(
|
||||
{"id": row_id, name_field.db_column: name},
|
||||
{entry_field.id: name, source_field.id: "automation"},
|
||||
)
|
||||
for row_id, name in ((101, "Ada Lovelace"), (202, "Grace Hopper"))
|
||||
]
|
||||
|
||||
def check(trigger, actions):
|
||||
service = trigger.service.specific if trigger else None
|
||||
creates = [
|
||||
node.service.specific
|
||||
for node in actions
|
||||
if node.get_type().type == "local_baserow_create_row"
|
||||
]
|
||||
targets = [service for service in creates if service.table_id == log_table.id]
|
||||
return [
|
||||
CheckResult(
|
||||
"DB trigger is rows_created",
|
||||
service is not None
|
||||
and service.get_type().type == "local_baserow_rows_created",
|
||||
),
|
||||
CheckResult(
|
||||
"DB trigger table is Contacts",
|
||||
service is not None
|
||||
and getattr(service, "table_id", None) == source_table.id,
|
||||
),
|
||||
CheckResult("create_row action in DB", bool(creates)),
|
||||
CheckResult("create_row targets Log table", bool(targets)),
|
||||
CheckResult(
|
||||
"saved Entry follows trigger Name and Source is automation",
|
||||
any(
|
||||
_row_values_match(service, trigger, samples, update=False)
|
||||
for service in targets
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
return _check_saved_workflows(scenario.refs["automation"], output, check)
|
||||
|
||||
|
||||
register_case(
|
||||
EvalCase(
|
||||
@@ -627,77 +591,12 @@ def _creates_update_row_workflow_scenario(fx: Fixtures) -> EvalScenario:
|
||||
def _check_creates_update_row_workflow(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
automation = scenario.refs["automation"]
|
||||
table = scenario.refs["table"]
|
||||
|
||||
call_args_list = _get_create_workflows_args(output)
|
||||
args = call_args_list[0] if call_args_list else {}
|
||||
wf_args = args.get("workflows", [{}])[0] if args.get("workflows") else {}
|
||||
trigger_args = wf_args.get("trigger", {})
|
||||
nodes_args = wf_args.get("nodes", [])
|
||||
update_nodes_args = [n for n in nodes_args if n.get("type") == "update_row"]
|
||||
ur = update_nodes_args[0] if update_nodes_args else {}
|
||||
|
||||
db_ok = AutomationWorkflow.objects.filter(automation=automation).exists()
|
||||
if db_ok:
|
||||
_, trigger_node, action_nodes = _get_workflow_nodes(automation)
|
||||
db_trigger_type = trigger_node.service.get_type().type
|
||||
db_update_actions = [
|
||||
n
|
||||
for n in action_nodes
|
||||
if n.service.get_type().type == "local_baserow_upsert_row"
|
||||
]
|
||||
else:
|
||||
db_trigger_type = None
|
||||
db_update_actions = []
|
||||
|
||||
ur_values = ur.get("values", [])
|
||||
ur_has_reviewed = any(
|
||||
"reviewed" in str(v.get("value", "")).lower() for v in ur_values
|
||||
return _check_updates_trigger_row(
|
||||
scenario,
|
||||
output,
|
||||
"rows_updated",
|
||||
{"Status": "Reviewed", "Notes": "Automatically reviewed by automation"},
|
||||
)
|
||||
ur_has_notes = any(
|
||||
"automation" in str(v.get("value", "")).lower()
|
||||
or "review" in str(v.get("value", "")).lower()
|
||||
for v in ur_values
|
||||
)
|
||||
trigger_table_id = trigger_args.get("rows_triggers_settings", {}).get("table_id")
|
||||
|
||||
return [
|
||||
CheckResult("called create_workflows", len(call_args_list) >= 1),
|
||||
CheckResult(
|
||||
"trigger is rows_updated",
|
||||
trigger_args.get("type") == "rows_updated",
|
||||
hint=f"got {trigger_args.get('type')}",
|
||||
),
|
||||
CheckResult(
|
||||
"trigger table is Tasks",
|
||||
trigger_table_id == table.id,
|
||||
hint=f"got table_id={trigger_table_id}, expected={table.id}",
|
||||
),
|
||||
CheckResult(
|
||||
"update_row node in args",
|
||||
len(update_nodes_args) >= 1,
|
||||
hint=f"node types: {[n.get('type') for n in nodes_args]}",
|
||||
),
|
||||
CheckResult("update_row has >=1 field value", len(ur_values) >= 1),
|
||||
CheckResult("update_row has row_id", bool(ur.get("row_id"))),
|
||||
CheckResult(
|
||||
"update_row sets Status to 'Reviewed'",
|
||||
ur_has_reviewed,
|
||||
hint=f"values: {ur_values}",
|
||||
),
|
||||
CheckResult(
|
||||
"update_row sets Notes (automation/reviewed text)",
|
||||
ur_has_notes,
|
||||
hint=f"values: {ur_values}",
|
||||
),
|
||||
CheckResult(
|
||||
"DB trigger is rows_updated",
|
||||
db_trigger_type == "local_baserow_rows_updated",
|
||||
hint=f"got {db_trigger_type}",
|
||||
),
|
||||
CheckResult("update_row action in DB", len(db_update_actions) >= 1),
|
||||
]
|
||||
|
||||
|
||||
register_case(
|
||||
@@ -740,65 +639,39 @@ def _creates_email_notification_workflow_scenario(fx: Fixtures) -> EvalScenario:
|
||||
def _check_creates_email_notification_workflow(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
automation = scenario.refs["automation"]
|
||||
table = scenario.refs["table"]
|
||||
|
||||
call_args_list = _get_create_workflows_args(output)
|
||||
args = call_args_list[0] if call_args_list else {}
|
||||
wf_args = args.get("workflows", [{}])[0] if args.get("workflows") else {}
|
||||
trigger_args = wf_args.get("trigger", {})
|
||||
trigger_table_id = trigger_args.get("rows_triggers_settings", {}).get("table_id")
|
||||
nodes_args = wf_args.get("nodes", [])
|
||||
email_nodes_args = [n for n in nodes_args if n.get("type") == "smtp_email"]
|
||||
email_node = email_nodes_args[0] if email_nodes_args else {}
|
||||
email_to = email_node.get("to_emails", "")
|
||||
email_subject = email_node.get("subject", "")
|
||||
email_body = email_node.get("body", "")
|
||||
|
||||
db_ok = AutomationWorkflow.objects.filter(automation=automation).exists()
|
||||
if db_ok:
|
||||
_, trigger_node, action_nodes = _get_workflow_nodes(automation)
|
||||
db_email_actions = [
|
||||
n for n in action_nodes if n.service.get_type().type == "smtp_email"
|
||||
def check(trigger, actions):
|
||||
service = trigger.service.specific if trigger else None
|
||||
emails = [
|
||||
node.service.specific
|
||||
for node in actions
|
||||
if node.service.get_type().type == "smtp_email"
|
||||
]
|
||||
return [
|
||||
CheckResult(
|
||||
"trigger is rows_created",
|
||||
service is not None
|
||||
and service.get_type().type == "local_baserow_rows_created",
|
||||
),
|
||||
CheckResult(
|
||||
"trigger table is Orders",
|
||||
service is not None and getattr(service, "table_id", None) == table.id,
|
||||
),
|
||||
CheckResult("smtp_email action in DB", bool(emails)),
|
||||
CheckResult(
|
||||
"saved email has the requested recipient, subject and body",
|
||||
any(
|
||||
_resolve_saved_formula(email.to_emails) == "admin@example.com"
|
||||
and _resolve_saved_formula(email.subject) == "New Order"
|
||||
and _resolve_saved_formula(email.body)
|
||||
== "A new order has been placed"
|
||||
for email in emails
|
||||
),
|
||||
),
|
||||
]
|
||||
else:
|
||||
db_email_actions = []
|
||||
|
||||
return [
|
||||
CheckResult("called create_workflows", len(call_args_list) >= 1),
|
||||
CheckResult(
|
||||
"trigger is rows_created",
|
||||
trigger_args.get("type") == "rows_created",
|
||||
hint=f"got {trigger_args.get('type')}",
|
||||
),
|
||||
CheckResult(
|
||||
"trigger table is Orders",
|
||||
trigger_table_id == table.id,
|
||||
hint=f"got table_id={trigger_table_id}, expected={table.id}",
|
||||
),
|
||||
CheckResult(
|
||||
"smtp_email node in args",
|
||||
len(email_nodes_args) >= 1,
|
||||
hint=f"node types: {[n.get('type') for n in nodes_args]}",
|
||||
),
|
||||
CheckResult(
|
||||
"email to admin@example.com",
|
||||
"admin@example.com" in email_to,
|
||||
hint=f"got to: '{email_to}'",
|
||||
),
|
||||
CheckResult(
|
||||
"email subject mentions 'Order'",
|
||||
"order" in email_subject.lower(),
|
||||
hint=f"got subject: '{email_subject}'",
|
||||
),
|
||||
CheckResult(
|
||||
"email body mentions order being placed",
|
||||
"order" in email_body.lower() or "placed" in email_body.lower(),
|
||||
hint=f"got body: '{email_body}'",
|
||||
),
|
||||
CheckResult("workflow created in DB", db_ok),
|
||||
CheckResult("smtp_email action in DB", len(db_email_actions) >= 1),
|
||||
]
|
||||
return _check_saved_workflows(scenario.refs["automation"], output, check)
|
||||
|
||||
|
||||
register_case(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,6 +7,8 @@ keywords) triple varies per case.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from baserow.test_utils.fixtures import Fixtures
|
||||
from baserow_enterprise.assistant.evals.harness import tool_called
|
||||
from baserow_enterprise.assistant.evals.registry import (
|
||||
@@ -35,14 +37,26 @@ def _docs_question_scenario(fx: Fixtures) -> EvalScenario:
|
||||
)
|
||||
|
||||
|
||||
def _normalize_keyword_text(text: str) -> str:
|
||||
"""Compare wording independently of spacing and equivalent typography."""
|
||||
|
||||
text = text.casefold().replace("\u2018", "'").replace("\u2019", "'")
|
||||
text = text.replace("\u2010", "-").replace("\u2011", "-")
|
||||
text = re.sub(r"[*_`]+", "", text)
|
||||
return " ".join(text.split())
|
||||
|
||||
|
||||
def _make_docs_checks(
|
||||
expected_source_patterns: list[str], expected_keywords: list[str]
|
||||
) -> CheckSuite:
|
||||
def _checks(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
answer = output.answer.lower()
|
||||
keyword_match = any(kw.lower() in answer for kw in expected_keywords)
|
||||
# Typography is equivalent; values, wording and negation still matter.
|
||||
answer = _normalize_keyword_text(output.answer)
|
||||
keyword_match = any(
|
||||
_normalize_keyword_text(keyword) in answer for keyword in expected_keywords
|
||||
)
|
||||
|
||||
# Source-URL matching is non-fatal — URLs change and retrieval may
|
||||
# return valid alternative sources — so this always passes; a
|
||||
@@ -150,12 +164,14 @@ _register_docs_case(
|
||||
"but it says 'Invalid Syntax'. What am I doing wrong?"
|
||||
),
|
||||
["formula", "understanding-formulas"],
|
||||
["date_diff", "date diff", "datediff"],
|
||||
# Subtracting the dates is also correct: it returns a duration, not a number.
|
||||
["date_diff", "date diff", "datediff", "subtract"],
|
||||
reference_answer=(
|
||||
"Baserow formulas don't start with '=' and there is no DAYS() "
|
||||
"function — use date_diff with the unit as the first argument: "
|
||||
"date_diff('day', field('Start'), field('End')). Other units include "
|
||||
"'hour', 'week', 'month', and 'year'."
|
||||
"'hour', 'week', 'month', and 'year'. Subtracting the dates, "
|
||||
"field('End') - field('Start'), returns the difference as a duration."
|
||||
),
|
||||
)
|
||||
|
||||
@@ -1056,7 +1072,7 @@ _register_docs_case(
|
||||
"full of scanned invoices and I want to pull the text out of them."
|
||||
),
|
||||
["ai-field", "file-field"],
|
||||
["ai field", "file field"],
|
||||
["ai field", "ai prompt", "file field"],
|
||||
reference_answer=(
|
||||
"Yes, via the AI field (a paid feature): point it at your file "
|
||||
"field and it can read the attachments — including images and PDFs "
|
||||
@@ -1090,7 +1106,7 @@ _register_docs_case(
|
||||
"suggests addresses while I type?"
|
||||
),
|
||||
["single-line-text-field"],
|
||||
["doesn't", "text field"],
|
||||
["doesn't", "does not", "text field"],
|
||||
reference_answer=(
|
||||
"Baserow doesn't have an address field type or any address "
|
||||
"autocomplete. Store addresses in a single line text field, or "
|
||||
@@ -1139,7 +1155,7 @@ _register_docs_case(
|
||||
"views of a table, so resizing once applies everywhere?"
|
||||
),
|
||||
["guide-to-grid-view"],
|
||||
["doesn't", "each view", "duplicat"],
|
||||
["doesn't", "each view", "duplicat", "per view", "per-view"],
|
||||
reference_answer=(
|
||||
"Baserow doesn't have a way to sync column widths across views — "
|
||||
"width is saved per view, so each view keeps its own. The closest "
|
||||
|
||||
@@ -0,0 +1,723 @@
|
||||
"""Kuma-prod-replay eval dataset: regression prompts for turn-ending failures.
|
||||
|
||||
Every prompt is an invented request that exercises a failure class which used
|
||||
to end the turn with an unhandled exception. Each scenario seeds the minimal
|
||||
workspace the prompt assumes and the checks assert the property that changed:
|
||||
the turn completes and recovers instead of dying with the class's exception.
|
||||
|
||||
Failure classes:
|
||||
|
||||
- ``'XElement' object has no attribute 'order'`` from page inspection.
|
||||
- Wrong/invented ids and view config errors ending the turn.
|
||||
- Formula compiler errors / tool retry budgets exhausting the turn.
|
||||
- ``Tool name conflicts with existing tool: 'create_rows_in_table_N'``.
|
||||
- Row value validation (decimal/date/number got ``''``) ending the turn.
|
||||
- ``Exceeded maximum output retries (1)`` from the formula agent.
|
||||
|
||||
Containment turns these recoverable failures into retry prompts by design, so
|
||||
each case carries an explicit ``max_tool_errors`` budget instead of the
|
||||
default 0.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from baserow.contrib.database.fields.models import FormulaField, LinkRowField
|
||||
from baserow.contrib.database.models import Table
|
||||
from baserow.contrib.database.rows.handler import RowHandler
|
||||
from baserow.contrib.database.views.models import (
|
||||
FormView,
|
||||
FormViewFieldOptions,
|
||||
View,
|
||||
)
|
||||
from baserow.test_utils.fixtures import Fixtures
|
||||
from baserow_enterprise.assistant.deps import AgentMode
|
||||
from baserow_enterprise.assistant.evals.harness import executed_tool_calls
|
||||
from baserow_enterprise.assistant.evals.registry import (
|
||||
register_case,
|
||||
register_scenario,
|
||||
)
|
||||
from baserow_enterprise.assistant.evals.scenarios import (
|
||||
build_builder_ui_context,
|
||||
build_database_ui_context,
|
||||
)
|
||||
from baserow_enterprise.assistant.evals.types import (
|
||||
CheckResult,
|
||||
EvalCase,
|
||||
EvalRunOutput,
|
||||
EvalScenario,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prompts — invented requests, one per failure class
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# view_config class: a form view over a table with a formula field.
|
||||
PROMPT_FORM_FOR_TABLE = "Add a form view so customers can submit new orders."
|
||||
|
||||
# element_order class: any page inspection died in list_elements.
|
||||
PROMPT_PAGE_LAYOUT_CHECK = (
|
||||
"The button on this page looks out of place. Can you check the layout?"
|
||||
)
|
||||
|
||||
# row_tool_conflict class: onboarding path reloads row tools.
|
||||
PROMPT_PROJECT_TRACKER = (
|
||||
"Create a database including tables, fields, example rows, and example "
|
||||
"views matching this description: A project tracker with Projects, "
|
||||
"Milestones, Owners, and Deadlines."
|
||||
)
|
||||
|
||||
# formula_agent_retries class: one validator rejection exhausted the budget.
|
||||
PROMPT_ISO_WEEK_FORMULA = (
|
||||
"Add a formula field named Week that returns the ISO week number of the "
|
||||
"{Shipped On} date."
|
||||
)
|
||||
|
||||
# formula_agent_retries class: a request the formula language cannot express.
|
||||
PROMPT_IMPOSSIBLE_FORMULA = (
|
||||
"Write a formula that downloads the PDF at the {Brochure Link} URL and "
|
||||
"counts its pages."
|
||||
)
|
||||
|
||||
# row_validation class: typed fields got '' and the turn died.
|
||||
PROMPT_SAMPLE_EMPLOYEE_ROWS = (
|
||||
"Generate 30 sample employees with:\n\n"
|
||||
"Full Name\nTeam\nPhone\nLevel (1,2,3)\nStart Date\n"
|
||||
"Notes\nPerformance Score"
|
||||
)
|
||||
|
||||
# formula_compiler class.
|
||||
PROMPT_SIGNED_AMOUNT_FORMULA = (
|
||||
'In the "Transactions" table, add a formula field called '
|
||||
'"Signed Amount" that turns each transaction into a signed number: '
|
||||
'"Credit" transactions count as positive Amount and "Debit" transactions '
|
||||
"as negative Amount."
|
||||
)
|
||||
|
||||
|
||||
REQUESTED_TRACKER_TABLES = ("Projects", "Milestones")
|
||||
SHIPMENT_ISO_WEEKS = {"2026-01-01": 1, "2026-06-15": 25, "2027-01-01": 53}
|
||||
REQUESTED_EMPLOYEE_COUNT = 30
|
||||
REQUIRED_EMPLOYEE_FIELDS = (
|
||||
"Full Name",
|
||||
"Team",
|
||||
"Phone",
|
||||
"Level",
|
||||
"Start Date",
|
||||
"Notes",
|
||||
"Performance Score",
|
||||
)
|
||||
SIGNED_TRANSACTIONS = (
|
||||
("T-1", "Credit", 100),
|
||||
("T-2", "Debit", 40),
|
||||
("T-3", "Credit", 7),
|
||||
)
|
||||
|
||||
|
||||
def _messages_text(output: EvalRunOutput) -> str:
|
||||
"""Full formatted history as one string, for leaked-error substring checks."""
|
||||
|
||||
return str(output.messages)
|
||||
|
||||
|
||||
def _as_number(value: Any) -> Decimal | None:
|
||||
"""Parse a saved formula value, which may be text such as ``"01"``."""
|
||||
|
||||
try:
|
||||
return Decimal(str(value).strip())
|
||||
except (InvalidOperation, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _numeric_values_by_primary(
|
||||
table: Table, field: FormulaField
|
||||
) -> dict[str, Decimal | None]:
|
||||
"""Map every row's primary value to the field's saved numeric value."""
|
||||
|
||||
primary = table.field_set.get(primary=True)
|
||||
return {
|
||||
str(getattr(row, primary.db_column)): _as_number(getattr(row, field.db_column))
|
||||
for row in table.get_model().objects.all()
|
||||
}
|
||||
|
||||
|
||||
def _preferred_formula_field(table: Table, name_hint: str) -> FormulaField | None:
|
||||
"""The valid formula field whose name mentions *name_hint*, else any valid one."""
|
||||
|
||||
valid = [f for f in FormulaField.objects.filter(table=table) if not f.error]
|
||||
named = [f for f in valid if name_hint in f.name.lower()]
|
||||
return (named or valid or [None])[0]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Form for a table with a formula field
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@register_scenario("prod-replay-form-for-table-with-formula-field")
|
||||
def _form_for_table_with_formula_field_scenario(fx: Fixtures) -> EvalScenario:
|
||||
"""Orders table whose formula field broke form-view creation."""
|
||||
|
||||
user = fx.create_user()
|
||||
workspace = fx.create_workspace(user=user)
|
||||
database = fx.create_database_application(workspace=workspace, name="Orders DB")
|
||||
table = fx.create_database_table(database=database, name="Orders")
|
||||
customer = fx.create_text_field(table=table, name="Customer", primary=True)
|
||||
price = fx.create_number_field(table=table, name="Price")
|
||||
fx.create_formula_field(
|
||||
table=table, name="Price incl. VAT", formula=f"field('{price.name}') * 1.21"
|
||||
)
|
||||
return EvalScenario(
|
||||
user=user,
|
||||
workspace=workspace,
|
||||
ui_context=build_database_ui_context(user, workspace, database, table),
|
||||
refs={"table": table, "order_field_ids": {customer.id, price.id}},
|
||||
)
|
||||
|
||||
|
||||
def _check_form_for_table_with_formula_field(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
"""Regression: 'The field type formula is not compatible with the form view.'"""
|
||||
|
||||
table = scenario.refs["table"]
|
||||
views = View.objects.filter(table=table)
|
||||
form_views = list(FormView.objects.filter(table=table))
|
||||
order_field_ids = scenario.refs["order_field_ids"]
|
||||
active_field_ids = set(
|
||||
table.field_set.filter(id__in=order_field_ids).values_list("id", flat=True)
|
||||
)
|
||||
enabled_by_form = {
|
||||
form.id: set(
|
||||
FormViewFieldOptions.objects.filter(
|
||||
form_view=form, enabled=True
|
||||
).values_list("field_id", flat=True)
|
||||
)
|
||||
for form in form_views
|
||||
}
|
||||
return [
|
||||
CheckResult(
|
||||
"form view created",
|
||||
bool(form_views),
|
||||
hint=f"views: {[v.content_type.model for v in views]}",
|
||||
),
|
||||
CheckResult(
|
||||
"form collects Customer and Price",
|
||||
order_field_ids <= active_field_ids
|
||||
and any(order_field_ids <= enabled for enabled in enabled_by_form.values()),
|
||||
hint=f"enabled field ids per form: {enabled_by_form}",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
register_case(
|
||||
EvalCase(
|
||||
id="prod-replay/form-for-table-with-formula-field",
|
||||
dataset="kuma-prod-replay",
|
||||
prompt=PROMPT_FORM_FOR_TABLE,
|
||||
scenario="prod-replay-form-for-table-with-formula-field",
|
||||
checks=_check_form_for_table_with_formula_field,
|
||||
max_iters=15,
|
||||
max_tool_errors=2,
|
||||
metadata={"failure_class": "view_config"},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Page inspection over existing builder elements
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@register_scenario("prod-replay-page-inspection-existing-elements")
|
||||
def _page_inspection_existing_elements_scenario(fx: Fixtures) -> EvalScenario:
|
||||
"""Builder page with existing elements that ``list_elements`` choked on."""
|
||||
|
||||
user = fx.create_user()
|
||||
workspace = fx.create_workspace(user=user)
|
||||
builder = fx.create_builder_application(
|
||||
user=user, workspace=workspace, name="Task App"
|
||||
)
|
||||
page = fx.create_builder_page(builder=builder, name="Tasks", path="/")
|
||||
fx.create_builder_heading_element(page=page, value="'Tasks'")
|
||||
fx.create_builder_text_element(page=page)
|
||||
fx.create_builder_button_element(page=page)
|
||||
return EvalScenario(
|
||||
user=user,
|
||||
workspace=workspace,
|
||||
ui_context=build_builder_ui_context(user, workspace, builder),
|
||||
)
|
||||
|
||||
|
||||
def _check_page_inspection_existing_elements(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
"""Regression: any page inspection died with `'XElement' has no attribute 'order'`."""
|
||||
|
||||
return [
|
||||
CheckResult(
|
||||
"page elements inspected",
|
||||
bool(executed_tool_calls(output, "list_elements")),
|
||||
hint=f"tools called: {output.tool_calls}",
|
||||
),
|
||||
CheckResult(
|
||||
"no attribute error leaked",
|
||||
"has no attribute" not in _messages_text(output),
|
||||
hint=f"tools called: {output.tool_calls}",
|
||||
),
|
||||
CheckResult(
|
||||
"turn ended with a real answer",
|
||||
bool(output.answer.strip()),
|
||||
hint=f"answer: {output.answer[:200]!r}",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
register_case(
|
||||
EvalCase(
|
||||
id="prod-replay/page-inspection-existing-elements",
|
||||
dataset="kuma-prod-replay",
|
||||
prompt=PROMPT_PAGE_LAYOUT_CHECK,
|
||||
scenario="prod-replay-page-inspection-existing-elements",
|
||||
checks=_check_page_inspection_existing_elements,
|
||||
mode=AgentMode.APPLICATION,
|
||||
max_iters=15,
|
||||
max_tool_errors=2,
|
||||
metadata={"failure_class": "element_order"},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Project tracker onboarding
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@register_scenario("prod-replay-project-tracker-onboarding")
|
||||
def _project_tracker_onboarding_scenario(fx: Fixtures) -> EvalScenario:
|
||||
"""Empty Project Tracker database, as the onboarding flow creates it."""
|
||||
|
||||
user = fx.create_user()
|
||||
workspace = fx.create_workspace(user=user)
|
||||
database = fx.create_database_application(
|
||||
workspace=workspace, name="Project Tracker"
|
||||
)
|
||||
return EvalScenario(
|
||||
user=user,
|
||||
workspace=workspace,
|
||||
ui_context=build_database_ui_context(user, workspace, database),
|
||||
refs={"database": database},
|
||||
)
|
||||
|
||||
|
||||
def _check_project_tracker_onboarding(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
"""Regression: 'Tool name conflicts with existing tool: create_rows_in_table_N'."""
|
||||
|
||||
database = scenario.refs["database"]
|
||||
tables = list(Table.objects.filter(database=database).prefetch_related("field_set"))
|
||||
rows_by_table = {table.name: table.get_model().objects.count() for table in tables}
|
||||
singular_names = {
|
||||
name.strip().casefold().removesuffix("s") for name in rows_by_table
|
||||
}
|
||||
requested_names = {
|
||||
name.casefold().removesuffix("s") for name in REQUESTED_TRACKER_TABLES
|
||||
}
|
||||
tracker_ids = {
|
||||
table.id
|
||||
for table in tables
|
||||
if table.name.strip().casefold().removesuffix("s") in requested_names
|
||||
}
|
||||
# Owners and deadlines can be fields or related tables. An unrelated table
|
||||
# with the right name does not make them part of the project tracker.
|
||||
related_ids = set(tracker_ids)
|
||||
table_ids = {table.id for table in tables}
|
||||
for source_id, target_id in LinkRowField.objects.filter(
|
||||
table_id__in=table_ids, link_row_table_id__in=table_ids
|
||||
).values_list("table_id", "link_row_table_id"):
|
||||
if source_id in tracker_ids or target_id in tracker_ids:
|
||||
related_ids.update((source_id, target_id))
|
||||
schema_names = {
|
||||
name.strip().casefold().removesuffix("s")
|
||||
for table in tables
|
||||
if table.id in related_ids
|
||||
for name in [table.name, *(field.name for field in table.field_set.all())]
|
||||
}
|
||||
# Match whole words in composite labels, and only explicit deadline phrases:
|
||||
# a generic date field (for example Start Date) is not a deadline.
|
||||
name_words = [
|
||||
tuple(
|
||||
word.removesuffix("s")
|
||||
for word in name.replace("_", " ").replace("-", " ").split()
|
||||
)
|
||||
for name in schema_names
|
||||
]
|
||||
has_owner = any({"owner", "assignee"}.intersection(words) for words in name_words)
|
||||
has_deadline = any(
|
||||
"deadline" in words
|
||||
or any(
|
||||
pair in {("due", "date"), ("target", "date")}
|
||||
for pair in zip(words, words[1:])
|
||||
)
|
||||
for words in name_words
|
||||
)
|
||||
return [
|
||||
CheckResult(
|
||||
"Projects and Milestones tables created",
|
||||
requested_names <= singular_names,
|
||||
hint=f"tables: {sorted(rows_by_table)}",
|
||||
),
|
||||
CheckResult(
|
||||
"every table has example rows",
|
||||
bool(rows_by_table) and all(rows_by_table.values()),
|
||||
hint=f"rows per table: {rows_by_table}",
|
||||
),
|
||||
CheckResult(
|
||||
"tracker represents owners and deadlines",
|
||||
has_owner and has_deadline,
|
||||
hint=f"tracker schema names: {sorted(schema_names)}",
|
||||
),
|
||||
CheckResult(
|
||||
"no tool name conflict leaked",
|
||||
"conflicts with existing tool" not in _messages_text(output),
|
||||
hint=f"tools called: {output.tool_calls}",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
register_case(
|
||||
EvalCase(
|
||||
id="prod-replay/project-tracker-onboarding",
|
||||
dataset="kuma-prod-replay",
|
||||
prompt=PROMPT_PROJECT_TRACKER,
|
||||
scenario="prod-replay-project-tracker-onboarding",
|
||||
checks=_check_project_tracker_onboarding,
|
||||
max_iters=30,
|
||||
max_tool_errors=3,
|
||||
metadata={"failure_class": "row_tool_conflict"},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ISO week number formula
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@register_scenario("prod-replay-iso-week-number-formula")
|
||||
def _iso_week_number_formula_scenario(fx: Fixtures) -> EvalScenario:
|
||||
"""Shipments table with the {Shipped On} column the prompt references."""
|
||||
|
||||
user = fx.create_user()
|
||||
workspace = fx.create_workspace(user=user)
|
||||
database = fx.create_database_application(workspace=workspace, name="Shipping DB")
|
||||
table = fx.create_database_table(database=database, name="Shipments")
|
||||
name = fx.create_text_field(table=table, name="Name", primary=True)
|
||||
shipped_on = fx.create_date_field(table=table, name="Shipped On")
|
||||
RowHandler().force_create_rows(
|
||||
user,
|
||||
table,
|
||||
[
|
||||
{name.db_column: f"Shipment {day}", shipped_on.db_column: day}
|
||||
for day in SHIPMENT_ISO_WEEKS
|
||||
],
|
||||
)
|
||||
return EvalScenario(
|
||||
user=user,
|
||||
workspace=workspace,
|
||||
ui_context=build_database_ui_context(user, workspace, database, table),
|
||||
refs={"table": table},
|
||||
)
|
||||
|
||||
|
||||
def _check_iso_week_number_formula(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
"""Regression: 'Exceeded maximum output retries (1)' from the formula agent."""
|
||||
|
||||
table = scenario.refs["table"]
|
||||
all_formula_fields = list(FormulaField.objects.filter(table=table))
|
||||
week_fields = [f for f in all_formula_fields if "week" in f.name.lower()]
|
||||
# Recovery must not leave a broken candidate beside a working formula.
|
||||
week_errors = {field.name: field.error for field in week_fields if field.error}
|
||||
week_field = _preferred_formula_field(table, "week")
|
||||
expected = {
|
||||
f"Shipment {day}": Decimal(week) for day, week in SHIPMENT_ISO_WEEKS.items()
|
||||
}
|
||||
actual = _numeric_values_by_primary(table, week_field) if week_field else {}
|
||||
return [
|
||||
CheckResult(
|
||||
"week number formula field created",
|
||||
len(week_fields) >= 1,
|
||||
hint=f"formula fields: {[f.name for f in all_formula_fields]}",
|
||||
),
|
||||
CheckResult(
|
||||
"formula is valid",
|
||||
bool(week_fields) and not week_errors,
|
||||
hint=f"formula errors: {week_errors}" if week_fields else "no field",
|
||||
),
|
||||
CheckResult(
|
||||
"week numbers match ISO 8601",
|
||||
actual == expected,
|
||||
hint=f"expected {expected}, got {actual}",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
register_case(
|
||||
EvalCase(
|
||||
id="prod-replay/iso-week-number-formula",
|
||||
dataset="kuma-prod-replay",
|
||||
prompt=PROMPT_ISO_WEEK_FORMULA,
|
||||
scenario="prod-replay-iso-week-number-formula",
|
||||
checks=_check_iso_week_number_formula,
|
||||
max_iters=15,
|
||||
max_tool_errors=2,
|
||||
metadata={"failure_class": "formula_agent_retries"},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Impossible formula request
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@register_scenario("prod-replay-impossible-formula-request")
|
||||
def _impossible_formula_request_scenario(fx: Fixtures) -> EvalScenario:
|
||||
"""Brochures table with the URL field the impossible request points at."""
|
||||
|
||||
user = fx.create_user()
|
||||
workspace = fx.create_workspace(user=user)
|
||||
database = fx.create_database_application(workspace=workspace, name="Marketing DB")
|
||||
table = fx.create_database_table(database=database, name="Brochures")
|
||||
fx.create_text_field(table=table, name="Name", primary=True)
|
||||
fx.create_url_field(table=table, name="Brochure Link")
|
||||
return EvalScenario(
|
||||
user=user,
|
||||
workspace=workspace,
|
||||
ui_context=build_database_ui_context(user, workspace, database, table),
|
||||
refs={"table": table},
|
||||
)
|
||||
|
||||
|
||||
def _check_impossible_formula_request(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
"""Regression: same retries exhaustion when the request cannot be expressed."""
|
||||
|
||||
broken = [
|
||||
field.name
|
||||
for field in FormulaField.objects.filter(table=scenario.refs["table"])
|
||||
if field.error
|
||||
]
|
||||
# The exhaustion may appear in a contained retry prompt; surviving it is the fix.
|
||||
return [
|
||||
CheckResult(
|
||||
"turn ended with a real answer",
|
||||
bool(output.answer.strip()),
|
||||
hint=f"answer: {output.answer[:200]!r}",
|
||||
),
|
||||
CheckResult(
|
||||
"no broken formula left behind",
|
||||
not broken,
|
||||
hint=f"formula fields with errors: {broken}",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
register_case(
|
||||
EvalCase(
|
||||
id="prod-replay/impossible-formula-request",
|
||||
dataset="kuma-prod-replay",
|
||||
prompt=PROMPT_IMPOSSIBLE_FORMULA,
|
||||
scenario="prod-replay-impossible-formula-request",
|
||||
checks=_check_impossible_formula_request,
|
||||
max_iters=15,
|
||||
max_tool_errors=3,
|
||||
metadata={"failure_class": "formula_agent_retries"},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fake rows into typed fields
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@register_scenario("prod-replay-fake-rows-into-typed-fields")
|
||||
def _fake_rows_into_typed_fields_scenario(fx: Fixtures) -> EvalScenario:
|
||||
"""Employees table with the exact typed fields the prompt enumerates."""
|
||||
|
||||
user = fx.create_user()
|
||||
workspace = fx.create_workspace(user=user)
|
||||
database = fx.create_database_application(workspace=workspace, name="Staff DB")
|
||||
table = fx.create_database_table(database=database, name="Employees")
|
||||
fields = {
|
||||
"Full Name": fx.create_text_field(table=table, name="Full Name", primary=True),
|
||||
"Team": fx.create_text_field(table=table, name="Team"),
|
||||
"Phone": fx.create_text_field(table=table, name="Phone"),
|
||||
"Level": fx.create_single_select_field(table=table, name="Level"),
|
||||
"Start Date": fx.create_date_field(table=table, name="Start Date"),
|
||||
"Notes": fx.create_text_field(table=table, name="Notes"),
|
||||
"Performance Score": fx.create_number_field(
|
||||
table=table, name="Performance Score"
|
||||
),
|
||||
}
|
||||
for value in ("1", "2", "3"):
|
||||
fx.create_select_option(field=fields["Level"], value=value)
|
||||
return EvalScenario(
|
||||
user=user,
|
||||
workspace=workspace,
|
||||
ui_context=build_database_ui_context(user, workspace, database, table),
|
||||
refs={"table": table, "fields": fields},
|
||||
)
|
||||
|
||||
|
||||
def _check_fake_rows_into_typed_fields(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
"""Regression: 'value must be a decimal number' / date format errors ended the turn."""
|
||||
|
||||
table = scenario.refs["table"]
|
||||
required_fields = {
|
||||
name: scenario.refs["fields"][name] for name in REQUIRED_EMPLOYEE_FIELDS
|
||||
}
|
||||
active_field_ids = set(table.field_set.values_list("id", flat=True))
|
||||
missing_fields = [
|
||||
name
|
||||
for name, field in required_fields.items()
|
||||
if field.id not in active_field_ids
|
||||
]
|
||||
columns = [field.db_column for field in required_fields.values()]
|
||||
rows = list(table.get_model().objects.all())
|
||||
incomplete_row_ids = [
|
||||
row.id
|
||||
for row in rows
|
||||
if any(getattr(row, column, None) in (None, "") for column in columns)
|
||||
]
|
||||
return [
|
||||
CheckResult(
|
||||
f"{REQUESTED_EMPLOYEE_COUNT} employees created",
|
||||
len(rows) == REQUESTED_EMPLOYEE_COUNT,
|
||||
hint=f"rows: {len(rows)}",
|
||||
),
|
||||
CheckResult(
|
||||
"every row has valid typed values",
|
||||
bool(rows) and not missing_fields and not incomplete_row_ids,
|
||||
hint=(
|
||||
f"missing fields: {missing_fields}; "
|
||||
f"rows missing one of {REQUIRED_EMPLOYEE_FIELDS}: "
|
||||
f"{incomplete_row_ids[:10]}"
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
register_case(
|
||||
EvalCase(
|
||||
id="prod-replay/fake-rows-into-typed-fields",
|
||||
dataset="kuma-prod-replay",
|
||||
prompt=PROMPT_SAMPLE_EMPLOYEE_ROWS,
|
||||
scenario="prod-replay-fake-rows-into-typed-fields",
|
||||
checks=_check_fake_rows_into_typed_fields,
|
||||
max_iters=20,
|
||||
max_tool_errors=3,
|
||||
metadata={"failure_class": "row_validation"},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Signed amount formula
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@register_scenario("prod-replay-signed-amount-formula")
|
||||
def _signed_amount_formula_scenario(fx: Fixtures) -> EvalScenario:
|
||||
"""Transactions table with the Transaction Type/Amount fields it needs."""
|
||||
|
||||
user = fx.create_user()
|
||||
workspace = fx.create_workspace(user=user)
|
||||
database = fx.create_database_application(workspace=workspace, name="Finance DB")
|
||||
table = fx.create_database_table(database=database, name="Transactions")
|
||||
reference = fx.create_text_field(table=table, name="Reference", primary=True)
|
||||
transaction_type = fx.create_single_select_field(
|
||||
table=table, name="Transaction Type"
|
||||
)
|
||||
options = {
|
||||
value: fx.create_select_option(field=transaction_type, value=value)
|
||||
for value in ("Credit", "Debit")
|
||||
}
|
||||
amount = fx.create_number_field(table=table, name="Amount")
|
||||
RowHandler().force_create_rows(
|
||||
user,
|
||||
table,
|
||||
[
|
||||
{
|
||||
reference.db_column: ref,
|
||||
transaction_type.db_column: options[kind].id,
|
||||
amount.db_column: value,
|
||||
}
|
||||
for ref, kind, value in SIGNED_TRANSACTIONS
|
||||
],
|
||||
)
|
||||
return EvalScenario(
|
||||
user=user,
|
||||
workspace=workspace,
|
||||
ui_context=build_database_ui_context(user, workspace, database, table),
|
||||
refs={"table": table},
|
||||
)
|
||||
|
||||
|
||||
def _check_signed_amount_formula(
|
||||
case: EvalCase, scenario: EvalScenario, output: EvalRunOutput
|
||||
) -> list[CheckResult]:
|
||||
"""Regression: bare formula compiler errors ('and'/'or' arity) ended the turn."""
|
||||
|
||||
table = scenario.refs["table"]
|
||||
# The crash class is what this replay verifies; the exact field name is not.
|
||||
formula_fields = list(FormulaField.objects.filter(table=table))
|
||||
formula_errors = {
|
||||
field.name: field.error for field in formula_fields if field.error
|
||||
}
|
||||
signed_field = _preferred_formula_field(table, "signed")
|
||||
expected = {
|
||||
ref: Decimal(value if kind == "Credit" else -value)
|
||||
for ref, kind, value in SIGNED_TRANSACTIONS
|
||||
}
|
||||
actual = _numeric_values_by_primary(table, signed_field) if signed_field else {}
|
||||
return [
|
||||
CheckResult(
|
||||
"a formula field was created",
|
||||
len(formula_fields) >= 1,
|
||||
hint=f"formula fields: {[f.name for f in formula_fields]}",
|
||||
),
|
||||
CheckResult(
|
||||
"formula is valid",
|
||||
bool(formula_fields) and not formula_errors,
|
||||
hint=f"formula errors: {formula_errors}" if formula_fields else "no field",
|
||||
),
|
||||
CheckResult(
|
||||
"signed amounts match the transaction type",
|
||||
actual == expected,
|
||||
hint=f"expected {expected}, got {actual}",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
register_case(
|
||||
EvalCase(
|
||||
id="prod-replay/signed-amount-formula",
|
||||
dataset="kuma-prod-replay",
|
||||
prompt=PROMPT_SIGNED_AMOUNT_FORMULA,
|
||||
scenario="prod-replay-signed-amount-formula",
|
||||
checks=_check_signed_amount_formula,
|
||||
max_iters=15,
|
||||
max_tool_errors=2,
|
||||
metadata={"failure_class": "formula_compiler"},
|
||||
)
|
||||
)
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess # nosec
|
||||
from pathlib import Path
|
||||
@@ -8,6 +9,19 @@ from pathlib import Path
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[6]
|
||||
|
||||
|
||||
def get_evaluator_source_hash() -> str:
|
||||
"""Fingerprint evaluator/check sources even in an archive without git metadata."""
|
||||
|
||||
root = Path(__file__).resolve().parent
|
||||
digest = hashlib.sha256()
|
||||
for path in sorted(root.rglob("*.py")):
|
||||
digest.update(path.relative_to(root).as_posix().encode())
|
||||
digest.update(b"\0")
|
||||
digest.update(path.read_bytes())
|
||||
digest.update(b"\0")
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _git(*args: str) -> str:
|
||||
"""Run a git command in the repo root; "" on any failure (no git, no
|
||||
.git dir, timeout, non-zero exit) — this must never raise."""
|
||||
|
||||
@@ -19,6 +19,7 @@ from pydantic_ai._utils import ( # noqa: PLC2701
|
||||
run_until_complete,
|
||||
using_thread_executor,
|
||||
)
|
||||
from pydantic_ai.exceptions import UnexpectedModelBehavior, UsageLimitExceeded
|
||||
from pydantic_ai.messages import ModelRequest, ModelResponse, RetryPromptPart
|
||||
from pydantic_ai.models import Model
|
||||
from pydantic_ai.tool_manager import ToolManager
|
||||
@@ -208,6 +209,10 @@ def count_tool_errors(result: Any) -> tuple[int, str]:
|
||||
or is_mode_redirect(content)
|
||||
):
|
||||
continue
|
||||
# pydantic-ai's nudge after an empty model response, which it
|
||||
# recovers from on its own — not a tool failure.
|
||||
if part.tool_name is None and content.startswith("Please "):
|
||||
continue
|
||||
retry_errors.append(
|
||||
{
|
||||
"tool_name": getattr(part, "tool_name", None),
|
||||
@@ -218,6 +223,34 @@ def count_tool_errors(result: Any) -> tuple[int, str]:
|
||||
return len(retry_errors), hint
|
||||
|
||||
|
||||
def executed_tool_calls(output: EvalRunOutput, name: str) -> list[dict]:
|
||||
"""
|
||||
Return the calls to a tool that the mode router did not send back.
|
||||
|
||||
An incomplete call to a tool owned by another mode is answered with a
|
||||
re-call redirect instead of running. Scoring that call reads the model's
|
||||
first guess instead of the arguments that ran.
|
||||
|
||||
:param output: The recorded run output.
|
||||
:param name: The tool function name.
|
||||
:return: The surviving assistant call entries, in call order.
|
||||
"""
|
||||
|
||||
redirected = {
|
||||
entry.get("tool_call_id")
|
||||
for entry in output.messages
|
||||
if entry["role"] == "user" and is_mode_redirect(entry.get("content"))
|
||||
}
|
||||
return [
|
||||
entry
|
||||
for entry in output.messages
|
||||
if entry["role"] == "assistant"
|
||||
and entry.get("tool_name") == name
|
||||
and "args" in entry
|
||||
and entry.get("tool_call_id") not in redirected
|
||||
]
|
||||
|
||||
|
||||
def tool_called(output: EvalRunOutput, name: str) -> int:
|
||||
"""Return how many times *name* was called during the run."""
|
||||
|
||||
@@ -257,6 +290,14 @@ class EvalCaseTimeout(Exception):
|
||||
"""A case outran its budget and its cancelled tools have finished."""
|
||||
|
||||
|
||||
class EvalCaseModelError(Exception):
|
||||
"""A known model failure from the agent run, rather than setup or checks."""
|
||||
|
||||
def __init__(self, error: UsageLimitExceeded | UnexpectedModelBehavior):
|
||||
self.error = error
|
||||
super().__init__(str(error))
|
||||
|
||||
|
||||
class EvalCaseCleanupError(RuntimeError):
|
||||
"""A tool outlived bounded cleanup; the eval process must be restarted."""
|
||||
|
||||
@@ -417,6 +458,8 @@ def run_case(
|
||||
raise EvalCaseTimeout(
|
||||
f"{case.id} exceeded {timeout_s:g}s and was cancelled"
|
||||
) from exc
|
||||
except (UsageLimitExceeded, UnexpectedModelBehavior) as exc:
|
||||
raise EvalCaseModelError(exc) from exc
|
||||
duration_s = time.monotonic() - start
|
||||
|
||||
tool_error_count, tool_error_hint = count_tool_errors(result)
|
||||
|
||||
@@ -14,7 +14,7 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from collections import Counter
|
||||
import time
|
||||
from dataclasses import asdict
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
@@ -24,15 +24,19 @@ from openinference.semconv.trace import OpenInferenceSpanKindValues, SpanAttribu
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.context import Context
|
||||
from opentelemetry.trace import Status, StatusCode
|
||||
from pydantic_ai.exceptions import UsageLimitExceeded
|
||||
|
||||
from baserow_enterprise.assistant.deps import AgentMode
|
||||
from baserow_enterprise.assistant.evals.control import RunControl
|
||||
from baserow_enterprise.assistant.evals.gitinfo import get_git_info
|
||||
from baserow_enterprise.assistant.evals.gitinfo import (
|
||||
get_evaluator_source_hash,
|
||||
get_git_info,
|
||||
)
|
||||
from baserow_enterprise.assistant.evals.harness import (
|
||||
EvalCaseCleanupError,
|
||||
EvalCaseModelError,
|
||||
EvalCaseTimeout,
|
||||
ensure_worker_safe,
|
||||
get_case_timeout_s,
|
||||
override_assistant_prompts,
|
||||
run_case,
|
||||
tool_called,
|
||||
@@ -68,7 +72,12 @@ from baserow_enterprise.assistant.tools.search_user_docs.handler import (
|
||||
|
||||
UI_CASE_PREFIX = "ui:"
|
||||
# Version 1 recorded production settings without applying them to the agent.
|
||||
HARNESS_VERSION = 2
|
||||
# Version 3 excludes required mode redirects from the tool-error budget.
|
||||
# Version 4 checks saved Builder behavior and records request-budget failures.
|
||||
# Version 5 also records model/tool and other execution errors as failed cases.
|
||||
# Version 6 leaves infrastructure, harness and check errors ungraded.
|
||||
# Version 7 checks saved state and records execution errors without replaying cases.
|
||||
HARNESS_VERSION = 7
|
||||
|
||||
_PROMPT_INPUT_KEYS = ("prompt", "question", "input", "message")
|
||||
|
||||
@@ -239,53 +248,70 @@ def _score_and_explanation(checks: list[dict[str, Any]]) -> tuple[float, str]:
|
||||
return passed_count / total, explanation
|
||||
|
||||
|
||||
def checklist(output: dict[str, Any]) -> dict[str, Any]:
|
||||
def checklist(output: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""Evaluator: fraction of checks that passed, plus failure detail.
|
||||
|
||||
Skipped outputs (no ``checks`` were ever run) score an empty result — the
|
||||
Missing or skipped outputs score an empty result — the
|
||||
Phoenix-valid way to record "no score" — so they don't count as 0.0 in
|
||||
aggregates. ``None`` is not an option: the installed phoenix-client
|
||||
aggregates. Returning ``None`` is not an option: the installed phoenix-client
|
||||
scorer (``_default_eval_scorer``) raises ``ValueError`` on it.
|
||||
"""
|
||||
|
||||
if "skipped" in output:
|
||||
if output is None or "skipped" in output:
|
||||
return {}
|
||||
score, explanation = _score_and_explanation(output.get("checks", []))
|
||||
# 2-tuples map position 1 to the LABEL in the phoenix client; 3-tuples don't.
|
||||
return {"score": score, "explanation": explanation or None}
|
||||
|
||||
|
||||
def passed(output: dict[str, Any]) -> bool | dict[str, Any]:
|
||||
def passed(output: dict[str, Any] | None) -> bool | dict[str, Any]:
|
||||
"""Evaluator: whether every check (incl. the tool-error budget) passed.
|
||||
|
||||
Skipped outputs score an empty result instead of the vacuous ``all([])
|
||||
Missing or skipped outputs score an empty result instead of the vacuous ``all([])
|
||||
is True``, so they don't count as passing in aggregates.
|
||||
"""
|
||||
|
||||
if "skipped" in output:
|
||||
if output is None or "skipped" in output:
|
||||
return {}
|
||||
return all(c["passed"] for c in output.get("checks", []))
|
||||
|
||||
|
||||
def _timed_out_result(case: EvalCase, reason: str) -> dict[str, Any]:
|
||||
"""A timed-out case's Phoenix output: one failed check, so it scores 0."""
|
||||
def _failed_execution_result(
|
||||
case: EvalCase, error: Exception, duration_s: float
|
||||
) -> dict[str, Any]:
|
||||
"""Record a failed attempt without inventing counters or running state checks."""
|
||||
|
||||
checks = [{"name": "completed_within_timeout", "passed": False, "hint": reason}]
|
||||
timed_out = isinstance(error, EvalCaseTimeout)
|
||||
reason = str(error)
|
||||
usage_limit_exceeded = isinstance(error, UsageLimitExceeded)
|
||||
if timed_out:
|
||||
check_name = "completed_within_timeout"
|
||||
elif usage_limit_exceeded:
|
||||
check_name = "completed_within_request_limit"
|
||||
else:
|
||||
check_name = "completed_without_execution_error"
|
||||
span = trace.get_current_span()
|
||||
span.record_exception(error)
|
||||
span.set_status(Status(StatusCode.ERROR, reason))
|
||||
checks = [{"name": check_name, "passed": False, "hint": reason}]
|
||||
return {
|
||||
"question": case.prompt,
|
||||
# No answer to grade, so don't spend a judge call on it.
|
||||
"judge_docs": False,
|
||||
"answer": "",
|
||||
"tool_calls": [],
|
||||
"tool_error_count": 0,
|
||||
"tool_error_count": None,
|
||||
"checks": checks,
|
||||
"score": 0.0,
|
||||
"passed": False,
|
||||
"timed_out": True,
|
||||
"timed_out": timed_out,
|
||||
"usage_limit_exceeded": usage_limit_exceeded,
|
||||
"execution_error": reason,
|
||||
"execution_error_type": type(error).__name__,
|
||||
"sources": [],
|
||||
"sources_count": 0,
|
||||
"request_count": 0,
|
||||
"duration_s": get_case_timeout_s(),
|
||||
"request_count": None,
|
||||
"duration_s": duration_s,
|
||||
}
|
||||
|
||||
|
||||
@@ -307,14 +333,16 @@ def run_case_for_experiment(
|
||||
return {"skipped": "knowledge base unavailable"}
|
||||
|
||||
logger.info("run {}", case.id)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
with override_assistant_prompts(prompt_texts or {}):
|
||||
output, checks = run_case(case, model)
|
||||
except EvalCaseTimeout as exc:
|
||||
# A hang is a real failure: score it 0 rather than skipping it, and
|
||||
# keep the remaining cases running.
|
||||
logger.warning("TIMEOUT {}", exc)
|
||||
return _timed_out_result(case, str(exc))
|
||||
except (EvalCaseTimeout, EvalCaseModelError) as exc:
|
||||
# Only outcomes classified inside the agent run are model failures.
|
||||
# Setup, infrastructure and check errors must reach Phoenix ungraded.
|
||||
error = exc.error if isinstance(exc, EvalCaseModelError) else exc
|
||||
logger.warning("FAILED EXECUTION {}: {}", case.id, error)
|
||||
return _failed_execution_result(case, error, time.monotonic() - started)
|
||||
check_dicts = [asdict(c) for c in checks]
|
||||
partial = {"checks": check_dicts}
|
||||
score = _score_and_explanation(check_dicts)[0]
|
||||
@@ -344,7 +372,7 @@ def run_case_for_experiment(
|
||||
|
||||
|
||||
def answer_quality(
|
||||
output: dict[str, Any],
|
||||
output: dict[str, Any] | None,
|
||||
metadata: dict[str, Any],
|
||||
expected: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
@@ -360,7 +388,7 @@ def answer_quality(
|
||||
binder passes it by that name (an alias, ``reference``, also exists).
|
||||
"""
|
||||
|
||||
if "skipped" in output or not output.get("judge_docs"):
|
||||
if output is None or "skipped" in output or not output.get("judge_docs"):
|
||||
return {}
|
||||
|
||||
reference_answer = (expected or {}).get("reference_answer") or None
|
||||
@@ -416,6 +444,7 @@ def _experiment_metadata(
|
||||
metadata = {
|
||||
"model": model,
|
||||
"harness_version": HARNESS_VERSION,
|
||||
"evaluator_source_hash": get_evaluator_source_hash(),
|
||||
"model_settings": dict(get_model_settings(model, ORCHESTRATOR)),
|
||||
"judge_model": get_judge_model(),
|
||||
**extra,
|
||||
@@ -455,6 +484,13 @@ def run_experiment_for(
|
||||
control = control or RunControl()
|
||||
client = get_phoenix_client()
|
||||
kb_available = KnowledgeBaseHandler().can_search()
|
||||
if dataset_name == "kuma-docs" and not kb_available:
|
||||
raise ValueError(
|
||||
"Docs evals require a searchable knowledge base in the eval database. "
|
||||
"Configure BASEROW_EMBEDDINGS_API_URL and pgvector, then run "
|
||||
"`just dc-dev exec assistant-eval-runner just b manage "
|
||||
"sync_knowledge_base` and wait for indexing to finish."
|
||||
)
|
||||
prompt_texts = _fetch_prompt_overrides(client, prompt_overrides)
|
||||
|
||||
if case_ids:
|
||||
@@ -472,8 +508,6 @@ def run_experiment_for(
|
||||
runner_run_id,
|
||||
)
|
||||
|
||||
# Phoenix re-enters the task on retry, so cap each example at its repetitions.
|
||||
counted: Counter[str] = Counter()
|
||||
cleanup_error: EvalCaseCleanupError | None = None
|
||||
|
||||
def task(example: Any) -> dict[str, Any]:
|
||||
@@ -492,15 +526,16 @@ def run_experiment_for(
|
||||
case, model, kb_available, prompt_texts
|
||||
)
|
||||
except EvalCaseCleanupError as exc:
|
||||
# Phoenix catches task exceptions and may retry them. Stop its
|
||||
# remaining work, then propagate this failure to the runner.
|
||||
# Phoenix catches task exceptions. Stop its remaining work,
|
||||
# then propagate this failure to the runner.
|
||||
cleanup_error = exc
|
||||
control.stop()
|
||||
raise
|
||||
example_id = str(example.id)
|
||||
if counted[example_id] < runs:
|
||||
counted[example_id] += 1
|
||||
control.case_finished()
|
||||
except Exception:
|
||||
# Phoenix prints task errors; the runner captures Loguru instead.
|
||||
logger.exception("Ungraded eval error in {}", case.id)
|
||||
raise
|
||||
control.case_finished()
|
||||
return result
|
||||
|
||||
dataset = client.datasets.get_dataset(dataset=dataset_name)
|
||||
@@ -517,6 +552,8 @@ def run_experiment_for(
|
||||
runner_run_id=runner_run_id,
|
||||
),
|
||||
repetitions=runs,
|
||||
# Retrying a check/provider error would repeat the entire agent run.
|
||||
retries=0,
|
||||
)
|
||||
if cleanup_error is not None:
|
||||
raise cleanup_error
|
||||
@@ -639,10 +676,42 @@ def _log_case_run(
|
||||
SpanAttributes.INPUT_MIME_TYPE: "text/plain",
|
||||
},
|
||||
) as span:
|
||||
result = run_case_for_experiment(case, model, kb_available, prompt_texts)
|
||||
try:
|
||||
result = run_case_for_experiment(
|
||||
case, model, kb_available, prompt_texts
|
||||
)
|
||||
except EvalCaseCleanupError:
|
||||
# Preserve the poisoned worker's immediate abort behavior.
|
||||
raise
|
||||
except Exception as exc:
|
||||
# Unlike the full-dataset path, this loop owns Phoenix run
|
||||
# logging. Record an ungraded error before aborting the subset.
|
||||
span_context = span.get_span_context()
|
||||
try:
|
||||
client.experiments.log_run(
|
||||
experiment_id=experiment["id"],
|
||||
dataset_example_id=example.get("node_id") or example["id"],
|
||||
output=None,
|
||||
error=repr(exc),
|
||||
start_time=start,
|
||||
end_time=datetime.now(timezone.utc),
|
||||
repetition_number=repetition,
|
||||
trace_id=(
|
||||
format(span_context.trace_id, "032x")
|
||||
if span_context and span_context.trace_id
|
||||
else None
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Could not record failed eval case {}", case.id)
|
||||
raise
|
||||
span.set_attribute(SpanAttributes.OUTPUT_VALUE, json.dumps(result))
|
||||
span.set_attribute(SpanAttributes.OUTPUT_MIME_TYPE, "application/json")
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
span.set_status(
|
||||
Status(StatusCode.ERROR, result["execution_error"])
|
||||
if result.get("execution_error")
|
||||
else Status(StatusCode.OK)
|
||||
)
|
||||
span_context = span.get_span_context()
|
||||
end = datetime.now(timezone.utc)
|
||||
|
||||
|
||||
@@ -516,10 +516,13 @@ query ($datasetId: ID!) {
|
||||
name
|
||||
createdAt
|
||||
metadata
|
||||
repetitions
|
||||
runCount
|
||||
expectedRunCount
|
||||
datasetVersion { id }
|
||||
averageRunLatencyMs
|
||||
costSummary { total { cost tokens } }
|
||||
annotationSummaries { annotationName meanScore }
|
||||
annotationSummaries { annotationName meanScore scoreCount }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -537,7 +540,9 @@ def _settings_label(metadata: dict[str, Any]) -> str | None:
|
||||
"""Compact "temperature=0.3 reasoning=none" for the results table."""
|
||||
|
||||
settings = metadata.get("model_settings") or {}
|
||||
if settings and metadata.get("harness_version") != HARNESS_VERSION:
|
||||
if settings and metadata.get("harness_version") not in range(
|
||||
2, HARNESS_VERSION + 1
|
||||
):
|
||||
return "model settings unverified (legacy harness)"
|
||||
parts = [
|
||||
f"{key.replace('openai_reasoning_effort', 'reasoning')}={settings[key]}"
|
||||
@@ -610,6 +615,27 @@ def _results_json() -> bytes:
|
||||
run_count = node.get("runCount")
|
||||
if run_count is None:
|
||||
run_count = totals.get("run_count")
|
||||
expected_run_count = node.get("expectedRunCount")
|
||||
repetitions = node.get("repetitions") or 1
|
||||
# Phoenix freezes the case population when creating an experiment;
|
||||
# today's registry may contain a different set of cases.
|
||||
case_count = (
|
||||
expected_run_count // repetitions
|
||||
if expected_run_count is not None
|
||||
and expected_run_count > 0
|
||||
and repetitions > 0
|
||||
and expected_run_count % repetitions == 0
|
||||
else None
|
||||
)
|
||||
annotation_summaries = node.get("annotationSummaries", [])
|
||||
score_counts = {
|
||||
summary["annotationName"]: summary.get("scoreCount") or 0
|
||||
for summary in annotation_summaries
|
||||
}
|
||||
mandatory_score_counts = [
|
||||
score_counts.get(name, 0) for name in ("checklist", "passed")
|
||||
]
|
||||
scored_run_count = min(mandatory_score_counts)
|
||||
avg_latency_ms = node.get("averageRunLatencyMs") or totals.get(
|
||||
"average_run_latency_ms"
|
||||
)
|
||||
@@ -626,18 +652,33 @@ def _results_json() -> bytes:
|
||||
"name": node.get("name") or "",
|
||||
"created_at": node.get("createdAt"),
|
||||
"status": state.status if state else "unknown",
|
||||
"run_count": run_count,
|
||||
"prompts": metadata.get("prompts"),
|
||||
"prompt_overrides": metadata.get("prompt_overrides", []),
|
||||
"model": metadata.get("model"),
|
||||
"git_label": git_label or None,
|
||||
"notes": metadata.get("notes"),
|
||||
"settings": _settings_label(metadata),
|
||||
"imported_baseline": bool(metadata.get("baseline")),
|
||||
"evaluator_source_hash": metadata.get("evaluator_source_hash"),
|
||||
"scores": {
|
||||
s["annotationName"]: s["meanScore"]
|
||||
for s in node.get("annotationSummaries", [])
|
||||
for s in annotation_summaries
|
||||
if s.get("meanScore") is not None
|
||||
},
|
||||
"run_count": run_count,
|
||||
"expected_run_count": expected_run_count,
|
||||
"case_count": case_count,
|
||||
"dataset_version_id": (node.get("datasetVersion") or {}).get(
|
||||
"id"
|
||||
),
|
||||
"repetitions": repetitions,
|
||||
"scored_run_count": scored_run_count,
|
||||
"score_counts": score_counts,
|
||||
"complete": bool(expected_run_count)
|
||||
and all(
|
||||
count == expected_run_count
|
||||
for count in mandatory_score_counts
|
||||
),
|
||||
"time_s": (
|
||||
avg_latency_ms * run_count / 1000
|
||||
if avg_latency_ms and run_count
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
from django.contrib.auth.models import AbstractUser
|
||||
|
||||
from faker import Faker
|
||||
@@ -20,10 +22,18 @@ from baserow_enterprise.assistant.types import (
|
||||
)
|
||||
|
||||
|
||||
class _EvalFixtures(Fixtures):
|
||||
def create_user(self, **kwargs) -> AbstractUser:
|
||||
# Faker's uniqueness cache belongs to one fixture instance, while eval
|
||||
# users persist across scenarios and runs in the same database.
|
||||
kwargs.setdefault("email", f"kuma-eval-{uuid4().hex}@example.com")
|
||||
return super().create_user(**kwargs)
|
||||
|
||||
|
||||
def make_fixtures() -> Fixtures:
|
||||
"""Build a ``Fixtures`` instance usable outside pytest, e.g. by scenario builders."""
|
||||
|
||||
return Fixtures(Faker())
|
||||
return _EvalFixtures(Faker())
|
||||
|
||||
|
||||
def build_database_ui_context(
|
||||
|
||||
+15
@@ -20,6 +20,20 @@ from baserow_enterprise.assistant.evals.runner import (
|
||||
)
|
||||
from baserow_enterprise.assistant.evals.sync import sync_datasets
|
||||
from baserow_enterprise.assistant.telemetry import setup_instrumentation
|
||||
from baserow_enterprise.assistant.tools.search_user_docs.handler import (
|
||||
KnowledgeBaseHandler,
|
||||
)
|
||||
|
||||
|
||||
def sync_knowledge_base_if_needed() -> None:
|
||||
"""Populate a usable but empty knowledge base before evals can run."""
|
||||
|
||||
try:
|
||||
handler = KnowledgeBaseHandler()
|
||||
if handler.can_have_knowledge_base() and not handler.can_search():
|
||||
handler.sync_knowledge_base()
|
||||
except Exception:
|
||||
logger.exception("Failed to sync the assistant knowledge base on startup")
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
@@ -45,6 +59,7 @@ class Command(BaseCommand):
|
||||
|
||||
setup_instrumentation()
|
||||
load_all()
|
||||
sync_knowledge_base_if_needed()
|
||||
|
||||
try:
|
||||
sync_datasets(get_phoenix_client())
|
||||
|
||||
+147
-8
@@ -263,6 +263,10 @@
|
||||
border-radius: 3px;
|
||||
}
|
||||
.score-cell > span { position: relative; }
|
||||
.delta { font-size: 0.75rem; margin-left: 0.3rem; }
|
||||
.delta.up { color: var(--ok); }
|
||||
.delta.down { color: var(--bad); }
|
||||
.delta.flat { color: var(--muted); }
|
||||
#results-experiment {
|
||||
padding: 0.15rem 0.3rem;
|
||||
border: 1px solid var(--border);
|
||||
@@ -683,7 +687,17 @@
|
||||
return tokens + " tok";
|
||||
}
|
||||
|
||||
function usageCell(row, value, formatter, subText) {
|
||||
function deltaBadge(delta, formatted, lowerIsBetter) {
|
||||
var badge = document.createElement("span");
|
||||
var good = lowerIsBetter ? delta < 0 : delta > 0;
|
||||
var flat = Math.abs(delta) < 1e-9;
|
||||
badge.className = "delta " + (flat ? "flat" : good ? "up" : "down");
|
||||
badge.textContent = (delta >= 0 ? "+" : "−") + formatted;
|
||||
return badge;
|
||||
}
|
||||
|
||||
|
||||
function usageCell(row, value, baselineValue, formatter, subText) {
|
||||
var cell = document.createElement("td");
|
||||
if (value == null) {
|
||||
cell.textContent = "–";
|
||||
@@ -693,6 +707,12 @@
|
||||
var val = document.createElement("span");
|
||||
val.textContent = formatter(value);
|
||||
cell.appendChild(val);
|
||||
if (baselineValue != null) {
|
||||
cell.appendChild(document.createTextNode(" "));
|
||||
cell.appendChild(
|
||||
deltaBadge(value - baselineValue, formatter(Math.abs(value - baselineValue)), true)
|
||||
);
|
||||
}
|
||||
if (subText) {
|
||||
var sub = document.createElement("small");
|
||||
sub.style.display = "block";
|
||||
@@ -703,7 +723,7 @@
|
||||
row.appendChild(cell);
|
||||
}
|
||||
|
||||
function scoreCell(row, value) {
|
||||
function scoreCell(row, value, baselineValue) {
|
||||
var cell = document.createElement("td");
|
||||
cell.className = "score";
|
||||
if (value == null) {
|
||||
@@ -720,6 +740,13 @@
|
||||
var val = document.createElement("span");
|
||||
val.textContent = value.toFixed(2);
|
||||
wrap.appendChild(val);
|
||||
if (baselineValue != null) {
|
||||
var delta = value - baselineValue;
|
||||
var badge = document.createElement("span");
|
||||
badge.className = "delta " + (delta >= 0.02 ? "up" : delta <= -0.02 ? "down" : "flat");
|
||||
badge.textContent = (delta >= 0 ? "+" : "") + delta.toFixed(2);
|
||||
wrap.appendChild(badge);
|
||||
}
|
||||
cell.appendChild(wrap);
|
||||
row.appendChild(cell);
|
||||
}
|
||||
@@ -749,9 +776,38 @@
|
||||
});
|
||||
table.appendChild(head);
|
||||
|
||||
var totals = {
|
||||
scores: {},
|
||||
weights: {},
|
||||
baseline: {},
|
||||
baselineWeights: {},
|
||||
casesRun: 0,
|
||||
};
|
||||
|
||||
resultsData.forEach(function (dataset) {
|
||||
var byName = experimentsByName(dataset);
|
||||
var experiment = byName[selected];
|
||||
var baseline = byName["baseline"];
|
||||
var experimentComplete = experiment && experiment.complete;
|
||||
// Imports attach historical results to today's dataset version. Only live
|
||||
// experiments retain the version that their recorded checks actually ran.
|
||||
var importedBaseline = (experiment && experiment.imported_baseline) ||
|
||||
(baseline && baseline.imported_baseline);
|
||||
var comparable = experimentComplete && baseline && baseline.complete &&
|
||||
!importedBaseline && experiment.dataset_version_id &&
|
||||
experiment.dataset_version_id === baseline.dataset_version_id &&
|
||||
experiment.evaluator_source_hash &&
|
||||
experiment.evaluator_source_hash === baseline.evaluator_source_hash &&
|
||||
experiment.case_count > 0 && experiment.case_count === baseline.case_count;
|
||||
// Scores are already means; time and cost are totals over the repetitions.
|
||||
var repetitions = function (candidate) {
|
||||
return (candidate && candidate.repetitions) || 1;
|
||||
};
|
||||
var perPass = function (candidate, key) {
|
||||
if (!candidate || candidate[key] == null) return null;
|
||||
var reps = repetitions(candidate);
|
||||
return reps > 0 ? candidate[key] / reps : null;
|
||||
};
|
||||
var row = document.createElement("tr");
|
||||
var nameCell = document.createElement("td");
|
||||
if (experiment && experiment.link) {
|
||||
@@ -772,6 +828,32 @@
|
||||
if (experiment) {
|
||||
modelCell.textContent = (experiment.model || "") +
|
||||
(experiment.git_label ? " (" + experiment.git_label + ")" : "");
|
||||
if (!experimentComplete) {
|
||||
var incomplete = document.createElement("small");
|
||||
incomplete.className = "experiment-note";
|
||||
incomplete.textContent = "incomplete (" + experiment.scored_run_count +
|
||||
"/" + experiment.expected_run_count + " scored)";
|
||||
modelCell.appendChild(incomplete);
|
||||
} else if (importedBaseline) {
|
||||
var historical = document.createElement("small");
|
||||
historical.className = "experiment-note";
|
||||
historical.textContent = "historical baseline; comparison unavailable";
|
||||
modelCell.appendChild(historical);
|
||||
} else if (baseline && baseline.complete && !comparable) {
|
||||
var otherCases = document.createElement("small");
|
||||
otherCases.className = "experiment-note";
|
||||
otherCases.textContent = "matching baseline cases and checks could not be verified";
|
||||
modelCell.appendChild(otherCases);
|
||||
}
|
||||
var runReps = repetitions(experiment);
|
||||
var baseReps = baseline ? repetitions(baseline) : 1;
|
||||
if (runReps !== 1 || baseReps !== 1) {
|
||||
var repNote = document.createElement("small");
|
||||
repNote.className = "experiment-note";
|
||||
repNote.textContent = runReps + "x vs baseline " + baseReps +
|
||||
"x \u2014 time and cost shown per pass";
|
||||
modelCell.appendChild(repNote);
|
||||
}
|
||||
var overrides = experiment.prompt_overrides || [];
|
||||
var promptNote = overrides.length ? "Prompt overrides: " + overrides.join(", ") : "";
|
||||
[experiment.settings, experiment.notes, promptNote].forEach(function (text) {
|
||||
@@ -790,22 +872,79 @@
|
||||
stateCell.textContent = experiment ? statusText(experiment) : dataset.error ? "unavailable" : "not run";
|
||||
row.appendChild(stateCell);
|
||||
METRICS.forEach(function (metric) {
|
||||
var value = experiment ? experiment.scores[metric] : null;
|
||||
scoreCell(row, value == null ? null : value);
|
||||
var value = experimentComplete ? experiment.scores[metric] : null;
|
||||
var metricComparable = comparable &&
|
||||
experiment.score_counts[metric] === experiment.expected_run_count &&
|
||||
baseline.score_counts[metric] === baseline.expected_run_count;
|
||||
var baseValue = metricComparable ? baseline.scores[metric] : null;
|
||||
scoreCell(row, value == null ? null : value, baseValue == null ? null : baseValue);
|
||||
if (value != null && baseValue != null) {
|
||||
totals.scores[metric] = (totals.scores[metric] || 0) +
|
||||
value * experiment.case_count;
|
||||
totals.weights[metric] = (totals.weights[metric] || 0) +
|
||||
experiment.case_count;
|
||||
totals.baseline[metric] = (totals.baseline[metric] || 0) + baseValue * baseline.case_count;
|
||||
totals.baselineWeights[metric] = (totals.baselineWeights[metric] || 0) + baseline.case_count;
|
||||
}
|
||||
});
|
||||
usageCell(row, experiment ? experiment.time_s : null, fmtDuration);
|
||||
var time = experimentComplete ? perPass(experiment, "time_s") : null;
|
||||
var baseTime = comparable ? perPass(baseline, "time_s") : null;
|
||||
usageCell(row, time, baseTime, fmtDuration);
|
||||
var cost = experimentComplete ? perPass(experiment, "cost") : null;
|
||||
var baseCost = comparable ? perPass(baseline, "cost") : null;
|
||||
usageCell(
|
||||
row, experiment ? experiment.cost : null,
|
||||
row, cost, baseCost,
|
||||
function (value) { return "$" + value.toFixed(2); },
|
||||
experiment && experiment.tokens != null ? fmtTokens(experiment.tokens) : null
|
||||
experimentComplete && experiment.tokens != null
|
||||
? fmtTokens(perPass(experiment, "tokens")) : null
|
||||
);
|
||||
["time_s", "cost"].forEach(function (key) {
|
||||
if (comparable && experiment[key] != null && baseline[key] != null) {
|
||||
totals[key] = (totals[key] || 0) + perPass(experiment, key);
|
||||
totals["baseline_" + key] = (totals["baseline_" + key] || 0) + perPass(baseline, key);
|
||||
}
|
||||
});
|
||||
if (comparable && experiment.tokens != null) {
|
||||
totals.tokens = (totals.tokens || 0) + perPass(experiment, "tokens");
|
||||
}
|
||||
if (comparable) totals.casesRun += experiment.case_count;
|
||||
table.appendChild(row);
|
||||
});
|
||||
|
||||
if (totals.casesRun) {
|
||||
var totalRow = document.createElement("tr");
|
||||
["Overall (comparable cases)", String(totals.casesRun), "", ""].forEach(function (label) {
|
||||
var cell = document.createElement("td");
|
||||
cell.textContent = label;
|
||||
if (label === "Overall (comparable cases)") cell.style.fontWeight = "600";
|
||||
totalRow.appendChild(cell);
|
||||
});
|
||||
METRICS.forEach(function (metric) {
|
||||
var value = totals.weights[metric] ? totals.scores[metric] / totals.weights[metric] : null;
|
||||
var baseValue = totals.baselineWeights[metric]
|
||||
? totals.baseline[metric] / totals.baselineWeights[metric] : null;
|
||||
scoreCell(totalRow, value, baseValue);
|
||||
});
|
||||
usageCell(
|
||||
totalRow,
|
||||
totals.time_s != null ? totals.time_s : null,
|
||||
totals.baseline_time_s != null ? totals.baseline_time_s : null,
|
||||
fmtDuration
|
||||
);
|
||||
usageCell(
|
||||
totalRow,
|
||||
totals.cost != null ? totals.cost : null,
|
||||
totals.baseline_cost != null ? totals.baseline_cost : null,
|
||||
function (value) { return "$" + value.toFixed(2); },
|
||||
totals.tokens != null ? fmtTokens(totals.tokens) : null
|
||||
);
|
||||
table.appendChild(totalRow);
|
||||
}
|
||||
|
||||
body.appendChild(table);
|
||||
var note = document.createElement("p");
|
||||
note.className = "results-note";
|
||||
note.textContent = "Finished means the executor completed, not that cases passed. Scores exclude skipped or ungraded cases; inspect the per-case Phoenix comparison before drawing conclusions. Runs includes repetitions. Time is the sum of run latencies; cost uses Phoenix token prices.";
|
||||
note.textContent = "Scores are experiment means per dataset; answer_quality exists only where a judge ran. Comparisons require complete live runs with matching dataset versions, recorded case counts and scoring checks. Imported historical baselines remain viewable but are not compared. Overall includes only comparable datasets, weighs scores by their recorded case counts, and sums time/cost. Time and cost are shown per pass over the dataset, so a --runs 3 experiment is divided by 3. Time is the sum of run latencies; cost comes from Phoenix's token prices (imported baseline values are frozen at capture time).";
|
||||
body.appendChild(note);
|
||||
}
|
||||
|
||||
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
"""Structural checks for the eval runner page's inline script.
|
||||
|
||||
The backend CI image ships no JavaScript engine, so the page's script is
|
||||
checked here with a small tokenizer rather than ``node --check``. The checks
|
||||
are deliberately structural: balance, function extraction and call arity. No
|
||||
scope or type analysis is attempted.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
_STRING_QUOTES = "\"'"
|
||||
_REGEX_PRECEDING_CHARS = "(,=:[!&|?{};+-*/%<>~^"
|
||||
_REGEX_PRECEDING_WORDS = frozenset(
|
||||
{"return", "typeof", "case", "in", "of", "new", "delete", "void", "instanceof"}
|
||||
)
|
||||
_AFTER_LITERAL = "\x00"
|
||||
|
||||
_SCRIPT_RE = re.compile(r"<script>(?P<body>.*?)</script>", re.DOTALL)
|
||||
_FUNCTION_RE = re.compile(r"\b(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(")
|
||||
|
||||
|
||||
def inline_script(page: str) -> str:
|
||||
"""Return the body of the page's single inline ``<script>`` tag.
|
||||
|
||||
:param page: The rendered HTML page.
|
||||
:raises AssertionError: If the page does not hold exactly one script tag.
|
||||
:return: The script body, without the surrounding tags.
|
||||
"""
|
||||
|
||||
scripts = _SCRIPT_RE.findall(page)
|
||||
assert len(scripts) == 1, (
|
||||
f"expected exactly one inline script, found {len(scripts)}"
|
||||
)
|
||||
return scripts[0]
|
||||
|
||||
|
||||
def _blank_span(source: str) -> str:
|
||||
return "".join(character if character == "\n" else " " for character in source)
|
||||
|
||||
|
||||
def _regex_can_start(previous: str, blanked_so_far: str) -> bool:
|
||||
if previous == _AFTER_LITERAL:
|
||||
return False
|
||||
if previous == "" or previous in _REGEX_PRECEDING_CHARS:
|
||||
return True
|
||||
word = re.search(r"([A-Za-z_$][\w$]*)\s*$", blanked_so_far)
|
||||
return bool(word) and word.group(1) in _REGEX_PRECEDING_WORDS
|
||||
|
||||
|
||||
def _template_end(source: str, start: int) -> int:
|
||||
"""Find the offset just past a template literal, spanning ``${}`` parts.
|
||||
|
||||
:param source: JavaScript source.
|
||||
:param start: Offset of the opening backtick.
|
||||
:return: Offset just past the closing backtick.
|
||||
"""
|
||||
|
||||
index = start + 1
|
||||
length = len(source)
|
||||
depth = 0
|
||||
while index < length:
|
||||
character = source[index]
|
||||
if character == "\\":
|
||||
index += 2
|
||||
continue
|
||||
if character == "`" and depth == 0:
|
||||
return index + 1
|
||||
if character == "`":
|
||||
index = _template_end(source, index)
|
||||
continue
|
||||
if character == "$" and source[index : index + 2] == "${":
|
||||
depth += 1
|
||||
index += 2
|
||||
continue
|
||||
if character == "{" and depth:
|
||||
depth += 1
|
||||
elif character == "}" and depth:
|
||||
depth -= 1
|
||||
index += 1
|
||||
return length
|
||||
|
||||
|
||||
def blank_literals(source: str) -> str:
|
||||
"""Replace comments, strings, templates and regex literals with spaces.
|
||||
|
||||
Offsets and line breaks are preserved so positions stay reportable.
|
||||
|
||||
:param source: JavaScript source.
|
||||
:return: The source with every literal blanked out.
|
||||
"""
|
||||
|
||||
out: list[str] = []
|
||||
index = 0
|
||||
length = len(source)
|
||||
previous = ""
|
||||
while index < length:
|
||||
character = source[index]
|
||||
following = source[index + 1] if index + 1 < length else ""
|
||||
if character == "/" and following == "/":
|
||||
end = source.find("\n", index)
|
||||
end = length if end == -1 else end
|
||||
elif character == "/" and following == "*":
|
||||
end = source.find("*/", index + 2)
|
||||
end = length if end == -1 else end + 2
|
||||
elif character == "`":
|
||||
end = _template_end(source, index)
|
||||
previous = _AFTER_LITERAL
|
||||
elif character in _STRING_QUOTES:
|
||||
end = index + 1
|
||||
while end < length:
|
||||
if source[end] == "\\":
|
||||
end += 2
|
||||
continue
|
||||
if source[end] == character:
|
||||
end += 1
|
||||
break
|
||||
end += 1
|
||||
previous = _AFTER_LITERAL
|
||||
elif character == "/" and _regex_can_start(previous, "".join(out[-40:])):
|
||||
end = index + 1
|
||||
in_class = False
|
||||
while end < length:
|
||||
current = source[end]
|
||||
if current == "\\":
|
||||
end += 2
|
||||
continue
|
||||
if current == "\n":
|
||||
break
|
||||
if current == "[":
|
||||
in_class = True
|
||||
elif current == "]":
|
||||
in_class = False
|
||||
elif current == "/" and not in_class:
|
||||
end += 1
|
||||
break
|
||||
end += 1
|
||||
previous = _AFTER_LITERAL
|
||||
else:
|
||||
out.append(character)
|
||||
if not character.isspace():
|
||||
previous = character
|
||||
index += 1
|
||||
continue
|
||||
out.append(_blank_span(source[index:end]))
|
||||
index = end
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _line_of(source: str, offset: int) -> int:
|
||||
return source.count("\n", 0, offset) + 1
|
||||
|
||||
|
||||
def _matching_brace(blanked: str, opening: int) -> int | None:
|
||||
depth = 0
|
||||
for offset in range(opening, len(blanked)):
|
||||
if blanked[offset] == "{":
|
||||
depth += 1
|
||||
elif blanked[offset] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return offset + 1
|
||||
return None
|
||||
|
||||
|
||||
def declared_functions(source: str) -> list[str]:
|
||||
"""List every named function declared in the script, in source order.
|
||||
|
||||
:param source: JavaScript source.
|
||||
:return: The declared function names, with duplicates preserved.
|
||||
"""
|
||||
|
||||
return _FUNCTION_RE.findall(blank_literals(source))
|
||||
|
||||
|
||||
def brace_problems(source: str) -> list[str]:
|
||||
"""Report brace imbalance, and refuse to pass on a script it cannot read.
|
||||
|
||||
:param source: JavaScript source.
|
||||
:return: One message per problem, empty when the source is well-formed.
|
||||
"""
|
||||
|
||||
blanked = blank_literals(source)
|
||||
problems: list[str] = []
|
||||
depth = 0
|
||||
for offset, character in enumerate(blanked):
|
||||
if character == "{":
|
||||
depth += 1
|
||||
elif character == "}":
|
||||
depth -= 1
|
||||
if depth < 0:
|
||||
problems.append(f"line {_line_of(source, offset)}: unmatched '}}'")
|
||||
depth = 0
|
||||
if depth != 0:
|
||||
problems.append(f"{depth} brace(s) never closed; the script cannot parse")
|
||||
if not _FUNCTION_RE.search(blanked):
|
||||
problems.append("no function declarations found; the checker cannot read this")
|
||||
return problems
|
||||
|
||||
|
||||
def function_body(source: str, name: str) -> str:
|
||||
"""Return the body of a named function, braces included.
|
||||
|
||||
:param source: JavaScript source.
|
||||
:param name: The declared function name.
|
||||
:raises AssertionError: If the function is absent or never closed.
|
||||
:return: The function body from its opening brace to its closing brace.
|
||||
"""
|
||||
|
||||
blanked = blank_literals(source)
|
||||
match = re.search(rf"\b(?:async\s+)?function\s+{re.escape(name)}\s*\(", blanked)
|
||||
assert match, f"no function named {name}"
|
||||
opening = blanked.find("{", match.end())
|
||||
end = _matching_brace(blanked, opening) if opening != -1 else None
|
||||
assert end is not None, f"function {name} is never closed"
|
||||
return source[opening:end]
|
||||
|
||||
|
||||
def call_arguments(source: str, name: str) -> list[list[str]]:
|
||||
"""Split the top-level arguments of every call to a named function.
|
||||
|
||||
:param source: JavaScript source.
|
||||
:param name: The called function name.
|
||||
:return: One list of argument expressions per call site.
|
||||
"""
|
||||
|
||||
blanked = blank_literals(source)
|
||||
calls: list[list[str]] = []
|
||||
for match in re.finditer(rf"(?<![\w$.]){re.escape(name)}\s*\(", blanked):
|
||||
preceding = blanked[: match.start()].rstrip()
|
||||
if preceding.endswith("function"):
|
||||
continue
|
||||
opening = match.end() - 1
|
||||
depth = 0
|
||||
arguments: list[str] = []
|
||||
start = opening + 1
|
||||
for offset in range(opening, len(blanked)):
|
||||
character = blanked[offset]
|
||||
if character in "([{":
|
||||
depth += 1
|
||||
elif character in ")]}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
arguments.append(source[start:offset])
|
||||
break
|
||||
elif character == "," and depth == 1:
|
||||
arguments.append(source[start:offset])
|
||||
start = offset + 1
|
||||
calls.append([argument.strip() for argument in arguments if argument.strip()])
|
||||
return calls
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
"""Saved workflow checks tolerate rejected and repaired model requests."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from pydantic_ai.messages import (
|
||||
ModelRequest,
|
||||
ModelResponse,
|
||||
RetryPromptPart,
|
||||
ToolCallPart,
|
||||
ToolReturnPart,
|
||||
)
|
||||
|
||||
from baserow.contrib.integrations.local_baserow.models import (
|
||||
LocalBaserowTableServiceFieldMapping,
|
||||
)
|
||||
from baserow_enterprise.assistant.evals.datasets import automation
|
||||
from baserow_enterprise.assistant.evals.harness import format_message_history
|
||||
from baserow_enterprise.assistant.evals.types import EvalRunOutput
|
||||
|
||||
|
||||
def _output(workflow, rejected_first=True):
|
||||
rejected = [
|
||||
ModelResponse(
|
||||
parts=[
|
||||
ToolCallPart(
|
||||
"create_workflows",
|
||||
{"workflows": [{"name": "Rejected", "nodes": None}]},
|
||||
tool_call_id="rejected",
|
||||
)
|
||||
]
|
||||
),
|
||||
ModelRequest(
|
||||
parts=[
|
||||
RetryPromptPart(
|
||||
"Invalid nodes",
|
||||
tool_name="create_workflows",
|
||||
tool_call_id="rejected",
|
||||
)
|
||||
]
|
||||
),
|
||||
]
|
||||
# InlineRefs repairs this payload before execution without changing the
|
||||
# original ToolCallPart. The return identifies the actually saved workflow.
|
||||
repaired = [
|
||||
ModelResponse(
|
||||
parts=[
|
||||
ToolCallPart(
|
||||
"create_workflows",
|
||||
{
|
||||
"workflows": [
|
||||
{"name": "Uncorrected", "trigger": None, "nodes": [None]}
|
||||
]
|
||||
},
|
||||
tool_call_id="repaired",
|
||||
)
|
||||
]
|
||||
),
|
||||
ModelRequest(
|
||||
parts=[
|
||||
ToolReturnPart(
|
||||
"create_workflows",
|
||||
{"created_workflows": [{"id": workflow.id, "name": workflow.name}]},
|
||||
tool_call_id="repaired",
|
||||
)
|
||||
]
|
||||
),
|
||||
]
|
||||
messages = rejected + repaired if rejected_first else repaired + rejected
|
||||
return EvalRunOutput(
|
||||
answer="Created the workflow.",
|
||||
messages=format_message_history(SimpleNamespace(all_messages=lambda: messages)),
|
||||
tool_calls=["create_workflows", "create_workflows"],
|
||||
tool_error_count=1,
|
||||
tool_error_hint="Invalid nodes",
|
||||
sources=[],
|
||||
request_count=1,
|
||||
duration_s=0,
|
||||
)
|
||||
|
||||
|
||||
def _save_workflow(data_fixture, scenario, kind):
|
||||
automation_app = scenario.refs["automation"]
|
||||
table = scenario.refs.get("table") or scenario.refs.get("source_table")
|
||||
schedule = {
|
||||
"interval": "WEEK",
|
||||
"day_of_week": 1,
|
||||
"hour": 9,
|
||||
"minute": 0,
|
||||
"timezone": "UTC",
|
||||
}
|
||||
workflow = data_fixture.create_automation_workflow(
|
||||
automation=automation_app,
|
||||
trigger_type="periodic"
|
||||
if kind == "weekly_slack_reminder"
|
||||
else "rows_updated"
|
||||
if kind == "update_row_workflow"
|
||||
else "rows_created",
|
||||
trigger_service_kwargs=schedule
|
||||
if kind == "weekly_slack_reminder"
|
||||
else {"table": table},
|
||||
)
|
||||
trigger = workflow.get_trigger()
|
||||
if kind == "weekly_slack_reminder":
|
||||
data_fixture.create_automation_node(
|
||||
workflow=workflow,
|
||||
type="slack_write_message",
|
||||
service_kwargs={
|
||||
"channel": "general",
|
||||
"text": "'Is there anything to demo this week?'",
|
||||
},
|
||||
)
|
||||
elif kind == "email_notification_workflow":
|
||||
data_fixture.create_automation_node(
|
||||
workflow=workflow,
|
||||
type="smtp_email",
|
||||
service_kwargs={
|
||||
"to_emails": "'admin@example.com'",
|
||||
"subject": "'New Order'",
|
||||
"body": "'A new order has been placed'",
|
||||
},
|
||||
)
|
||||
elif kind == "router_workflow":
|
||||
router = data_fixture.create_automation_node(workflow=workflow, type="router")
|
||||
router.service.specific.edges.all().delete()
|
||||
priority = table.field_set.get(name="Priority")
|
||||
high = data_fixture.create_core_router_service_edge(
|
||||
service=router.service.specific,
|
||||
label="High",
|
||||
order=1,
|
||||
condition=f"if(equal(get('previous_node.{trigger.id}[0].{priority.db_column}.value'), 'High'), 'true', 'false')",
|
||||
skip_output_node=True,
|
||||
)
|
||||
data_fixture.create_core_router_service_edge(
|
||||
service=router.service.specific,
|
||||
label="Low",
|
||||
order=2,
|
||||
condition=f"equal(get('previous_node.{trigger.id}[0].{priority.db_column}.value'), 'Low')",
|
||||
skip_output_node=True,
|
||||
)
|
||||
data_fixture.create_automation_node(
|
||||
workflow=workflow,
|
||||
type="slack_write_message",
|
||||
reference_node=router,
|
||||
output=high.uid,
|
||||
service_kwargs={
|
||||
"channel": "urgent",
|
||||
"text": "'High priority ticket created'",
|
||||
},
|
||||
)
|
||||
else:
|
||||
creating = kind == "row_with_field_values"
|
||||
target = scenario.refs["log_table"] if creating else table
|
||||
node = data_fixture.create_automation_node(
|
||||
workflow=workflow,
|
||||
type="create_row" if creating else "update_row",
|
||||
service_kwargs={
|
||||
"table": target,
|
||||
"row_id": ""
|
||||
if creating
|
||||
else f"get('previous_node.{trigger.id}[0].id')",
|
||||
},
|
||||
)
|
||||
values = {"Status": "'Processing'"}
|
||||
if creating:
|
||||
name = table.field_set.get(name="Name")
|
||||
values = {
|
||||
"Entry": f"get('previous_node.{trigger.id}[0].{name.db_column}')",
|
||||
"Source": "'automation'",
|
||||
}
|
||||
elif kind == "update_row_workflow":
|
||||
values = {
|
||||
"Status": "'Reviewed'",
|
||||
"Notes": "'Automatically reviewed by automation'",
|
||||
}
|
||||
for name, formula in values.items():
|
||||
LocalBaserowTableServiceFieldMapping.objects.create(
|
||||
service=node.service,
|
||||
field=target.field_set.get(name=name),
|
||||
value=formula,
|
||||
)
|
||||
return workflow
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize("rejected_first", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"kind",
|
||||
[
|
||||
"workflow",
|
||||
"update_row_workflow",
|
||||
"router_workflow",
|
||||
"email_notification_workflow",
|
||||
"row_with_field_values",
|
||||
"weekly_slack_reminder",
|
||||
],
|
||||
)
|
||||
def test_complete_workflow_survives_earlier_draft_and_rejected_or_repaired_history(
|
||||
data_fixture, kind, rejected_first
|
||||
):
|
||||
scenario = getattr(automation, f"_creates_{kind}_scenario")(data_fixture)
|
||||
data_fixture.create_automation_workflow(
|
||||
automation=scenario.refs["automation"], name="Incomplete draft"
|
||||
)
|
||||
workflow = _save_workflow(data_fixture, scenario, kind)
|
||||
checks = getattr(automation, f"_check_creates_{kind}")(
|
||||
None, scenario, _output(workflow, rejected_first)
|
||||
)
|
||||
assert all(check.passed for check in checks), checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_checks_do_not_combine_two_incomplete_workflows(data_fixture):
|
||||
scenario = automation._creates_weekly_slack_reminder_scenario(data_fixture)
|
||||
data_fixture.create_automation_workflow(
|
||||
automation=scenario.refs["automation"],
|
||||
trigger_type="periodic",
|
||||
trigger_service_kwargs={
|
||||
"interval": "WEEK",
|
||||
"day_of_week": 1,
|
||||
"hour": 9,
|
||||
"minute": 0,
|
||||
"timezone": "UTC",
|
||||
},
|
||||
)
|
||||
second = _save_workflow(data_fixture, scenario, "weekly_slack_reminder")
|
||||
periodic = second.get_trigger().service.specific
|
||||
periodic.day_of_week = 2
|
||||
periodic.save()
|
||||
checks = automation._check_creates_weekly_slack_reminder(
|
||||
None, scenario, _output(second)
|
||||
)
|
||||
assert not all(check.passed for check in checks), checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"defect", ["wrong_table", "disabled_status", "swapped_fields", "missing_notes"]
|
||||
)
|
||||
def test_update_checks_require_saved_named_mappings_and_target(data_fixture, defect):
|
||||
scenario = automation._creates_update_row_workflow_scenario(data_fixture)
|
||||
workflow = _save_workflow(data_fixture, scenario, "update_row_workflow")
|
||||
node = workflow.automation_workflow_nodes.get(
|
||||
content_type__model="localbaserowupdaterowactionnode"
|
||||
)
|
||||
service = node.service.specific
|
||||
if defect == "wrong_table":
|
||||
service.table = data_fixture.create_database_table(
|
||||
database=scenario.refs["table"].database
|
||||
)
|
||||
service.save()
|
||||
elif defect == "disabled_status":
|
||||
service.field_mappings.filter(field__name="Status").update(enabled=False)
|
||||
elif defect == "missing_notes":
|
||||
service.field_mappings.filter(field__name="Notes").delete()
|
||||
else:
|
||||
status, notes = [
|
||||
service.field_mappings.get(field__name=name) for name in ("Status", "Notes")
|
||||
]
|
||||
status.value, notes.value = notes.value, status.value
|
||||
status.save()
|
||||
notes.save()
|
||||
checks = automation._check_creates_update_row_workflow(
|
||||
None, scenario, _output(workflow)
|
||||
)
|
||||
assert not all(check.passed for check in checks), checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"defect",
|
||||
[
|
||||
"reversed_condition",
|
||||
"malformed_later_edge",
|
||||
"low_branch_action",
|
||||
"channel",
|
||||
"message",
|
||||
],
|
||||
)
|
||||
def test_router_check_uses_saved_conditions_and_branch_message(data_fixture, defect):
|
||||
scenario = automation._creates_router_workflow_scenario(data_fixture)
|
||||
workflow = _save_workflow(data_fixture, scenario, "router_workflow")
|
||||
router = workflow.automation_workflow_nodes.get(
|
||||
content_type__model="corerouteractionnode"
|
||||
)
|
||||
slack = workflow.automation_workflow_nodes.get(
|
||||
content_type__model="slackwritemessageactionnode"
|
||||
).service.specific
|
||||
if defect == "reversed_condition":
|
||||
edge = router.service.specific.edges.get(label="High")
|
||||
edge.condition = "false"
|
||||
edge.save()
|
||||
elif defect == "malformed_later_edge":
|
||||
data_fixture.create_core_router_service_edge(
|
||||
service=router.service.specific,
|
||||
label="Invalid later condition",
|
||||
order=3,
|
||||
condition="invalid_function()",
|
||||
skip_output_node=True,
|
||||
)
|
||||
elif defect == "low_branch_action":
|
||||
edge = router.service.specific.edges.get(label="Low")
|
||||
data_fixture.create_automation_node(
|
||||
workflow=workflow,
|
||||
type="slack_write_message",
|
||||
reference_node=router,
|
||||
output=edge.uid,
|
||||
)
|
||||
else:
|
||||
if defect == "channel":
|
||||
slack.channel = "urgent-other"
|
||||
else:
|
||||
slack.text = "'An unrelated message'"
|
||||
slack.save()
|
||||
checks = automation._check_creates_router_workflow(
|
||||
None, scenario, _output(workflow)
|
||||
)
|
||||
assert not all(check.passed for check in checks), checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"field,value",
|
||||
[
|
||||
("to_emails", "other@example.com"),
|
||||
("subject", "Other order"),
|
||||
("body", "The order was cancelled"),
|
||||
],
|
||||
)
|
||||
def test_email_check_uses_saved_recipient_subject_and_body(data_fixture, field, value):
|
||||
scenario = automation._creates_email_notification_workflow_scenario(data_fixture)
|
||||
workflow = _save_workflow(data_fixture, scenario, "email_notification_workflow")
|
||||
service = workflow.automation_workflow_nodes.get(
|
||||
content_type__model="coresmtpemailactionnode"
|
||||
).service.specific
|
||||
setattr(service, field, repr(value))
|
||||
service.save()
|
||||
checks = automation._check_creates_email_notification_workflow(
|
||||
None, scenario, _output(workflow)
|
||||
)
|
||||
assert not all(check.passed for check in checks), checks
|
||||
+477
-24
@@ -1,9 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from contextlib import contextmanager
|
||||
from unittest.mock import patch
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from phoenix.client import Client
|
||||
|
||||
from baserow_enterprise.assistant.evals import baseline, registry
|
||||
from baserow_enterprise.assistant.evals.baseline import (
|
||||
@@ -33,6 +36,12 @@ def _baseline_file(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(baseline, "BASELINE_PATH", tmp_path / "baseline.json")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def import_metadata_patch():
|
||||
with patch.object(baseline.httpx, "patch") as request:
|
||||
yield request
|
||||
|
||||
|
||||
class _FakeDataset:
|
||||
def __init__(self, examples):
|
||||
self.id = "ds-1"
|
||||
@@ -45,13 +54,28 @@ class _FakeExperimentsAPI:
|
||||
self.create_calls: list[dict] = []
|
||||
self.log_run_calls: list[dict] = []
|
||||
self.log_evaluation_calls: list[dict] = []
|
||||
self.records: list[dict] = []
|
||||
|
||||
def list(self, **kwargs):
|
||||
return list(self.records)
|
||||
|
||||
def create(self, **kwargs):
|
||||
self.create_calls.append(kwargs)
|
||||
return {"id": "exp-baseline"}
|
||||
record = {
|
||||
"id": f"exp-baseline-{len(self.create_calls)}",
|
||||
"name": kwargs["experiment_name"],
|
||||
"dataset_version_id": kwargs["dataset_version_id"],
|
||||
"metadata": dict(kwargs["experiment_metadata"]),
|
||||
"successful_run_count": 0,
|
||||
}
|
||||
self.records.append(record)
|
||||
return record
|
||||
|
||||
def log_run(self, **kwargs):
|
||||
self.log_run_calls.append(kwargs)
|
||||
next(
|
||||
record for record in self.records if record["id"] == kwargs["experiment_id"]
|
||||
)["successful_run_count"] += 1
|
||||
return {"id": f"run-{len(self.log_run_calls)}"}
|
||||
|
||||
def log_evaluation(self, **kwargs):
|
||||
@@ -68,6 +92,23 @@ class _FakeClient:
|
||||
return self._dataset
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _sdk_client(handler):
|
||||
"""Exercise Phoenix's real SDK and the direct requests at their HTTP boundary."""
|
||||
|
||||
with (
|
||||
httpx.Client(
|
||||
base_url="http://phoenix.test", transport=httpx.MockTransport(handler)
|
||||
) as http,
|
||||
patch.object(baseline.httpx, "get", side_effect=http.get),
|
||||
patch.object(baseline.httpx, "post", side_effect=http.post),
|
||||
patch.object(baseline.httpx, "patch", side_effect=http.patch),
|
||||
):
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
client.experiments = Client(http_client=http).experiments
|
||||
yield client
|
||||
|
||||
|
||||
_CODE_EXAMPLE = {
|
||||
"id": "database/list-tables",
|
||||
"node_id": "node-1",
|
||||
@@ -91,7 +132,15 @@ class TestCaptureBaseline:
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
rest = {
|
||||
"/v1/datasets/ds-1/experiments": [
|
||||
{"id": "exp-2", "name": "latest", "metadata": {"model": "m"}},
|
||||
{
|
||||
"id": "exp-2",
|
||||
"name": "latest",
|
||||
"metadata": {
|
||||
"model": "m",
|
||||
"harness_version": 4,
|
||||
"evaluator_source_hash": "checks-v4",
|
||||
},
|
||||
},
|
||||
{"id": "exp-1", "name": "older", "metadata": {}},
|
||||
],
|
||||
"/v1/experiments/exp-2/runs": [
|
||||
@@ -106,6 +155,7 @@ class TestCaptureBaseline:
|
||||
"total_cost": 0.05,
|
||||
"total_tokens": 120000,
|
||||
}
|
||||
client.experiments.records = rest["/v1/datasets/ds-1/experiments"]
|
||||
with (
|
||||
patch.object(baseline, "_get", side_effect=lambda path: rest[path]),
|
||||
patch.object(
|
||||
@@ -125,22 +175,61 @@ class TestCaptureBaseline:
|
||||
assert run["case_id"] == "database/list-tables"
|
||||
assert run["annotations"] == [{"name": "passed", "score": 1.0}]
|
||||
assert dataset_entry["totals"] == totals
|
||||
assert dataset_entry["metadata"]["harness_version"] == 4
|
||||
assert dataset_entry["metadata"]["evaluator_source_hash"] == "checks-v4"
|
||||
captured_hash = baseline._snapshot_hash(snapshot)
|
||||
dataset_entry["metadata"]["evaluator_source_hash"] = "changed-checks"
|
||||
assert baseline._snapshot_hash(snapshot) != captured_hash
|
||||
|
||||
def test_experiment_name_filter_and_missing_experiment(self):
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
rest = {
|
||||
"/v1/datasets/ds-1/experiments": [
|
||||
{"id": "exp-2", "name": "other", "metadata": {}},
|
||||
],
|
||||
}
|
||||
|
||||
with patch.object(baseline, "_get", side_effect=lambda path: rest[path]):
|
||||
results = capture_baseline(client, experiment_name="baseline-candidate")
|
||||
client.experiments.records = [
|
||||
{"id": "exp-2", "name": "other", "metadata": {}},
|
||||
]
|
||||
results = capture_baseline(client, experiment_name="baseline-candidate")
|
||||
|
||||
assert results["kuma-database"] == "no matching experiment"
|
||||
snapshot = json.loads(baseline.BASELINE_PATH.read_text())
|
||||
assert snapshot["datasets"] == {}
|
||||
|
||||
@pytest.mark.parametrize("error", ["Provider unavailable", ""])
|
||||
def test_errored_run_does_not_replace_snapshot(self, error):
|
||||
original = json.dumps(_snapshot([_snapshot_run()]))
|
||||
baseline.BASELINE_PATH.write_text(original)
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
client.experiments.records = [{"id": "exp-1", "name": "candidate"}]
|
||||
failed_run = {**_run_payload(), "output": None, "error": error}
|
||||
|
||||
with patch.object(baseline, "_get", return_value=[failed_run]):
|
||||
with pytest.raises(ValueError, match="exp-1.*database/list-tables"):
|
||||
capture_baseline(client)
|
||||
|
||||
assert baseline.BASELINE_PATH.read_text() == original
|
||||
|
||||
def test_scored_model_failure_can_be_captured(self):
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
client.experiments.records = [{"id": "exp-1", "name": "candidate"}]
|
||||
failed_model_run = {
|
||||
**_run_payload(),
|
||||
"output": {"passed": False, "score": 0.0},
|
||||
"error": None,
|
||||
}
|
||||
with (
|
||||
patch.object(baseline, "_get", return_value=[failed_model_run]),
|
||||
patch.object(
|
||||
baseline,
|
||||
"_run_annotations",
|
||||
return_value=[{"name": "passed", "score": 0.0}],
|
||||
),
|
||||
patch.object(baseline, "_experiment_totals", return_value={}),
|
||||
):
|
||||
capture_baseline(client)
|
||||
|
||||
saved = json.loads(baseline.BASELINE_PATH.read_text())
|
||||
run = saved["datasets"]["kuma-database"]["runs"][0]
|
||||
assert run["output"] == failed_model_run["output"]
|
||||
assert run["annotations"] == [{"name": "passed", "score": 0.0}]
|
||||
|
||||
|
||||
def _snapshot(runs):
|
||||
return {
|
||||
@@ -167,25 +256,120 @@ def _snapshot_run(case_id="database/list-tables"):
|
||||
}
|
||||
|
||||
|
||||
def _persist_import_requests(monkeypatch, client, import_metadata_patch):
|
||||
"""Keep the fake Phoenix state across import attempts and restarts."""
|
||||
|
||||
deleted_ids = []
|
||||
|
||||
def update(url, *, json, **kwargs):
|
||||
experiment_id = url.rsplit("/", 1)[-1]
|
||||
next(
|
||||
record
|
||||
for record in client.experiments.records
|
||||
if record["id"] == experiment_id
|
||||
)["metadata"] = json["metadata"]
|
||||
return import_metadata_patch.return_value
|
||||
|
||||
def delete(experiment_ids):
|
||||
deleted_ids.extend(experiment_ids)
|
||||
client.experiments.records[:] = [
|
||||
record
|
||||
for record in client.experiments.records
|
||||
if record["id"] not in experiment_ids
|
||||
]
|
||||
|
||||
monkeypatch.setattr(baseline, "_delete_experiments", delete)
|
||||
import_metadata_patch.side_effect = update
|
||||
return deleted_ids
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["capture", "import"])
|
||||
def test_baseline_finds_experiments_beyond_first_page(action):
|
||||
snapshot = _snapshot([_snapshot_run()])
|
||||
baseline.BASELINE_PATH.write_text(json.dumps(snapshot))
|
||||
recent = [
|
||||
{"id": f"live-{i}", "name": f"candidate-{i}", "metadata": {}} for i in range(50)
|
||||
]
|
||||
older = [
|
||||
{
|
||||
"id": "current-import",
|
||||
"name": "baseline (imported)",
|
||||
"dataset_version_id": "v1",
|
||||
"metadata": {
|
||||
"baseline_snapshot_hash": baseline._snapshot_hash(snapshot),
|
||||
"baseline_import_complete": True,
|
||||
},
|
||||
"successful_run_count": 1,
|
||||
},
|
||||
{
|
||||
"id": "obsolete-import",
|
||||
"name": "baseline (imported)",
|
||||
"metadata": {"baseline_snapshot_hash": "previous"},
|
||||
},
|
||||
]
|
||||
cursors = []
|
||||
deleted = []
|
||||
|
||||
def respond(request):
|
||||
if request.url.path == "/v1/datasets/ds-1/experiments":
|
||||
assert request.method == "GET"
|
||||
cursor = request.url.params.get("cursor")
|
||||
cursors.append(cursor)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"data": older if cursor else recent,
|
||||
"next_cursor": None if cursor else "older",
|
||||
},
|
||||
)
|
||||
if request.url.path == "/v1/experiments/current-import/runs":
|
||||
return httpx.Response(200, json={"data": [_run_payload()]})
|
||||
if request.url.path == "/graphql":
|
||||
body = json.loads(request.content)
|
||||
deleted.extend(body["variables"]["ids"])
|
||||
return httpx.Response(200, json={"data": {}})
|
||||
raise AssertionError((request.method, request.url.path))
|
||||
|
||||
with (
|
||||
_sdk_client(respond) as client,
|
||||
patch.object(baseline, "_run_annotations", return_value=[]),
|
||||
patch.object(baseline, "_experiment_totals", return_value={}),
|
||||
):
|
||||
if action == "capture":
|
||||
result = capture_baseline(client, experiment_name="baseline (imported)")
|
||||
assert (
|
||||
result["kuma-database"] == "captured 1 runs from 'baseline (imported)'"
|
||||
)
|
||||
saved = json.loads(baseline.BASELINE_PATH.read_text())
|
||||
assert len(saved["datasets"]["kuma-database"]["runs"]) == 1
|
||||
assert deleted == []
|
||||
else:
|
||||
assert import_baseline(client)["kuma-database"] == "already imported"
|
||||
assert deleted == ["obsolete-import"]
|
||||
assert cursors == [None, "older"]
|
||||
|
||||
|
||||
class TestImportBaseline:
|
||||
def test_no_snapshot_file(self):
|
||||
assert import_baseline(_FakeClient([])) == {
|
||||
"status": "no baseline snapshot committed"
|
||||
}
|
||||
|
||||
def test_imports_runs_and_evaluations_and_skips_removed_cases(self):
|
||||
def test_imports_runs_and_evaluations_and_skips_removed_cases(
|
||||
self, import_metadata_patch
|
||||
):
|
||||
baseline.BASELINE_PATH.write_text(
|
||||
json.dumps(_snapshot([_snapshot_run(), _snapshot_run("database/gone")]))
|
||||
)
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
|
||||
with patch.object(baseline, "_get", return_value=[]):
|
||||
results = import_baseline(client)
|
||||
results = import_baseline(client)
|
||||
|
||||
assert results["kuma-database"] == "imported 1 runs (1 removed cases skipped)"
|
||||
create = client.experiments.create_calls[0]
|
||||
assert create["experiment_name"] == "baseline"
|
||||
assert create["experiment_name"] == "baseline (imported)"
|
||||
assert create["experiment_metadata"]["baseline"] is True
|
||||
assert create["experiment_metadata"]["baseline_import_complete"] is False
|
||||
assert create["experiment_metadata"]["model"] == "m"
|
||||
assert create["experiment_metadata"]["baseline_totals"] == {
|
||||
"total_cost": 0.05,
|
||||
@@ -193,8 +377,18 @@ class TestImportBaseline:
|
||||
}
|
||||
assert client.experiments.log_run_calls[0]["dataset_example_id"] == "node-1"
|
||||
assert client.experiments.log_evaluation_calls[0]["name"] == "passed"
|
||||
assert import_metadata_patch.call_args.args[0].endswith(
|
||||
"/v1/experiments/exp-baseline-1"
|
||||
)
|
||||
assert import_metadata_patch.call_args.kwargs["json"] == {
|
||||
"metadata": {
|
||||
**create["experiment_metadata"],
|
||||
"baseline_import_complete": True,
|
||||
}
|
||||
}
|
||||
import_metadata_patch.return_value.raise_for_status.assert_called_once_with()
|
||||
|
||||
def test_import_supersedes_stale_named_baseline_experiments(self):
|
||||
def test_import_replaces_only_owned_experiments_regardless_of_name(self):
|
||||
baseline.BASELINE_PATH.write_text(json.dumps(_snapshot([_snapshot_run()])))
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
existing = [
|
||||
@@ -203,16 +397,27 @@ class TestImportBaseline:
|
||||
"name": "baseline",
|
||||
"metadata": {"baseline_snapshot_hash": "oldhash123456"},
|
||||
"successful_run_count": 1,
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "renamed-import",
|
||||
"name": "old saved import",
|
||||
"metadata": {"baseline_snapshot_hash": "olderhash"},
|
||||
},
|
||||
{"id": "live-baseline", "name": "baseline", "metadata": {}},
|
||||
{
|
||||
"id": "live-import-name",
|
||||
"name": "baseline (imported)",
|
||||
"metadata": {},
|
||||
},
|
||||
]
|
||||
|
||||
with (
|
||||
patch.object(baseline, "_get", return_value=existing),
|
||||
patch.object(client.experiments, "list", return_value=existing),
|
||||
patch.object(baseline, "_delete_experiments") as mock_delete,
|
||||
):
|
||||
results = import_baseline(client)
|
||||
|
||||
mock_delete.assert_called_once_with(["exp-old-baseline"])
|
||||
mock_delete.assert_called_once_with(["exp-old-baseline", "renamed-import"])
|
||||
assert results["kuma-database"] == "imported 1 runs"
|
||||
|
||||
def test_import_is_idempotent_by_snapshot_hash(self):
|
||||
@@ -222,12 +427,18 @@ class TestImportBaseline:
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
existing = [
|
||||
{
|
||||
"metadata": {"baseline_snapshot_hash": content_hash},
|
||||
"id": "current-import",
|
||||
"name": "baseline (imported)",
|
||||
"dataset_version_id": "v1",
|
||||
"metadata": {
|
||||
"baseline_snapshot_hash": content_hash,
|
||||
"baseline_import_complete": True,
|
||||
},
|
||||
"successful_run_count": 1,
|
||||
}
|
||||
]
|
||||
|
||||
with patch.object(baseline, "_get", return_value=existing):
|
||||
with patch.object(client.experiments, "list", return_value=existing):
|
||||
results = import_baseline(client)
|
||||
|
||||
assert results["kuma-database"] == "already imported"
|
||||
@@ -240,16 +451,226 @@ class TestImportBaseline:
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
existing = [
|
||||
{
|
||||
"metadata": {"baseline_snapshot_hash": content_hash},
|
||||
"id": "incomplete-import",
|
||||
"name": "baseline (imported)",
|
||||
"dataset_version_id": "v1",
|
||||
"metadata": {
|
||||
"baseline_snapshot_hash": content_hash,
|
||||
"baseline_import_complete": False,
|
||||
},
|
||||
"successful_run_count": 0,
|
||||
}
|
||||
]
|
||||
|
||||
with patch.object(baseline, "_get", return_value=existing):
|
||||
with (
|
||||
patch.object(client.experiments, "list", return_value=existing),
|
||||
patch.object(baseline, "_delete_experiments") as mock_delete,
|
||||
):
|
||||
results = import_baseline(client)
|
||||
|
||||
assert results["kuma-database"] == "imported 1 runs"
|
||||
assert len(client.experiments.create_calls) == 1
|
||||
mock_delete.assert_called_once_with(["incomplete-import"])
|
||||
|
||||
def test_removed_cases_do_not_repeat_import_or_replace_a_live_baseline(
|
||||
self, monkeypatch, import_metadata_patch
|
||||
):
|
||||
baseline.BASELINE_PATH.write_text(
|
||||
json.dumps(_snapshot([_snapshot_run(), _snapshot_run("database/gone")]))
|
||||
)
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
live = {"id": "live-baseline", "name": "baseline", "metadata": {}}
|
||||
client.experiments.records.append(live)
|
||||
deleted = _persist_import_requests(monkeypatch, client, import_metadata_patch)
|
||||
|
||||
first = import_baseline(client)
|
||||
second = import_baseline(client)
|
||||
|
||||
assert first["kuma-database"] == "imported 1 runs (1 removed cases skipped)"
|
||||
assert second["kuma-database"] == "already imported"
|
||||
assert len(client.experiments.create_calls) == 1
|
||||
assert deleted == []
|
||||
assert [record["name"] for record in client.experiments.records] == [
|
||||
"baseline",
|
||||
"baseline (imported)",
|
||||
]
|
||||
assert client.experiments.records[0] == live
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name, version, complete",
|
||||
[("baseline", "v1", None), ("baseline (imported)", "old-version", True)],
|
||||
ids=("legacy-name", "changed-dataset-version"),
|
||||
)
|
||||
def test_replaces_legacy_or_outdated_import_even_with_matching_snapshot_hash(
|
||||
self, monkeypatch, import_metadata_patch, name, version, complete
|
||||
):
|
||||
snapshot = _snapshot([_snapshot_run()])
|
||||
baseline.BASELINE_PATH.write_text(json.dumps(snapshot))
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
client.experiments.records.append(
|
||||
{
|
||||
"id": "previous-import",
|
||||
"name": name,
|
||||
"dataset_version_id": version,
|
||||
"metadata": {
|
||||
"baseline_snapshot_hash": baseline._snapshot_hash(snapshot),
|
||||
"baseline_import_complete": complete,
|
||||
},
|
||||
"successful_run_count": 1,
|
||||
}
|
||||
)
|
||||
deleted = _persist_import_requests(monkeypatch, client, import_metadata_patch)
|
||||
|
||||
result = import_baseline(client)
|
||||
|
||||
assert result["kuma-database"] == "imported 1 runs"
|
||||
assert deleted == ["previous-import"]
|
||||
assert client.experiments.records[0]["name"] == "baseline (imported)"
|
||||
assert client.experiments.records[0]["dataset_version_id"] == "v1"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"failure_path, status, cleanup_fails",
|
||||
[
|
||||
("/runs", 409, False),
|
||||
("/v1/experiment_evaluations", 503, False),
|
||||
("completion", 503, False),
|
||||
("completion", 503, True),
|
||||
],
|
||||
ids=("run-conflict", "annotation", "completion", "cleanup-also-fails"),
|
||||
)
|
||||
def test_failed_import_preserves_old_results_and_can_retry(
|
||||
self, failure_path, status, cleanup_fails
|
||||
):
|
||||
baseline.BASELINE_PATH.write_text(json.dumps(_snapshot([_snapshot_run()])))
|
||||
previous = {
|
||||
"live-baseline": {
|
||||
"id": "live-baseline",
|
||||
"name": "baseline",
|
||||
"metadata": {},
|
||||
},
|
||||
"previous-import": {
|
||||
"id": "previous-import",
|
||||
"name": "baseline (imported)",
|
||||
"metadata": {"baseline_snapshot_hash": "previous-snapshot"},
|
||||
},
|
||||
}
|
||||
records = dict(previous)
|
||||
created = 0
|
||||
fail = True
|
||||
|
||||
def respond(request):
|
||||
nonlocal created
|
||||
path = request.url.path
|
||||
body = json.loads(request.content) if request.content else {}
|
||||
if path == "/v1/datasets/ds-1/experiments":
|
||||
if request.method == "GET":
|
||||
return httpx.Response(200, json={"data": list(records.values())})
|
||||
created += 1
|
||||
record = {
|
||||
"id": f"new-{created}",
|
||||
"name": body["name"],
|
||||
"dataset_version_id": body["version_id"],
|
||||
"metadata": body["metadata"],
|
||||
"successful_run_count": 0,
|
||||
}
|
||||
records[record["id"]] = record
|
||||
return httpx.Response(200, json={"data": record})
|
||||
if request.method == "DELETE":
|
||||
experiment_id = path.rsplit("/", 1)[-1]
|
||||
assert experiment_id.startswith("new-")
|
||||
if cleanup_fails:
|
||||
return httpx.Response(502, json={"detail": "cleanup unavailable"})
|
||||
del records[experiment_id]
|
||||
return httpx.Response(204)
|
||||
if fail and (
|
||||
path.endswith(failure_path)
|
||||
or (failure_path == "completion" and request.method == "PATCH")
|
||||
):
|
||||
return httpx.Response(status, json={"detail": "original failure"})
|
||||
if path.endswith("/runs"):
|
||||
records[path.split("/")[3]]["successful_run_count"] += 1
|
||||
return httpx.Response(200, json={"data": {"id": "run-1"}})
|
||||
if path == "/v1/experiment_evaluations":
|
||||
return httpx.Response(200, json={"data": {"id": "evaluation-1"}})
|
||||
if request.method == "PATCH":
|
||||
records[path.rsplit("/", 1)[-1]]["metadata"] = body["metadata"]
|
||||
return httpx.Response(200, json={"data": {}})
|
||||
if path == "/graphql":
|
||||
for experiment_id in body["variables"]["ids"]:
|
||||
del records[experiment_id]
|
||||
return httpx.Response(200, json={"data": {}})
|
||||
raise AssertionError((request.method, path))
|
||||
|
||||
with (
|
||||
_sdk_client(respond) as client,
|
||||
patch.object(baseline.logger, "warning") as warning,
|
||||
):
|
||||
for _ in range(1 if cleanup_fails else 2):
|
||||
with pytest.raises(httpx.HTTPStatusError) as caught:
|
||||
import_baseline(client)
|
||||
assert caught.value.response.status_code == status
|
||||
assert caught.value.response.json()["detail"] == "original failure"
|
||||
assert {key: records[key] for key in previous} == previous
|
||||
if not cleanup_fails:
|
||||
assert records == previous
|
||||
if cleanup_fails:
|
||||
warning.assert_called_once()
|
||||
assert (
|
||||
"Could not delete failed baseline import"
|
||||
in warning.call_args.args[0]
|
||||
)
|
||||
|
||||
fail = False
|
||||
cleanup_fails = False
|
||||
assert import_baseline(client)["kuma-database"] == "imported 1 runs"
|
||||
assert set(records) == {"live-baseline", f"new-{created}"}
|
||||
assert records[f"new-{created}"]["metadata"]["baseline_import_complete"]
|
||||
assert import_baseline(client)["kuma-database"] == "already imported"
|
||||
|
||||
def test_retries_cleanup_without_reimporting_completed_results(
|
||||
self, monkeypatch, import_metadata_patch
|
||||
):
|
||||
baseline.BASELINE_PATH.write_text(json.dumps(_snapshot([_snapshot_run()])))
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
client.experiments.records.append(
|
||||
{
|
||||
"id": "previous-import",
|
||||
"name": "baseline",
|
||||
"metadata": {"baseline_snapshot_hash": "previous-snapshot"},
|
||||
}
|
||||
)
|
||||
deleted = _persist_import_requests(monkeypatch, client, import_metadata_patch)
|
||||
|
||||
with patch.object(
|
||||
baseline, "_delete_experiments", side_effect=RuntimeError("unavailable")
|
||||
):
|
||||
first = import_baseline(client)
|
||||
second = import_baseline(client)
|
||||
|
||||
assert first["kuma-database"] == "imported 1 runs"
|
||||
assert second["kuma-database"] == "already imported"
|
||||
assert len(client.experiments.create_calls) == 1
|
||||
assert deleted == ["previous-import"]
|
||||
|
||||
def test_no_applicable_cases_preserve_existing_experiments(self):
|
||||
baseline.BASELINE_PATH.write_text(json.dumps(_snapshot([_snapshot_run()])))
|
||||
client = _FakeClient([])
|
||||
|
||||
with (
|
||||
patch.object(client.experiments, "list") as mock_list,
|
||||
patch.object(baseline, "_delete_experiments") as mock_delete,
|
||||
):
|
||||
first = import_baseline(client)
|
||||
second = import_baseline(client)
|
||||
|
||||
assert (
|
||||
first
|
||||
== second
|
||||
== {"kuma-database": "no snapshot cases in the current dataset"}
|
||||
)
|
||||
assert client.experiments.create_calls == []
|
||||
mock_list.assert_not_called()
|
||||
mock_delete.assert_not_called()
|
||||
|
||||
def test_import_drops_no_result_annotations(self):
|
||||
run = _snapshot_run()
|
||||
@@ -259,8 +680,7 @@ class TestImportBaseline:
|
||||
baseline.BASELINE_PATH.write_text(json.dumps(_snapshot([run])))
|
||||
client = _FakeClient([_CODE_EXAMPLE])
|
||||
|
||||
with patch.object(baseline, "_get", return_value=[]):
|
||||
import_baseline(client)
|
||||
import_baseline(client)
|
||||
|
||||
logged = [call["name"] for call in client.experiments.log_evaluation_calls]
|
||||
assert logged == ["passed"]
|
||||
@@ -277,3 +697,36 @@ class TestImportBaseline:
|
||||
results = import_baseline(client)
|
||||
|
||||
assert results["kuma-database"] == "dataset not found in Phoenix"
|
||||
|
||||
|
||||
class TestDumpSnapshot:
|
||||
def test_round_trips_and_keeps_each_run_on_one_line(self):
|
||||
"""The one-line-per-run format caps the committed file's line count
|
||||
(a pretty-printed snapshot is ~20k diff lines) without losing data."""
|
||||
|
||||
snapshot = {
|
||||
"captured_at": "2026-09-02T00:00:00+00:00",
|
||||
"datasets": {
|
||||
"kuma-core": {
|
||||
"experiment_name": "run-x",
|
||||
"metadata": {"model": "m"},
|
||||
"totals": {"total_cost": 1.5},
|
||||
"runs": [
|
||||
{"case_id": "core/a", "output": {"answer": "hi\nthere"}},
|
||||
{"case_id": "core/b", "output": {}},
|
||||
],
|
||||
},
|
||||
"kuma-docs": {
|
||||
"experiment_name": None,
|
||||
"metadata": {},
|
||||
"totals": {},
|
||||
"runs": [],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
text = baseline._dump_snapshot(snapshot)
|
||||
|
||||
assert json.loads(text) == snapshot
|
||||
run_lines = [line for line in text.splitlines() if '"case_id"' in line]
|
||||
assert len(run_lines) == 2
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import pytest
|
||||
|
||||
from baserow.core.graph.types import GraphPointPosition
|
||||
from baserow_enterprise.assistant.evals.datasets.builder import (
|
||||
_changes_theme_scenario,
|
||||
_check_changes_theme,
|
||||
_check_creates_data_source_with_repeat,
|
||||
_check_creates_new_page_not_modifies_existing,
|
||||
_creates_data_source_with_repeat_scenario,
|
||||
_creates_new_page_not_modifies_existing_scenario,
|
||||
)
|
||||
from baserow_enterprise.assistant.evals.types import EvalRunOutput
|
||||
from baserow_enterprise.assistant.tools.builder.themes import apply_theme
|
||||
|
||||
|
||||
def _output(*calls):
|
||||
return EvalRunOutput(
|
||||
answer="Done",
|
||||
tool_calls=[name for name, _ in calls],
|
||||
messages=[
|
||||
{"role": "assistant", "tool_name": name, "args": args}
|
||||
for name, args in calls
|
||||
],
|
||||
tool_error_count=0,
|
||||
tool_error_hint="",
|
||||
sources=[],
|
||||
request_count=1,
|
||||
duration_s=0,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"defect",
|
||||
[
|
||||
None,
|
||||
"wrong_source",
|
||||
"wrong_table",
|
||||
"other_page",
|
||||
"no_service",
|
||||
"heading_outside",
|
||||
],
|
||||
)
|
||||
def test_repeat_check_uses_saved_binding_after_argument_repair(data_fixture, defect):
|
||||
scenario = _creates_data_source_with_repeat_scenario(data_fixture)
|
||||
builder, table = scenario.refs["builder"], scenario.refs["table"]
|
||||
page = data_fixture.create_builder_page(
|
||||
builder=builder, name="Products", path="/products"
|
||||
)
|
||||
other_page = data_fixture.create_builder_page(builder=builder, path="/other")
|
||||
other_table = data_fixture.create_database_table(database=table.database)
|
||||
source = data_fixture.create_builder_local_baserow_list_rows_data_source(
|
||||
page=other_page if defect == "other_page" else page,
|
||||
name="All Products",
|
||||
table=other_table if defect == "wrong_table" else table,
|
||||
)
|
||||
if defect == "no_service":
|
||||
source.service.delete()
|
||||
binding = source
|
||||
if defect == "wrong_source":
|
||||
binding = data_fixture.create_builder_local_baserow_list_rows_data_source(
|
||||
page=page,
|
||||
table=other_table,
|
||||
)
|
||||
repeat = data_fixture.create_builder_repeat_element(page=page, data_source=binding)
|
||||
data_fixture.create_builder_heading_element(
|
||||
page=page,
|
||||
value="'Product'",
|
||||
reference_element=repeat,
|
||||
position=GraphPointPosition.SOUTH
|
||||
if defect == "heading_outside"
|
||||
else GraphPointPosition.CHILD,
|
||||
)
|
||||
# Rejected/repaired requests are not a description of what was actually saved.
|
||||
output = _output(
|
||||
("create_pages", {}),
|
||||
("create_collection_elements", {"elements": None}),
|
||||
("setup_page", []),
|
||||
)
|
||||
checks = _check_creates_data_source_with_repeat(None, scenario, output)
|
||||
assert all(check.passed for check in checks) == (defect is None), checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize("saved_theme", ["midnight", "eclipse"])
|
||||
def test_theme_check_uses_saved_theme_after_argument_repair(data_fixture, saved_theme):
|
||||
scenario = _changes_theme_scenario(data_fixture)
|
||||
apply_theme(scenario.refs["builder"], saved_theme, scenario.user)
|
||||
checks = _check_changes_theme(None, scenario, _output(("set_theme", [])))
|
||||
assert all(check.passed for check in checks) == (saved_theme == "midnight"), checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_new_page_check_tolerates_repaired_argument_root(data_fixture):
|
||||
scenario = _creates_new_page_not_modifies_existing_scenario(data_fixture)
|
||||
page = data_fixture.create_builder_page(
|
||||
builder=scenario.refs["builder"], path="/new"
|
||||
)
|
||||
data_fixture.create_builder_heading_element(page=page)
|
||||
data_fixture.create_builder_text_element(page=page)
|
||||
checks = _check_creates_new_page_not_modifies_existing(
|
||||
None, scenario, _output(("create_pages", {}), ("setup_page", []))
|
||||
)
|
||||
assert all(check.passed for check in checks), checks
|
||||
+885
@@ -0,0 +1,885 @@
|
||||
"""Behavioral regressions for code checks, without calling a model."""
|
||||
|
||||
import pytest
|
||||
|
||||
from baserow.contrib.builder.pages.models import Page
|
||||
from baserow.contrib.integrations.local_baserow.models import (
|
||||
LocalBaserowTableServiceFieldMapping,
|
||||
)
|
||||
from baserow.core.graph.types import GraphPointPosition
|
||||
from baserow_enterprise.assistant.evals.datasets.automation import (
|
||||
_check_creates_row_with_field_values,
|
||||
_check_creates_update_row_workflow,
|
||||
_check_creates_weekly_slack_reminder,
|
||||
_check_creates_workflow,
|
||||
_creates_row_with_field_values_scenario,
|
||||
_creates_update_row_workflow_scenario,
|
||||
_creates_weekly_slack_reminder_scenario,
|
||||
_creates_workflow_scenario,
|
||||
)
|
||||
from baserow_enterprise.assistant.evals.datasets.builder import (
|
||||
_back_button_on_page_not_header_scenario,
|
||||
_check_asks_when_implied_table_missing,
|
||||
_check_back_button_on_page_not_header,
|
||||
_check_creates_app_when_table_exists,
|
||||
_check_creates_contact_form,
|
||||
_check_creates_landing_page,
|
||||
_check_filtered_data_source_via_view,
|
||||
_creates_app_when_table_exists_scenario,
|
||||
_creates_contact_form_scenario,
|
||||
_creates_landing_page_scenario,
|
||||
_filtered_data_source_via_view_scenario,
|
||||
_projects_table_missing_scenario,
|
||||
)
|
||||
from baserow_enterprise.assistant.evals.datasets.docs import _make_docs_checks
|
||||
from baserow_enterprise.assistant.evals.registry import get_case
|
||||
from baserow_enterprise.assistant.evals.types import EvalRunOutput
|
||||
|
||||
|
||||
def _output(**overrides):
|
||||
values = {
|
||||
"answer": "",
|
||||
"messages": [],
|
||||
"tool_calls": [],
|
||||
"tool_error_count": 0,
|
||||
"tool_error_hint": "",
|
||||
"sources": [],
|
||||
"request_count": 1,
|
||||
"duration_s": 0,
|
||||
}
|
||||
return EvalRunOutput(**(values | overrides))
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"defect",
|
||||
[
|
||||
None,
|
||||
"interval",
|
||||
"day_of_week",
|
||||
"hour",
|
||||
"minute",
|
||||
"timezone",
|
||||
"channel",
|
||||
"text",
|
||||
"blank_text",
|
||||
"missing_workflow",
|
||||
"missing_slack",
|
||||
"missing_call",
|
||||
],
|
||||
)
|
||||
def test_slack_reminder_check_uses_saved_schedule_and_message(data_fixture, defect):
|
||||
scenario = _creates_weekly_slack_reminder_scenario(data_fixture)
|
||||
schedule = {
|
||||
"interval": "WEEK",
|
||||
"day_of_week": 1,
|
||||
"hour": 9,
|
||||
"minute": 0,
|
||||
"timezone": "UTC",
|
||||
}
|
||||
wrong_schedule = {
|
||||
"interval": "DAY",
|
||||
"day_of_week": 2,
|
||||
"hour": 10,
|
||||
"minute": 30,
|
||||
"timezone": "Europe/Rome",
|
||||
}
|
||||
saved_schedule = schedule.copy()
|
||||
if defect in wrong_schedule:
|
||||
saved_schedule[defect] = wrong_schedule[defect]
|
||||
message = "Is there anything to demo this week?"
|
||||
if defect != "missing_workflow":
|
||||
workflow = data_fixture.create_automation_workflow(
|
||||
automation=scenario.refs["automation"],
|
||||
trigger_type="periodic",
|
||||
trigger_service_kwargs=saved_schedule,
|
||||
)
|
||||
if defect != "missing_slack":
|
||||
text = "Other demo message" if defect == "text" else message
|
||||
if defect == "blank_text":
|
||||
text = ""
|
||||
data_fixture.create_automation_node(
|
||||
workflow=workflow,
|
||||
type="slack_write_message",
|
||||
service_kwargs={
|
||||
"channel": "general-other" if defect == "channel" else "general",
|
||||
"text": f"'{text}'",
|
||||
},
|
||||
)
|
||||
|
||||
# The real argument fixer moved `body` to `text` before saving. Keep the
|
||||
# original model payload here, as recorded in the eval trace.
|
||||
output = _output(
|
||||
tool_calls=[] if defect == "missing_call" else ["create_workflows"],
|
||||
messages=[]
|
||||
if defect == "missing_call"
|
||||
else [
|
||||
{
|
||||
"role": "assistant",
|
||||
"tool_name": "create_workflows",
|
||||
"args": {
|
||||
"workflows": [
|
||||
{
|
||||
"trigger": {
|
||||
"type": "periodic",
|
||||
"periodic_interval": schedule,
|
||||
},
|
||||
"nodes": [
|
||||
{
|
||||
"type": "slack_write_message",
|
||||
"channel": "#general",
|
||||
"body" if defect is None else "text": message,
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
],
|
||||
)
|
||||
checks = _check_creates_weekly_slack_reminder(None, scenario, output)
|
||||
assert all(check.passed for check in checks) == (defect is None), checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"defect",
|
||||
[
|
||||
None,
|
||||
"wrong_trigger_table",
|
||||
"wrong_target_table",
|
||||
"update_row",
|
||||
"disabled",
|
||||
"constant_name",
|
||||
"wrong_source",
|
||||
"swapped_fields",
|
||||
],
|
||||
)
|
||||
def test_automation_row_check_uses_saved_configuration(data_fixture, defect):
|
||||
scenario = _creates_row_with_field_values_scenario(data_fixture)
|
||||
source, log = scenario.refs["source_table"], scenario.refs["log_table"]
|
||||
workflow = data_fixture.create_automation_workflow(
|
||||
automation=scenario.refs["automation"],
|
||||
trigger_type="rows_created",
|
||||
trigger_service_kwargs={
|
||||
"table": log if defect == "wrong_trigger_table" else source
|
||||
},
|
||||
)
|
||||
trigger = workflow.get_trigger()
|
||||
node = data_fixture.create_automation_node(
|
||||
workflow=workflow,
|
||||
type="create_row",
|
||||
service_kwargs={"table": source if defect == "wrong_target_table" else log},
|
||||
)
|
||||
service = node.service.specific
|
||||
if defect == "update_row":
|
||||
service.row_id = "1"
|
||||
service.save()
|
||||
name_field = source.field_set.get(name="Name")
|
||||
entry_field = log.field_set.get(name="Entry")
|
||||
source_field = log.field_set.get(name="Source")
|
||||
name_formula = f"get('previous_node.{trigger.id}[0].{name_field.db_column}')"
|
||||
LocalBaserowTableServiceFieldMapping.objects.create(
|
||||
service=service,
|
||||
field=source_field if defect == "swapped_fields" else entry_field,
|
||||
enabled=defect != "disabled",
|
||||
value="'Contact'" if defect == "constant_name" else name_formula,
|
||||
)
|
||||
LocalBaserowTableServiceFieldMapping.objects.create(
|
||||
service=service,
|
||||
field=entry_field if defect == "swapped_fields" else source_field,
|
||||
value="'manual'" if defect == "wrong_source" else "'automation'",
|
||||
)
|
||||
# The tool accepts registered aliases. The raw payload alone cannot prove
|
||||
# that a formula or field mapping was saved correctly.
|
||||
output = _output(
|
||||
tool_calls=["create_workflows"],
|
||||
messages=[
|
||||
{
|
||||
"role": "assistant",
|
||||
"tool_name": "create_workflows",
|
||||
"args": {
|
||||
"workflows": [
|
||||
{
|
||||
"trigger": {
|
||||
"type": "rows_created",
|
||||
"rows_triggers_settings": {"table_id": source.id},
|
||||
},
|
||||
"nodes": [
|
||||
{
|
||||
"type": "local_baserow_create_row",
|
||||
"table_id": log.id,
|
||||
"values": [
|
||||
{
|
||||
"field_id": entry_field.id,
|
||||
"value": "$formula: trigger Name",
|
||||
},
|
||||
{
|
||||
"field_id": source_field.id,
|
||||
"value": "automation",
|
||||
},
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
],
|
||||
)
|
||||
checks = _check_creates_row_with_field_values(None, scenario, output)
|
||||
assert all(check.passed for check in checks) == (defect is None), checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize("row_binding", ["empty", "constant", "trigger"])
|
||||
@pytest.mark.parametrize(
|
||||
"factory, check, trigger_type, status",
|
||||
[
|
||||
(
|
||||
_creates_workflow_scenario,
|
||||
_check_creates_workflow,
|
||||
"rows_created",
|
||||
"Processing",
|
||||
),
|
||||
(
|
||||
_creates_update_row_workflow_scenario,
|
||||
_check_creates_update_row_workflow,
|
||||
"rows_updated",
|
||||
"Reviewed",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_update_workflow_checks_use_saved_row_and_values(
|
||||
data_fixture, row_binding, factory, check, trigger_type, status
|
||||
):
|
||||
scenario = factory(data_fixture)
|
||||
table = scenario.refs["table"]
|
||||
workflow = data_fixture.create_automation_workflow(
|
||||
automation=scenario.refs["automation"],
|
||||
trigger_type=trigger_type,
|
||||
trigger_service_kwargs={"table": table},
|
||||
)
|
||||
trigger = workflow.get_trigger()
|
||||
row_id = {
|
||||
"empty": "",
|
||||
"constant": "1",
|
||||
"trigger": f"get('previous_node.{trigger.id}[0].id')",
|
||||
}[row_binding]
|
||||
node = data_fixture.create_automation_node(
|
||||
workflow=workflow,
|
||||
type="update_row",
|
||||
service_kwargs={"table": table, "row_id": row_id},
|
||||
)
|
||||
values = [{"field_id": table.field_set.get(name="Status").id, "value": status}]
|
||||
if trigger_type == "rows_updated":
|
||||
values.append(
|
||||
{
|
||||
"field_id": table.field_set.get(name="Notes").id,
|
||||
"value": "Automatically reviewed by automation",
|
||||
}
|
||||
)
|
||||
for value in values:
|
||||
LocalBaserowTableServiceFieldMapping.objects.create(
|
||||
service=node.service, field_id=value["field_id"], value=repr(value["value"])
|
||||
)
|
||||
# A successful tool-side repair does not rewrite the original model args.
|
||||
output = _output(
|
||||
tool_calls=["create_workflows"],
|
||||
messages=[
|
||||
{
|
||||
"role": "assistant",
|
||||
"tool_name": "create_workflows",
|
||||
"args": {
|
||||
"workflows": [
|
||||
{
|
||||
"name": "Uncorrected name",
|
||||
"trigger": None,
|
||||
"nodes": None,
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
],
|
||||
)
|
||||
checks = check(None, scenario, output)
|
||||
assert all(result.passed for result in checks) == (row_binding == "trigger"), checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"factory, check",
|
||||
[
|
||||
(_creates_workflow_scenario, _check_creates_workflow),
|
||||
(_creates_update_row_workflow_scenario, _check_creates_update_row_workflow),
|
||||
(_creates_row_with_field_values_scenario, _check_creates_row_with_field_values),
|
||||
(_creates_weekly_slack_reminder_scenario, _check_creates_weekly_slack_reminder),
|
||||
],
|
||||
)
|
||||
def test_automation_missing_trigger_returns_failed_checks(data_fixture, factory, check):
|
||||
scenario = factory(data_fixture)
|
||||
workflow = data_fixture.create_automation_workflow(
|
||||
automation=scenario.refs["automation"], create_trigger=False
|
||||
)
|
||||
output = _output(
|
||||
tool_calls=["create_workflows"],
|
||||
messages=[
|
||||
{
|
||||
"role": "assistant",
|
||||
"tool_name": "create_workflows",
|
||||
"args": {"workflows": [{"name": workflow.name, "trigger": None}]},
|
||||
}
|
||||
],
|
||||
)
|
||||
checks = check(None, scenario, output)
|
||||
assert any(not result.passed for result in checks)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("space", [" ", "\u202f", "\u00a0", "\n", "\t"])
|
||||
def test_documentation_keywords_accept_equivalent_whitespace(space):
|
||||
output = _output(
|
||||
answer=f"Row history is retained for 14{space}days.",
|
||||
tool_calls=["search_user_docs"],
|
||||
sources=["https://baserow.io/user-docs/row-history"],
|
||||
)
|
||||
checks = _make_docs_checks(["row-history"], ["14 days"])(None, None, output)
|
||||
assert all(check.passed for check in checks)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("apostrophe", ["'", "\u2018", "\u2019"])
|
||||
def test_documentation_keywords_accept_typographic_apostrophes(apostrophe):
|
||||
checks = _make_docs_checks([], ["doesn't"])(
|
||||
None,
|
||||
None,
|
||||
_output(
|
||||
answer=f"The documentation doesn{apostrophe}t establish that feature.",
|
||||
tool_calls=["search_user_docs"],
|
||||
sources=["https://baserow.io/user-docs/example"],
|
||||
),
|
||||
)
|
||||
assert all(check.passed for check in checks)
|
||||
|
||||
|
||||
def test_documentation_apostrophe_normalization_preserves_negation():
|
||||
checks = _make_docs_checks([], ["doesn't"])(
|
||||
None,
|
||||
None,
|
||||
_output(
|
||||
answer="The documentation does establish that feature.",
|
||||
tool_calls=["search_user_docs"],
|
||||
sources=["https://baserow.io/user-docs/example"],
|
||||
),
|
||||
)
|
||||
assert not next(c for c in checks if c.name.startswith("answer mentions")).passed
|
||||
|
||||
|
||||
def test_documentation_whitespace_normalization_preserves_other_requirements():
|
||||
checks = _make_docs_checks([], ["14 days"])(
|
||||
None, None, _output(answer="History is retained for 90\u202fdays.")
|
||||
)
|
||||
assert [check.passed for check in checks[:3]] == [False, False, False]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"wording", ["per view", "per-view", "per\u2010view", "per\u2011view"]
|
||||
)
|
||||
def test_column_width_check_accepts_reference_answer_wording(wording):
|
||||
case = get_case("docs/sync-column-widths")
|
||||
checks = case.checks(
|
||||
case,
|
||||
None,
|
||||
_output(
|
||||
answer=f"No. Column widths are saved {wording}; resizing one does not sync others.",
|
||||
tool_calls=["search_user_docs"],
|
||||
sources=["https://baserow.io/user-docs/guide-to-grid-view"],
|
||||
),
|
||||
)
|
||||
assert all(check.passed for check in checks)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("defect", ["wrong_answer", "missing_source", "missing_search"])
|
||||
def test_column_width_check_keeps_other_requirements(defect):
|
||||
case = get_case("docs/sync-column-widths")
|
||||
checks = case.checks(
|
||||
case,
|
||||
None,
|
||||
_output(
|
||||
answer=(
|
||||
"Column widths synchronize automatically across all views."
|
||||
if defect == "wrong_answer"
|
||||
else "Column widths are saved per-view."
|
||||
),
|
||||
tool_calls=[] if defect == "missing_search" else ["search_user_docs"],
|
||||
sources=[]
|
||||
if defect == "missing_source"
|
||||
else ["https://baserow.io/user-docs/guide-to-grid-view"],
|
||||
),
|
||||
)
|
||||
assert not all(check.passed for check in checks)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("negation", ["doesn't", "does not"])
|
||||
def test_address_check_accepts_contracted_and_uncontracted_negation(negation):
|
||||
case = get_case("docs/address-autocomplete-field")
|
||||
checks = case.checks(
|
||||
case,
|
||||
None,
|
||||
_output(
|
||||
answer=f"Baserow {negation} have a dedicated address field with autocomplete.",
|
||||
tool_calls=["search_user_docs"],
|
||||
sources=["https://baserow.io/user-docs/single-line-text-field"],
|
||||
),
|
||||
)
|
||||
assert all(check.passed for check in checks)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("defect", ["wrong_answer", "missing_source", "missing_search"])
|
||||
def test_address_check_keeps_other_requirements(defect):
|
||||
case = get_case("docs/address-autocomplete-field")
|
||||
checks = case.checks(
|
||||
case,
|
||||
None,
|
||||
_output(
|
||||
answer=(
|
||||
"Baserow does have a dedicated address field with autocomplete."
|
||||
if defect == "wrong_answer"
|
||||
else "Baserow does not have a dedicated address field with autocomplete."
|
||||
),
|
||||
tool_calls=[] if defect == "missing_search" else ["search_user_docs"],
|
||||
sources=[]
|
||||
if defect == "missing_source"
|
||||
else ["https://baserow.io/user-docs/single-line-text-field"],
|
||||
),
|
||||
)
|
||||
assert not all(check.passed for check in checks)
|
||||
|
||||
|
||||
def _element_call(elements):
|
||||
return {
|
||||
"role": "assistant",
|
||||
"tool_name": "create_display_elements",
|
||||
"args": {"elements": elements},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize("kind", ["button", "link"])
|
||||
@pytest.mark.parametrize(
|
||||
"defect", [None, "inert", "wrong_target", "shared", "wrong_label", "text_link"]
|
||||
)
|
||||
def test_back_button_checks_saved_navigation(data_fixture, kind, defect):
|
||||
scenario = _back_button_on_page_not_header_scenario(data_fixture)
|
||||
builder = scenario.refs["builder"]
|
||||
detail = scenario.refs["detail_page"]
|
||||
page = builder.shared_page if defect == "shared" else detail
|
||||
target = (
|
||||
detail
|
||||
if defect == "wrong_target"
|
||||
else Page.objects.get(builder=builder, path="/list")
|
||||
)
|
||||
value = "'Go elsewhere'" if defect == "wrong_label" else "'Back to List'"
|
||||
if kind == "link":
|
||||
data_fixture.create_builder_link_element(
|
||||
page=page,
|
||||
value=value,
|
||||
variant="link" if defect == "text_link" else "button",
|
||||
navigation_type="page",
|
||||
navigate_to_page_id=None if defect == "inert" else target.id,
|
||||
)
|
||||
else:
|
||||
button = data_fixture.create_builder_button_element(page=page, value=value)
|
||||
if defect != "inert":
|
||||
data_fixture.create_open_page_workflow_action(
|
||||
page=page,
|
||||
element=button,
|
||||
event="click",
|
||||
navigation_type="page",
|
||||
navigate_to_page=target,
|
||||
)
|
||||
output = _output(
|
||||
tool_calls=["create_display_elements"],
|
||||
messages=[_element_call([{"type": kind, "value": "Back to List"}])],
|
||||
)
|
||||
checks = _check_back_button_on_page_not_header(None, scenario, output)
|
||||
expected = defect is None or (kind == "button" and defect == "text_link")
|
||||
assert all(check.passed for check in checks) == expected, checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize("navigation_type", ["page", "custom"])
|
||||
def test_landing_checks_accept_interleaved_page_creation(data_fixture, navigation_type):
|
||||
scenario, home, button, output = _landing_page(data_fixture)
|
||||
contact = data_fixture.create_builder_page(
|
||||
builder=scenario.refs["builder"], name="Contact", path="/contact"
|
||||
)
|
||||
data_fixture.create_open_page_workflow_action(
|
||||
page=home,
|
||||
element=button,
|
||||
event="click",
|
||||
navigation_type=navigation_type,
|
||||
navigate_to_page=contact if navigation_type == "page" else None,
|
||||
navigate_to_url="'/contact'" if navigation_type == "custom" else "''",
|
||||
)
|
||||
# Home and its elements can be created before the Contact destination.
|
||||
output.tool_calls += ["create_pages", "create_actions"]
|
||||
checks = _check_creates_landing_page(None, scenario, output)
|
||||
assert all(check.passed for check in checks), checks
|
||||
|
||||
|
||||
def _landing_page(fx, link_variant=None):
|
||||
scenario = _creates_landing_page_scenario(fx)
|
||||
home = fx.create_builder_page(
|
||||
builder=scenario.refs["builder"], name="Home", path="/"
|
||||
)
|
||||
fx.create_builder_heading_element(page=home, value="'Welcome'")
|
||||
fx.create_builder_text_element(page=home, value="'This is our landing page'")
|
||||
button = (
|
||||
fx.create_builder_link_element(
|
||||
page=home,
|
||||
value="'Get Started'",
|
||||
variant=link_variant,
|
||||
navigation_type="custom",
|
||||
navigate_to_url="'/contact'",
|
||||
)
|
||||
if link_variant
|
||||
else fx.create_builder_button_element(page=home, value="'Get Started'")
|
||||
)
|
||||
output = _output(
|
||||
tool_calls=["create_pages", "create_display_elements"],
|
||||
messages=[
|
||||
_element_call(
|
||||
[
|
||||
{"type": "heading", "value": "Welcome"},
|
||||
{"type": "text", "value": "This is our landing page"},
|
||||
{
|
||||
"type": "button",
|
||||
"value": "Get Started",
|
||||
"navigation_type": "custom",
|
||||
"navigate_to_url": "/contact",
|
||||
},
|
||||
]
|
||||
)
|
||||
],
|
||||
)
|
||||
return scenario, home, button, output
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"variant, target, valid",
|
||||
[
|
||||
("button", "/contact", True),
|
||||
("link", "/contact", False),
|
||||
("button", "/wrong", False),
|
||||
],
|
||||
)
|
||||
def test_landing_accepts_working_link_button_without_action(
|
||||
data_fixture, variant, target, valid
|
||||
):
|
||||
scenario, _, link, output = _landing_page(data_fixture, link_variant=variant)
|
||||
link.navigate_to_url = f"'{target}'"
|
||||
link.save()
|
||||
checks = _check_creates_landing_page(None, scenario, output)
|
||||
assert all(check.passed for check in checks) is valid, checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"defect", ["missing", "wrong_target", "wrong_event", "wrong_button"]
|
||||
)
|
||||
def test_landing_checks_reject_inert_or_wrong_cta(data_fixture, defect):
|
||||
scenario, home, button, output = _landing_page(data_fixture)
|
||||
if defect != "missing":
|
||||
if defect == "wrong_button":
|
||||
button = data_fixture.create_builder_button_element(
|
||||
page=home, value="'Other button'"
|
||||
)
|
||||
data_fixture.create_open_page_workflow_action(
|
||||
page=home,
|
||||
element=button,
|
||||
event="submit" if defect == "wrong_event" else "click",
|
||||
navigation_type="custom",
|
||||
navigate_to_url="'/wrong'" if defect == "wrong_target" else "'/contact'",
|
||||
)
|
||||
checks = _check_creates_landing_page(None, scenario, output)
|
||||
assert not all(check.passed for check in checks), checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"source",
|
||||
["current_record", "first_row", "mixed", "outside_repeat", "nested_repeat"],
|
||||
)
|
||||
@pytest.mark.parametrize("target", ["current", "new", "other_workspace", "existing"])
|
||||
def test_project_cards_resolve_both_fields_for_each_record(
|
||||
data_fixture, source, target
|
||||
):
|
||||
scenario = _creates_app_when_table_exists_scenario(data_fixture)
|
||||
table = scenario.refs["projects_table"]
|
||||
builder = scenario.refs["builder"]
|
||||
if target != "current":
|
||||
builder = data_fixture.create_builder_application(
|
||||
workspace=(
|
||||
data_fixture.create_workspace()
|
||||
if target == "other_workspace"
|
||||
else scenario.workspace
|
||||
)
|
||||
)
|
||||
if target == "existing":
|
||||
scenario.refs["initial_builder_ids"].append(builder.id)
|
||||
page = data_fixture.create_builder_page(builder=builder)
|
||||
data_source = data_fixture.create_builder_local_baserow_list_rows_data_source(
|
||||
page=page, table=table
|
||||
)
|
||||
repeat = data_fixture.create_builder_repeat_element(
|
||||
page=page, data_source=data_source
|
||||
)
|
||||
container = data_fixture.create_builder_column_element(
|
||||
page=page, reference_element=repeat, position=GraphPointPosition.CHILD
|
||||
)
|
||||
if source == "nested_repeat":
|
||||
container = data_fixture.create_builder_repeat_element(
|
||||
page=page,
|
||||
data_source=data_source,
|
||||
reference_element=container,
|
||||
position=GraphPointPosition.CHILD,
|
||||
)
|
||||
for name, factory in [
|
||||
("Name", data_fixture.create_builder_heading_element),
|
||||
("Status", data_fixture.create_builder_text_element),
|
||||
]:
|
||||
field = table.field_set.get(name=name)
|
||||
root = (
|
||||
f"data_source.{data_source.id}.0"
|
||||
if source == "first_row" or (source == "mixed" and name == "Name")
|
||||
else "current_record"
|
||||
)
|
||||
placement = (
|
||||
{"reference_element": repeat, "position": GraphPointPosition.SOUTH}
|
||||
if source == "outside_repeat"
|
||||
else {"reference_element": container, "position": GraphPointPosition.CHILD}
|
||||
)
|
||||
factory(page=page, value=f"get('{root}.{field.db_column}')", **placement)
|
||||
output = _output(
|
||||
tool_calls=["create_pages", "create_data_sources", "create_display_elements"],
|
||||
messages=[
|
||||
{
|
||||
"role": "assistant",
|
||||
"tool_name": "create_data_sources",
|
||||
"args": {"data_sources": [{"table_id": table.id}]},
|
||||
},
|
||||
_element_call([{"type": "heading"}, {"type": "text"}]),
|
||||
],
|
||||
)
|
||||
checks = _check_creates_app_when_table_exists(None, scenario, output)
|
||||
expected = source == "current_record" and target in {"current", "new"}
|
||||
assert all(check.passed for check in checks) is expected, checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_contact_form_accepts_primitive_tools_and_requires_submit_action(data_fixture):
|
||||
scenario = _creates_contact_form_scenario(data_fixture)
|
||||
page = data_fixture.create_builder_page(
|
||||
builder=scenario.refs["builder"], name="Contact", path="/contact"
|
||||
)
|
||||
form = data_fixture.create_builder_form_container_element(page=page)
|
||||
service = data_fixture.create_local_baserow_upsert_row_service(
|
||||
table=scenario.refs["table"]
|
||||
)
|
||||
for name in ["name", "email"]:
|
||||
element = data_fixture.create_builder_input_text_element(
|
||||
page=page, reference_element=form, position=GraphPointPosition.CHILD
|
||||
)
|
||||
service.field_mappings.create(
|
||||
field=scenario.refs[f"{name}_field"],
|
||||
value=f"get('form_data.{element.id}')",
|
||||
enabled=True,
|
||||
)
|
||||
action = data_fixture.create_local_baserow_create_row_workflow_action(
|
||||
page=page, element=form, event="submit", service=service
|
||||
)
|
||||
output = _output(
|
||||
tool_calls=["create_pages", "create_form_elements", "create_actions"]
|
||||
)
|
||||
checks = _check_creates_contact_form(None, scenario, output)
|
||||
assert all(check.passed for check in checks), checks
|
||||
|
||||
action.event = "click"
|
||||
action.save()
|
||||
assert not all(
|
||||
check.passed for check in _check_creates_contact_form(None, scenario, output)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_filtered_source_accepts_automatic_routing_and_requires_matching_view(
|
||||
data_fixture,
|
||||
):
|
||||
scenario = _filtered_data_source_via_view_scenario(data_fixture)
|
||||
table = scenario.refs["table"]
|
||||
field = scenario.refs["status_field"]
|
||||
pending = field.select_options.get(value="Pending")
|
||||
view = data_fixture.create_grid_view(table=table)
|
||||
data_fixture.create_view_filter(
|
||||
view=view, field=field, type="single_select_equal", value=str(pending.id)
|
||||
)
|
||||
page = data_fixture.create_builder_page(builder=scenario.refs["builder"])
|
||||
source = data_fixture.create_builder_local_baserow_list_rows_data_source(
|
||||
page=page, table=table, view=view
|
||||
)
|
||||
output = _output(
|
||||
tool_calls=[
|
||||
"create_views",
|
||||
"create_view_filters",
|
||||
"create_pages",
|
||||
"create_data_sources",
|
||||
]
|
||||
)
|
||||
checks = _check_filtered_data_source_via_view(None, scenario, output)
|
||||
assert all(check.passed for check in checks), checks
|
||||
|
||||
source.service.specific.view = data_fixture.create_grid_view(table=table)
|
||||
source.service.specific.save()
|
||||
assert not all(
|
||||
check.passed
|
||||
for check in _check_filtered_data_source_via_view(None, scenario, output)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"group_type,disabled,valid",
|
||||
[("AND", False, True), ("OR", False, False), ("AND", True, True)],
|
||||
)
|
||||
def test_filtered_source_check_matches_service_group_and_disabled_semantics(
|
||||
data_fixture, group_type, disabled, valid
|
||||
):
|
||||
from baserow.contrib.integrations.local_baserow.service_types import (
|
||||
LocalBaserowListRowsUserServiceType,
|
||||
)
|
||||
from baserow.test_utils.pytest_conftest import FakeDispatchContext
|
||||
|
||||
scenario = _filtered_data_source_via_view_scenario(data_fixture)
|
||||
table, field = scenario.refs["table"], scenario.refs["status_field"]
|
||||
pending = field.select_options.get(value="Pending")
|
||||
done = field.select_options.get(value="Done")
|
||||
view = data_fixture.create_grid_view(table=table, filters_disabled=disabled)
|
||||
group = data_fixture.create_view_filter_group(view=view, filter_type=group_type)
|
||||
for option_ids in [str(pending.id), f"{pending.id},{done.id}"]:
|
||||
data_fixture.create_view_filter(
|
||||
view=view,
|
||||
field=field,
|
||||
type="single_select_is_any_of",
|
||||
value=option_ids,
|
||||
group=group,
|
||||
)
|
||||
page = data_fixture.create_builder_page(builder=scenario.refs["builder"])
|
||||
source = data_fixture.create_builder_local_baserow_list_rows_data_source(
|
||||
page=page, table=table, view=view
|
||||
)
|
||||
model = table.get_model()
|
||||
rows = [
|
||||
model.objects.create(**{f"{field.db_column}_id": option_id})
|
||||
for option_id in [pending.id, done.id, None]
|
||||
]
|
||||
actual = LocalBaserowListRowsUserServiceType().get_dispatch_filters(
|
||||
source.service.specific, model.objects.all(), model, FakeDispatchContext()
|
||||
)
|
||||
assert set(actual.values_list("id", flat=True)) == {
|
||||
row.id for row in (rows[:1] if valid else rows[:2])
|
||||
}
|
||||
checks = _check_filtered_data_source_via_view(None, scenario, _output())
|
||||
assert all(check.passed for check in checks) is valid, checks
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"tool_calls, answer, failed",
|
||||
[
|
||||
(
|
||||
["list_tables", "ask_user"],
|
||||
"Create a Projects table with sample data?",
|
||||
set(),
|
||||
),
|
||||
(
|
||||
["list_tables", "create_tables", "setup_page"],
|
||||
"The Projects app is ready with sample data.",
|
||||
{
|
||||
"did NOT invent a Projects table",
|
||||
"did NOT build the app pages",
|
||||
"asked the user about the missing records",
|
||||
},
|
||||
),
|
||||
(
|
||||
["ask_user"],
|
||||
"Create a Projects table with sample data?",
|
||||
{"looked the table up first"},
|
||||
),
|
||||
(
|
||||
["list_tables", "ask_user"],
|
||||
"Where are your projects stored?",
|
||||
{"offers to create a table with sample data"},
|
||||
),
|
||||
(["list_tables"], "Should I create a Projects table with sample data?", set()),
|
||||
],
|
||||
)
|
||||
def test_implied_projects_app_asks_instead_of_inventing_data(
|
||||
data_fixture, tool_calls, answer, failed
|
||||
):
|
||||
scenario = _projects_table_missing_scenario(data_fixture)
|
||||
|
||||
checks = _check_asks_when_implied_table_missing(
|
||||
None, scenario, _output(tool_calls=tool_calls, answer=answer)
|
||||
)
|
||||
|
||||
assert {check.name for check in checks if not check.passed} == failed
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"answer, accepted",
|
||||
[
|
||||
("Use date_diff('day', field('Start'), field('End')).", True),
|
||||
("Subtract the dates: field('End') - field('Start') gives a duration.", True),
|
||||
("Baserow has no way to compare dates.", False),
|
||||
],
|
||||
)
|
||||
def test_date_difference_accepts_either_correct_formula(answer, accepted):
|
||||
case = get_case("docs/date-diff-formula")
|
||||
output = _output(
|
||||
answer=answer,
|
||||
tool_calls=["search_user_docs"],
|
||||
sources=["https://baserow.io/user-docs/understanding-formulas"],
|
||||
)
|
||||
|
||||
checks = {check.name: check.passed for check in case.checks(case, None, output)}
|
||||
|
||||
assert (
|
||||
checks[
|
||||
"answer mentions one of ['date_diff', 'date diff', 'datediff', 'subtract']"
|
||||
]
|
||||
is accepted
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"answer, accepted",
|
||||
[
|
||||
("Store invoices in a **File** field and add an **AI Prompt field**.", True),
|
||||
("Use the AI field on your file field.", True),
|
||||
("Baserow cannot read files.", False),
|
||||
],
|
||||
)
|
||||
def test_ocr_answer_matches_despite_markdown_and_the_field_type_name(answer, accepted):
|
||||
case = get_case("docs/ocr-scan")
|
||||
output = _output(
|
||||
answer=answer,
|
||||
tool_calls=["search_user_docs"],
|
||||
sources=["https://baserow.io/user-docs/ai-field"],
|
||||
)
|
||||
|
||||
checks = {check.name: check.passed for check in case.checks(case, None, output)}
|
||||
|
||||
assert (
|
||||
checks["answer mentions one of ['ai field', 'ai prompt', 'file field']"]
|
||||
is accepted
|
||||
)
|
||||
+28
-3
@@ -59,6 +59,7 @@ _OUR_DATASETS = {
|
||||
"kuma-docs",
|
||||
"kuma-builder",
|
||||
"kuma-automation",
|
||||
"kuma-prod-replay",
|
||||
}
|
||||
|
||||
EXPECTED_CASE_IDS = {
|
||||
@@ -157,8 +158,12 @@ EXPECTED_CASE_IDS = {
|
||||
"docs/webhooks-availability",
|
||||
],
|
||||
"kuma-builder": [
|
||||
"builder/asks-once-when-goal-unclear",
|
||||
"builder/asks-when-implied-table-missing",
|
||||
"builder/asks-when-named-table-missing",
|
||||
"builder/back-button-on-page-not-header",
|
||||
"builder/builds-demo-page-without-asking",
|
||||
"builder/builds-example-app-without-asking",
|
||||
"builder/changes-theme",
|
||||
"builder/creates-app-when-table-exists",
|
||||
"builder/creates-app-with-theme",
|
||||
@@ -184,6 +189,15 @@ EXPECTED_CASE_IDS = {
|
||||
"automation/creates-workflow",
|
||||
"automation/lists-workflows",
|
||||
],
|
||||
"kuma-prod-replay": [
|
||||
"prod-replay/fake-rows-into-typed-fields",
|
||||
"prod-replay/form-for-table-with-formula-field",
|
||||
"prod-replay/impossible-formula-request",
|
||||
"prod-replay/iso-week-number-formula",
|
||||
"prod-replay/page-inspection-existing-elements",
|
||||
"prod-replay/project-tracker-onboarding",
|
||||
"prod-replay/signed-amount-formula",
|
||||
],
|
||||
}
|
||||
|
||||
# builder/creates-app-with-theme bypassed mode derivation in the legacy test
|
||||
@@ -191,6 +205,8 @@ EXPECTED_CASE_IDS = {
|
||||
# AssistantDeps default of DATABASE; every other builder case derived
|
||||
# APPLICATION from its application-slot UIContext. All automation cases never
|
||||
# set deps.mode, so they ran (and still run) in DATABASE mode too.
|
||||
# Prod-replay derived mode from the UI context: builder page inspection ran in
|
||||
# APPLICATION, every other replay in DATABASE.
|
||||
EXPECTED_MODES = {
|
||||
**{
|
||||
case_id: AgentMode.APPLICATION
|
||||
@@ -199,6 +215,10 @@ EXPECTED_MODES = {
|
||||
},
|
||||
"builder/creates-app-with-theme": AgentMode.DATABASE,
|
||||
**{case_id: AgentMode.DATABASE for case_id in EXPECTED_CASE_IDS["kuma-automation"]},
|
||||
**{
|
||||
case_id: AgentMode.DATABASE for case_id in EXPECTED_CASE_IDS["kuma-prod-replay"]
|
||||
},
|
||||
"prod-replay/page-inspection-existing-elements": AgentMode.APPLICATION,
|
||||
}
|
||||
|
||||
|
||||
@@ -213,8 +233,9 @@ class TestDatasetCounts:
|
||||
assert len(grouped["kuma-core"]) == 3
|
||||
assert len(grouped["kuma-database"]) == 21
|
||||
assert len(grouped["kuma-docs"]) == 64
|
||||
assert len(grouped["kuma-builder"]) == 17
|
||||
assert len(grouped["kuma-builder"]) == 21
|
||||
assert len(grouped["kuma-automation"]) == 7
|
||||
assert len(grouped["kuma-prod-replay"]) == 7
|
||||
|
||||
def test_case_ids_match_inventory(self):
|
||||
grouped = cases_by_dataset()
|
||||
@@ -247,12 +268,16 @@ class TestDocsCasesFlagKnowledgeBase:
|
||||
)
|
||||
|
||||
|
||||
class TestBuilderAutomationModes:
|
||||
class TestAgentModes:
|
||||
"""Mode is scenario configuration, not derived — pin it per case id."""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"case",
|
||||
[c for c in _our_cases() if c.dataset in ("kuma-builder", "kuma-automation")],
|
||||
[
|
||||
c
|
||||
for c in _our_cases()
|
||||
if c.dataset in ("kuma-builder", "kuma-automation", "kuma-prod-replay")
|
||||
],
|
||||
ids=lambda c: c.id,
|
||||
)
|
||||
def test_mode_matches_inventory(self, case):
|
||||
|
||||
+388
-2
@@ -4,10 +4,18 @@ import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from django.db import OperationalError
|
||||
|
||||
import pytest
|
||||
from asgiref.sync import async_to_sync, sync_to_async
|
||||
from pydantic import BaseModel, TypeAdapter, ValidationError
|
||||
from pydantic_ai import Agent, RunContext
|
||||
from pydantic_ai.exceptions import (
|
||||
ModelHTTPError,
|
||||
UnexpectedModelBehavior,
|
||||
UsageLimitExceeded,
|
||||
UserError,
|
||||
)
|
||||
from pydantic_ai.messages import (
|
||||
ModelRequest,
|
||||
ModelResponse,
|
||||
@@ -32,15 +40,22 @@ from baserow_enterprise.assistant.evals.harness import (
|
||||
PROMPT_AGENT_TARGETS,
|
||||
PROMPT_ATTR_TARGETS,
|
||||
EvalCaseCleanupError,
|
||||
EvalCaseModelError,
|
||||
EvalCaseTimeout,
|
||||
count_tool_errors,
|
||||
executed_tool_calls,
|
||||
get_case_timeout_s,
|
||||
override_assistant_prompts,
|
||||
run_case,
|
||||
)
|
||||
from baserow_enterprise.assistant.evals.prompt_sync import SYNCED_PROMPTS
|
||||
from baserow_enterprise.assistant.evals.scenarios import make_fixtures
|
||||
from baserow_enterprise.assistant.evals.types import CheckResult, EvalCase, EvalScenario
|
||||
from baserow_enterprise.assistant.evals.types import (
|
||||
CheckResult,
|
||||
EvalCase,
|
||||
EvalRunOutput,
|
||||
EvalScenario,
|
||||
)
|
||||
from baserow_enterprise.assistant.model_profiles import (
|
||||
ORCHESTRATOR,
|
||||
ResolvedAssistantModelProfile,
|
||||
@@ -308,6 +323,215 @@ class TestBuildAgentRunContext:
|
||||
model.__aexit__.assert_awaited_once()
|
||||
|
||||
|
||||
class TestAskUserTool:
|
||||
def test_records_the_question_and_tells_the_agent_to_stop(self):
|
||||
"""Asking must be an action the agent can take, not the absence of
|
||||
one — otherwise it competes with the prompt's bias toward acting."""
|
||||
|
||||
from baserow_enterprise.assistant.tools.core.tools import ask_user
|
||||
|
||||
deps = SimpleNamespace(pending_question=None)
|
||||
result = ask_user(
|
||||
SimpleNamespace(deps=deps),
|
||||
question="Which table holds your customers?",
|
||||
thought="No Customers table found.",
|
||||
)
|
||||
|
||||
assert deps.pending_question == "Which table holds your customers?"
|
||||
assert "restate this question verbatim" in result
|
||||
|
||||
def test_is_reachable_from_every_mode(self):
|
||||
from baserow_enterprise.assistant.deps import AgentMode
|
||||
from baserow_enterprise.assistant.tools.routing import is_tool_active
|
||||
|
||||
assert all(is_tool_active("ask_user", mode) for mode in AgentMode)
|
||||
|
||||
|
||||
class TestCountToolErrors:
|
||||
def test_empty_response_retry_is_not_a_tool_error(self):
|
||||
"""pydantic-ai nudges the model after an empty response with a
|
||||
tool_name-less RetryPromptPart; it recovers on its own, so it must not
|
||||
spend the case's tool-error budget."""
|
||||
|
||||
from pydantic_ai.messages import ModelRequest, RetryPromptPart
|
||||
|
||||
from baserow_enterprise.assistant.evals.harness import count_tool_errors
|
||||
|
||||
result = SimpleNamespace(
|
||||
all_messages=lambda: [
|
||||
ModelRequest(
|
||||
parts=[
|
||||
RetryPromptPart(content="Please return text or call a tool.")
|
||||
]
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
assert count_tool_errors(result) == (0, "")
|
||||
|
||||
def test_real_tool_validation_error_still_counts(self):
|
||||
from pydantic_ai.messages import ModelRequest, RetryPromptPart
|
||||
|
||||
from baserow_enterprise.assistant.evals.harness import count_tool_errors
|
||||
|
||||
result = SimpleNamespace(
|
||||
all_messages=lambda: [
|
||||
ModelRequest(
|
||||
parts=[
|
||||
RetryPromptPart(
|
||||
content="update_row requires row_id",
|
||||
tool_name="create_workflows",
|
||||
)
|
||||
]
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
count, hint = count_tool_errors(result)
|
||||
assert count == 1
|
||||
assert "create_workflows" in hint
|
||||
|
||||
def test_router_redirect_is_recognised_from_the_router_itself(self):
|
||||
"""The harness must not carry its own copy of the redirect wording."""
|
||||
|
||||
from pydantic_ai.messages import ModelRequest, RetryPromptPart
|
||||
|
||||
from baserow_enterprise.assistant.evals.harness import count_tool_errors
|
||||
from baserow_enterprise.assistant.tools.routing import mode_redirect_message
|
||||
|
||||
result = SimpleNamespace(
|
||||
all_messages=lambda: [
|
||||
ModelRequest(
|
||||
parts=[
|
||||
RetryPromptPart(
|
||||
content=mode_redirect_message(
|
||||
"create_workflows", AgentMode.AUTOMATION
|
||||
),
|
||||
tool_name="create_workflows",
|
||||
)
|
||||
]
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
assert count_tool_errors(result) == (0, "")
|
||||
|
||||
|
||||
class TestExecutedToolCalls:
|
||||
"""A routed call is rejected and re-issued; only the re-issue ran."""
|
||||
|
||||
def _output(self, messages):
|
||||
return EvalRunOutput(
|
||||
answer="",
|
||||
messages=messages,
|
||||
tool_calls=[],
|
||||
tool_error_count=0,
|
||||
tool_error_hint="",
|
||||
sources=[],
|
||||
request_count=0,
|
||||
duration_s=0.0,
|
||||
)
|
||||
|
||||
def test_the_call_the_router_sent_back_is_not_scored(self):
|
||||
from baserow_enterprise.assistant.evals.harness import executed_tool_calls
|
||||
from baserow_enterprise.assistant.tools.routing import mode_redirect_message
|
||||
|
||||
output = self._output(
|
||||
[
|
||||
{
|
||||
"role": "assistant",
|
||||
"type": "ToolCallPart",
|
||||
"tool_name": "create_workflows",
|
||||
"tool_call_id": "deferred",
|
||||
"args": {"workflows": [{"name": "first guess"}]},
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"type": "RetryPromptPart",
|
||||
"tool_name": "create_workflows",
|
||||
"tool_call_id": "deferred",
|
||||
"content": mode_redirect_message(
|
||||
"create_workflows", AgentMode.AUTOMATION
|
||||
),
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"type": "ToolCallPart",
|
||||
"tool_name": "create_workflows",
|
||||
"tool_call_id": "executed",
|
||||
"args": {"workflows": [{"name": "real request"}]},
|
||||
},
|
||||
]
|
||||
)
|
||||
|
||||
calls = executed_tool_calls(output, "create_workflows")
|
||||
|
||||
assert [call["tool_call_id"] for call in calls] == ["executed"]
|
||||
|
||||
def test_a_real_validation_retry_leaves_the_call_scored(self):
|
||||
from baserow_enterprise.assistant.evals.harness import executed_tool_calls
|
||||
|
||||
output = self._output(
|
||||
[
|
||||
{
|
||||
"role": "assistant",
|
||||
"type": "ToolCallPart",
|
||||
"tool_name": "create_workflows",
|
||||
"tool_call_id": "only",
|
||||
"args": {"workflows": []},
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"type": "RetryPromptPart",
|
||||
"tool_name": "create_workflows",
|
||||
"tool_call_id": "only",
|
||||
"content": "workflows must not be empty",
|
||||
},
|
||||
]
|
||||
)
|
||||
|
||||
calls = executed_tool_calls(output, "create_workflows")
|
||||
|
||||
assert [call["tool_call_id"] for call in calls] == ["only"]
|
||||
|
||||
def test_a_call_answered_with_a_redirect_result_is_not_scored(self):
|
||||
output = self._output(
|
||||
[
|
||||
{
|
||||
"role": "assistant",
|
||||
"type": "ToolCallPart",
|
||||
"tool_name": "create_workflows",
|
||||
"tool_call_id": "deferred",
|
||||
"args": {"workflows": [{"name": "first guess"}]},
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"type": "ToolReturnPart",
|
||||
"tool_name": "create_workflows",
|
||||
"tool_call_id": "deferred",
|
||||
"content": {
|
||||
"changed": False,
|
||||
"mode": AgentMode.AUTOMATION.value,
|
||||
"next_steps": mode_redirect_message(
|
||||
"create_workflows", AgentMode.AUTOMATION
|
||||
),
|
||||
},
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"type": "ToolCallPart",
|
||||
"tool_name": "create_workflows",
|
||||
"tool_call_id": "executed",
|
||||
"args": {"workflows": [{"name": "real request"}]},
|
||||
},
|
||||
]
|
||||
)
|
||||
|
||||
calls = executed_tool_calls(output, "create_workflows")
|
||||
|
||||
assert [call["tool_call_id"] for call in calls] == ["executed"]
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestRunCase:
|
||||
def _register_scenario(self, user, workspace):
|
||||
@@ -357,6 +581,38 @@ class TestRunCase:
|
||||
assert test_model.entered
|
||||
assert test_model.closed
|
||||
|
||||
def test_ask_user_is_exposed_to_the_agent_and_recorded_as_a_tool_call(self):
|
||||
"""End-to-end guard for the intent eval checks.
|
||||
|
||||
They assert ``tool_called(output, "ask_user")``, so the tool must be
|
||||
reachable through the real toolset AND land in ``output.tool_calls``
|
||||
under exactly that name. If either breaks, the ask cases would fail
|
||||
forever and the act cases would pass trivially — silently.
|
||||
"""
|
||||
|
||||
from baserow_enterprise.assistant.evals.harness import tool_called
|
||||
|
||||
fixtures = make_fixtures()
|
||||
user = fixtures.create_user()
|
||||
workspace = fixtures.create_workspace(user=user)
|
||||
self._register_scenario(user, workspace)
|
||||
|
||||
ctx = build_agent_run_context(user, workspace, _noop_tool_helpers(workspace))
|
||||
assert "ask_user" in ctx.deps.tool_catalog
|
||||
|
||||
case = EvalCase(
|
||||
id="harness-test/ask-user",
|
||||
dataset="harness-test",
|
||||
prompt="build me a page for our Customers",
|
||||
scenario="harness-test-scenario",
|
||||
checks=lambda case, scenario, output: [],
|
||||
)
|
||||
|
||||
output, _checks = run_case(case, TestModel(call_tools=["ask_user"]))
|
||||
|
||||
assert "ask_user" in output.tool_calls
|
||||
assert tool_called(output, "ask_user") == 1
|
||||
|
||||
def test_returns_output_and_prepends_budget_check(self):
|
||||
fixtures = make_fixtures()
|
||||
user = fixtures.create_user()
|
||||
@@ -391,7 +647,11 @@ class TestRunCase:
|
||||
assert results[1].name == "has-no-tool-calls"
|
||||
assert results[1].passed is True
|
||||
|
||||
def test_scenario_receives_case_mode_and_ui_context(self):
|
||||
def test_scenario_receives_case_mode_and_ui_context(self, monkeypatch):
|
||||
"""The case's mode and the scenario's ui_context must reach the run's
|
||||
deps — otherwise every case silently runs in DATABASE mode with no
|
||||
UI context and the whole baseline measures the wrong agent."""
|
||||
|
||||
from baserow_enterprise.assistant.deps import AgentMode
|
||||
|
||||
fixtures = make_fixtures()
|
||||
@@ -416,11 +676,59 @@ class TestRunCase:
|
||||
mode=AgentMode.APPLICATION,
|
||||
)
|
||||
|
||||
captured = {}
|
||||
real_build_context = build_agent_run_context
|
||||
|
||||
def build_context_spy(*args, **kwargs):
|
||||
ctx = real_build_context(*args, **kwargs)
|
||||
captured["ctx"] = ctx
|
||||
return ctx
|
||||
|
||||
monkeypatch.setattr(harness, "build_agent_run_context", build_context_spy)
|
||||
|
||||
output, results = run_case(
|
||||
case, TestModel(custom_output_text="hi", call_tools=[])
|
||||
)
|
||||
|
||||
assert output.answer == "hi"
|
||||
deps = captured["ctx"].deps
|
||||
assert deps.mode is AgentMode.APPLICATION
|
||||
request_context = deps.tool_helpers.request_context
|
||||
assert request_context["ui_context"] == '{"foo": "bar"}'
|
||||
|
||||
def test_runs_the_agent_in_sequential_tool_execution_mode(self, monkeypatch):
|
||||
"""Production serializes multi-tool-call responses (assistant.py);
|
||||
evals must measure the same execution mode, not pydantic-ai's
|
||||
parallel default."""
|
||||
|
||||
from pydantic_ai.tool_manager import _parallel_execution_mode_ctx_var
|
||||
|
||||
fixtures = make_fixtures()
|
||||
user = fixtures.create_user()
|
||||
workspace = fixtures.create_workspace(user=user)
|
||||
self._register_scenario(user, workspace)
|
||||
case = EvalCase(
|
||||
id="harness-test/sequential-mode",
|
||||
dataset="harness-test",
|
||||
prompt="say hi",
|
||||
scenario="harness-test-scenario",
|
||||
checks=lambda case, scenario, output: [],
|
||||
)
|
||||
seen = {}
|
||||
|
||||
async def run_spy(*args, **kwargs):
|
||||
seen["mode"] = _parallel_execution_mode_ctx_var.get()
|
||||
return SimpleNamespace(
|
||||
output="hello",
|
||||
usage=SimpleNamespace(requests=1),
|
||||
all_messages=lambda: [],
|
||||
)
|
||||
|
||||
monkeypatch.setattr(harness.main_agent, "run", run_spy)
|
||||
|
||||
run_case(case, TestModel(call_tools=[]))
|
||||
|
||||
assert seen["mode"] == "sequential"
|
||||
|
||||
|
||||
class _InstructionSpyModel(TestModel):
|
||||
@@ -791,3 +1099,81 @@ def test_an_empty_timeout_env_var_falls_back_to_the_default(monkeypatch, value):
|
||||
monkeypatch.setenv("BASEROW_EVAL_CASE_TIMEOUT", value)
|
||||
|
||||
assert get_case_timeout_s() == 120
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestModelFailureBoundary:
|
||||
@pytest.fixture
|
||||
def case(self, data_fixture, monkeypatch):
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
registry.register_scenario("error-boundary")(
|
||||
lambda _: EvalScenario(user=user, workspace=workspace, ui_context=None)
|
||||
)
|
||||
monkeypatch.setattr(harness, "main_agent", Agent())
|
||||
return EvalCase(
|
||||
id="harness/error-boundary",
|
||||
dataset="harness-test",
|
||||
prompt="Say hello",
|
||||
scenario="error-boundary",
|
||||
checks=MagicMock(return_value=[]),
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error_type", [UsageLimitExceeded, UnexpectedModelBehavior]
|
||||
)
|
||||
def test_only_known_agent_failures_are_classified(
|
||||
self, case, monkeypatch, error_type
|
||||
):
|
||||
error = error_type("The model exhausted its budget")
|
||||
monkeypatch.setattr(
|
||||
harness, "run_agent_with_model", AsyncMock(side_effect=error)
|
||||
)
|
||||
|
||||
with pytest.raises(EvalCaseModelError) as raised:
|
||||
run_case(case, TestModel(call_tools=[]))
|
||||
|
||||
assert raised.value.error is error
|
||||
assert raised.value.__cause__ is error
|
||||
case.checks.assert_not_called()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"phase, error",
|
||||
[
|
||||
("setup", UsageLimitExceeded("Setup failed")),
|
||||
("setup", UnexpectedModelBehavior("Setup failed")),
|
||||
("setup", UserError("Missing API key")),
|
||||
("agent", UserError("Invalid model configuration")),
|
||||
("agent", ModelHTTPError(401, "test-model")),
|
||||
("agent", ModelHTTPError(404, "unknown-model")),
|
||||
("agent", OperationalError("Database connection lost")),
|
||||
("agent", RuntimeError("Unexpected tool failure")),
|
||||
("checks", UsageLimitExceeded("A check failed")),
|
||||
("checks", UnexpectedModelBehavior("A check failed")),
|
||||
("checks", TimeoutError("A check timed out")),
|
||||
("checks", AttributeError("A check failed")),
|
||||
("output", AttributeError("Output formatting failed")),
|
||||
],
|
||||
)
|
||||
def test_other_failures_escape_without_becoming_model_scores(
|
||||
self, case, monkeypatch, phase, error
|
||||
):
|
||||
if phase == "setup":
|
||||
monkeypatch.setattr(
|
||||
harness, "build_agent_run_context", MagicMock(side_effect=error)
|
||||
)
|
||||
elif phase == "agent":
|
||||
monkeypatch.setattr(
|
||||
harness, "run_agent_with_model", AsyncMock(side_effect=error)
|
||||
)
|
||||
elif phase == "checks":
|
||||
case.checks.side_effect = error
|
||||
else:
|
||||
monkeypatch.setattr(
|
||||
harness, "format_message_history", MagicMock(side_effect=error)
|
||||
)
|
||||
|
||||
with pytest.raises(type(error)) as raised:
|
||||
run_case(case, TestModel(custom_output_text="Hello", call_tools=[]))
|
||||
|
||||
assert raised.value is error
|
||||
+427
@@ -0,0 +1,427 @@
|
||||
"""Prod-replay checks score saved values, without calling a model."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from baserow.contrib.database.fields.constants import DeleteFieldStrategyEnum
|
||||
from baserow.contrib.database.fields.handler import FieldHandler
|
||||
from baserow.contrib.database.fields.models import FormulaField
|
||||
from baserow.contrib.database.rows.handler import RowHandler
|
||||
from baserow_enterprise.assistant.evals.datasets.prod_replay import (
|
||||
_check_fake_rows_into_typed_fields,
|
||||
_check_form_for_table_with_formula_field,
|
||||
_check_impossible_formula_request,
|
||||
_check_iso_week_number_formula,
|
||||
_check_page_inspection_existing_elements,
|
||||
_check_project_tracker_onboarding,
|
||||
_check_signed_amount_formula,
|
||||
_fake_rows_into_typed_fields_scenario,
|
||||
_form_for_table_with_formula_field_scenario,
|
||||
_impossible_formula_request_scenario,
|
||||
_iso_week_number_formula_scenario,
|
||||
_page_inspection_existing_elements_scenario,
|
||||
_project_tracker_onboarding_scenario,
|
||||
_signed_amount_formula_scenario,
|
||||
)
|
||||
from baserow_enterprise.assistant.evals.types import CheckResult, EvalRunOutput
|
||||
|
||||
|
||||
def _output(**overrides: Any) -> EvalRunOutput:
|
||||
values = {
|
||||
"answer": "Done.",
|
||||
"messages": [],
|
||||
"tool_calls": [],
|
||||
"tool_error_count": 0,
|
||||
"tool_error_hint": "",
|
||||
"sources": [],
|
||||
"request_count": 1,
|
||||
"duration_s": 0,
|
||||
}
|
||||
return EvalRunOutput(**(values | overrides))
|
||||
|
||||
|
||||
def _failed(checks: list[CheckResult]) -> set[str]:
|
||||
return {check.name for check in checks if not check.passed}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"enabled_fields, failed",
|
||||
[
|
||||
(("Customer", "Price"), set()),
|
||||
(("Customer",), {"form collects Customer and Price"}),
|
||||
(None, {"form view created", "form collects Customer and Price"}),
|
||||
],
|
||||
)
|
||||
def test_form_check_requires_a_form_that_collects_the_order_fields(
|
||||
data_fixture, enabled_fields, failed
|
||||
):
|
||||
scenario = _form_for_table_with_formula_field_scenario(data_fixture)
|
||||
table = scenario.refs["table"]
|
||||
if enabled_fields is not None:
|
||||
form = data_fixture.create_form_view(table=table)
|
||||
for field in table.field_set.filter(name__in=enabled_fields):
|
||||
data_fixture.create_form_view_field_option(form, field, enabled=True)
|
||||
|
||||
checks = _check_form_for_table_with_formula_field(None, scenario, _output())
|
||||
|
||||
assert _failed(checks) == failed
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"mutation, enabled_fields, expected",
|
||||
[
|
||||
("rename_customer", ("Price",), False),
|
||||
("rename_both", (), False),
|
||||
("rename_both", ("Customer", "Price"), True),
|
||||
("delete_price", ("Customer", "Price"), False),
|
||||
],
|
||||
)
|
||||
def test_form_check_keeps_original_field_requirements(
|
||||
data_fixture, mutation, enabled_fields, expected
|
||||
):
|
||||
scenario = _form_for_table_with_formula_field_scenario(data_fixture)
|
||||
table = scenario.refs["table"]
|
||||
fields = {field.name: field for field in table.field_set.all()}
|
||||
form = data_fixture.create_form_view(table=table)
|
||||
for name in enabled_fields:
|
||||
data_fixture.create_form_view_field_option(form, fields[name], enabled=True)
|
||||
if mutation == "delete_price":
|
||||
FieldHandler().delete_field(scenario.user, fields["Price"])
|
||||
else:
|
||||
FieldHandler().update_field(
|
||||
scenario.user, fields["Customer"].specific, name="Client"
|
||||
)
|
||||
if mutation == "rename_both":
|
||||
FieldHandler().update_field(
|
||||
scenario.user, fields["Price"].specific, name="Amount"
|
||||
)
|
||||
|
||||
checks = _check_form_for_table_with_formula_field(None, scenario, _output())
|
||||
|
||||
assert _failed(checks) == (
|
||||
set() if expected else {"form collects Customer and Price"}
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"inspected, failed", [(True, set()), (False, {"page elements inspected"})]
|
||||
)
|
||||
def test_page_inspection_check_requires_listing_the_elements(
|
||||
data_fixture, inspected, failed
|
||||
):
|
||||
scenario = _page_inspection_existing_elements_scenario(data_fixture)
|
||||
messages = [
|
||||
{
|
||||
"role": "assistant",
|
||||
"type": "ToolCallPart",
|
||||
"tool_name": "list_elements",
|
||||
"tool_call_id": "inspect",
|
||||
"args": {},
|
||||
}
|
||||
]
|
||||
|
||||
checks = _check_page_inspection_existing_elements(
|
||||
None, scenario, _output(messages=messages if inspected else [])
|
||||
)
|
||||
|
||||
assert _failed(checks) == failed
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"row_counts, failed",
|
||||
[
|
||||
({"Projects": 2, "Milestones": 3}, set()),
|
||||
({"Projects": 2, "Milestones": 0}, {"every table has example rows"}),
|
||||
({"Projects": 2}, {"Projects and Milestones tables created"}),
|
||||
],
|
||||
)
|
||||
def test_onboarding_check_requires_the_requested_tables_with_rows(
|
||||
data_fixture, row_counts, failed
|
||||
):
|
||||
scenario = _project_tracker_onboarding_scenario(data_fixture)
|
||||
for name, row_count in row_counts.items():
|
||||
table = data_fixture.create_database_table(
|
||||
database=scenario.refs["database"], name=name
|
||||
)
|
||||
primary = data_fixture.create_text_field(table=table, name="Name", primary=True)
|
||||
data_fixture.create_text_field(table=table, name="Owner")
|
||||
data_fixture.create_date_field(table=table, name="Deadline")
|
||||
if row_count:
|
||||
RowHandler().force_create_rows(
|
||||
scenario.user,
|
||||
table,
|
||||
[{primary.db_column: f"{name} {i}"} for i in range(row_count)],
|
||||
)
|
||||
|
||||
checks = _check_project_tracker_onboarding(None, scenario, _output())
|
||||
|
||||
assert _failed(checks) == failed
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"owner, deadline, expected",
|
||||
[
|
||||
("field", "field", True),
|
||||
("alias_field", "alias_field", True),
|
||||
("composite_field", "field", True),
|
||||
("field", "composite_field", True),
|
||||
("composite_field", "target_date", True),
|
||||
("field", "start_date", False),
|
||||
("missing", "field", False),
|
||||
("field", "missing", False),
|
||||
("missing", "missing", False),
|
||||
("linked_table", "linked_table", True),
|
||||
("unlinked_table", "field", False),
|
||||
("field", "unlinked_table", False),
|
||||
("unrelated_field", "field", False),
|
||||
("field", "unrelated_field", False),
|
||||
],
|
||||
)
|
||||
def test_onboarding_check_requires_owner_and_deadline_representation(
|
||||
data_fixture, owner, deadline, expected
|
||||
):
|
||||
scenario = _project_tracker_onboarding_scenario(data_fixture)
|
||||
database = scenario.refs["database"]
|
||||
tracker_tables = []
|
||||
for name in ("Projects", "Milestones"):
|
||||
table = data_fixture.create_database_table(database=database, name=name)
|
||||
primary = data_fixture.create_text_field(table=table, name="Name", primary=True)
|
||||
RowHandler().force_create_rows(
|
||||
scenario.user, table, [{primary.db_column: f"Example {name}"}]
|
||||
)
|
||||
tracker_tables.append(table)
|
||||
|
||||
for tracker, name, alias, representation in (
|
||||
(tracker_tables[0], "Owner", "Assignee", owner),
|
||||
(tracker_tables[1], "Deadline", "Due Date", deadline),
|
||||
):
|
||||
if representation == "missing":
|
||||
continue
|
||||
field_names = {
|
||||
"field": name,
|
||||
"alias_field": alias,
|
||||
"composite_field": f"Project {name}",
|
||||
"target_date": "Target Date",
|
||||
"start_date": "Start Date",
|
||||
}
|
||||
if representation in field_names:
|
||||
factory = (
|
||||
data_fixture.create_text_field
|
||||
if name == "Owner"
|
||||
else data_fixture.create_date_field
|
||||
)
|
||||
factory(table=tracker, name=field_names[representation])
|
||||
continue
|
||||
table = data_fixture.create_database_table(
|
||||
database=database,
|
||||
name="Unrelated" if representation == "unrelated_field" else name + "s",
|
||||
)
|
||||
primary = data_fixture.create_text_field(table=table, name="Name", primary=True)
|
||||
RowHandler().force_create_rows(
|
||||
scenario.user, table, [{primary.db_column: "Example"}]
|
||||
)
|
||||
if representation == "linked_table":
|
||||
data_fixture.create_link_row_field(
|
||||
table=tracker, link_row_table=table, name="Related records"
|
||||
)
|
||||
elif representation == "unrelated_field":
|
||||
data_fixture.create_text_field(table=table, name=name)
|
||||
|
||||
checks = _check_project_tracker_onboarding(None, scenario, _output())
|
||||
|
||||
assert _failed(checks) == (
|
||||
set() if expected else {"tracker represents owners and deadlines"}
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"formula, failed",
|
||||
[
|
||||
("datetime_format(field('Shipped On'), 'IW')", set()),
|
||||
(
|
||||
"datetime_format(field('Shipped On'), 'WW')",
|
||||
{"week numbers match ISO 8601"},
|
||||
),
|
||||
(
|
||||
None,
|
||||
{
|
||||
"week number formula field created",
|
||||
"formula is valid",
|
||||
"week numbers match ISO 8601",
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_iso_week_check_compares_the_saved_week_numbers(data_fixture, formula, failed):
|
||||
scenario = _iso_week_number_formula_scenario(data_fixture)
|
||||
if formula is not None:
|
||||
FieldHandler().create_field(
|
||||
scenario.user,
|
||||
scenario.refs["table"],
|
||||
"formula",
|
||||
name="Week",
|
||||
formula=formula,
|
||||
)
|
||||
|
||||
checks = _check_iso_week_number_formula(None, scenario, _output())
|
||||
|
||||
assert _failed(checks) == failed
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize("broken_first", [False, True])
|
||||
@pytest.mark.parametrize("kind", ["week", "signed"])
|
||||
def test_formula_checks_reject_broken_leftovers_in_either_order(
|
||||
data_fixture, kind, broken_first
|
||||
):
|
||||
if kind == "week":
|
||||
scenario = _iso_week_number_formula_scenario(data_fixture)
|
||||
good_name, broken_name = "ISO Week", "Week"
|
||||
formula = "datetime_format(field('Shipped On'), 'IW')"
|
||||
check = _check_iso_week_number_formula
|
||||
else:
|
||||
scenario = _signed_amount_formula_scenario(data_fixture)
|
||||
good_name, broken_name = "Signed Amount", "Old Signed Amount"
|
||||
formula = (
|
||||
"if(totext(field('Transaction Type')) = 'Credit', field('Amount'), "
|
||||
"field('Amount') * -1)"
|
||||
)
|
||||
check = _check_signed_amount_formula
|
||||
for broken in (broken_first, not broken_first):
|
||||
field = FieldHandler().create_field(
|
||||
scenario.user,
|
||||
scenario.refs["table"],
|
||||
"formula",
|
||||
name=broken_name if broken else good_name,
|
||||
formula="1" if broken else formula,
|
||||
)
|
||||
if broken:
|
||||
FormulaField.objects.filter(id=field.id).update(error="unsupported")
|
||||
|
||||
checks = check(None, scenario, _output())
|
||||
|
||||
# The selected formula's saved numeric values are correct in both orders.
|
||||
assert _failed(checks) == {"formula is valid"}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"broken, failed", [(False, set()), (True, {"no broken formula left behind"})]
|
||||
)
|
||||
def test_impossible_formula_check_rejects_a_broken_formula(
|
||||
data_fixture, broken, failed
|
||||
):
|
||||
scenario = _impossible_formula_request_scenario(data_fixture)
|
||||
if broken:
|
||||
field = FieldHandler().create_field(
|
||||
scenario.user, scenario.refs["table"], "formula", name="Pages", formula="1"
|
||||
)
|
||||
FormulaField.objects.filter(id=field.id).update(error="unsupported")
|
||||
|
||||
checks = _check_impossible_formula_request(
|
||||
None, scenario, _output(answer="Formulas cannot download files.")
|
||||
)
|
||||
|
||||
assert _failed(checks) == failed
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"defect, failed",
|
||||
[
|
||||
(None, set()),
|
||||
("fewer_rows", {"30 employees created"}),
|
||||
("blank_full_name", {"every row has valid typed values"}),
|
||||
("blank_team", {"every row has valid typed values"}),
|
||||
("blank_phone", {"every row has valid typed values"}),
|
||||
("blank_level", {"every row has valid typed values"}),
|
||||
("blank_start_date", {"every row has valid typed values"}),
|
||||
("blank_notes", {"every row has valid typed values"}),
|
||||
("blank_score", {"every row has valid typed values"}),
|
||||
("deleted_notes", {"every row has valid typed values"}),
|
||||
("removed_notes", {"every row has valid typed values"}),
|
||||
],
|
||||
)
|
||||
def test_employee_rows_check_requires_valid_typed_values(data_fixture, defect, failed):
|
||||
scenario = _fake_rows_into_typed_fields_scenario(data_fixture)
|
||||
fields = scenario.refs["fields"]
|
||||
level = fields["Level"].select_options.first()
|
||||
rows = [
|
||||
{
|
||||
fields["Full Name"].db_column: f"Employee {i}",
|
||||
fields["Team"].db_column: "Operations",
|
||||
fields["Phone"].db_column: "555-0100",
|
||||
fields["Level"].db_column: level.id,
|
||||
fields["Start Date"].db_column: "2025-01-15",
|
||||
fields["Notes"].db_column: "Sample employee",
|
||||
fields["Performance Score"].db_column: 4,
|
||||
}
|
||||
for i in range(30)
|
||||
]
|
||||
if defect == "fewer_rows":
|
||||
rows = rows[:29]
|
||||
elif defect is not None and defect not in {"deleted_notes", "removed_notes"}:
|
||||
omitted_field = {
|
||||
"blank_full_name": "Full Name",
|
||||
"blank_team": "Team",
|
||||
"blank_phone": "Phone",
|
||||
"blank_level": "Level",
|
||||
"blank_start_date": "Start Date",
|
||||
"blank_notes": "Notes",
|
||||
"blank_score": "Performance Score",
|
||||
}[defect]
|
||||
rows[3].pop(fields[omitted_field].db_column)
|
||||
RowHandler().force_create_rows(scenario.user, scenario.refs["table"], rows)
|
||||
if defect in {"deleted_notes", "removed_notes"}:
|
||||
# Keep the scenario's original field identity even after permanent removal.
|
||||
notes = FieldHandler().get_field(fields["Notes"].id)
|
||||
FieldHandler().delete_field(
|
||||
scenario.user,
|
||||
notes,
|
||||
delete_strategy=(
|
||||
DeleteFieldStrategyEnum.TRASH
|
||||
if defect == "deleted_notes"
|
||||
else DeleteFieldStrategyEnum.PERMANENTLY_DELETE
|
||||
),
|
||||
)
|
||||
if defect == "deleted_notes":
|
||||
row = scenario.refs["table"].get_model().objects.first()
|
||||
assert getattr(row, fields["Notes"].db_column) == "Sample employee"
|
||||
|
||||
checks = _check_fake_rows_into_typed_fields(None, scenario, _output())
|
||||
|
||||
assert _failed(checks) == failed
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize(
|
||||
"formula, failed",
|
||||
[
|
||||
(
|
||||
"if(totext(field('Transaction Type')) = 'Credit', field('Amount'), "
|
||||
"field('Amount') * -1)",
|
||||
set(),
|
||||
),
|
||||
("field('Amount')", {"signed amounts match the transaction type"}),
|
||||
],
|
||||
)
|
||||
def test_signed_amount_check_compares_the_saved_values(data_fixture, formula, failed):
|
||||
scenario = _signed_amount_formula_scenario(data_fixture)
|
||||
FieldHandler().create_field(
|
||||
scenario.user,
|
||||
scenario.refs["table"],
|
||||
"formula",
|
||||
name="Signed Amount",
|
||||
formula=formula,
|
||||
)
|
||||
|
||||
checks = _check_signed_amount_formula(None, scenario, _output())
|
||||
|
||||
assert _failed(checks) == failed
|
||||
+325
-35
@@ -1,22 +1,37 @@
|
||||
import json
|
||||
import subprocess
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.core.management import call_command
|
||||
from django.core.management.base import CommandError
|
||||
from django.db import OperationalError
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from loguru import logger
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
||||
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
|
||||
InMemorySpanExporter,
|
||||
)
|
||||
from opentelemetry.trace import StatusCode
|
||||
from phoenix.client.resources.datasets import Dataset
|
||||
from phoenix.client.resources.experiments import Experiments
|
||||
from pydantic_ai.exceptions import (
|
||||
ModelHTTPError,
|
||||
UnexpectedModelBehavior,
|
||||
UsageLimitExceeded,
|
||||
UserError,
|
||||
)
|
||||
|
||||
from baserow_enterprise.assistant.deps import AgentMode
|
||||
from baserow_enterprise.assistant.evals import gitinfo, registry
|
||||
from baserow_enterprise.assistant.evals.control import RunControl
|
||||
from baserow_enterprise.assistant.evals.harness import (
|
||||
EvalCaseCleanupError,
|
||||
EvalCaseModelError,
|
||||
EvalCaseTimeout,
|
||||
)
|
||||
from baserow_enterprise.assistant.evals.judge import JudgeVerdict
|
||||
@@ -93,6 +108,20 @@ def _make_output(**overrides) -> EvalRunOutput:
|
||||
|
||||
|
||||
class TestGetGitInfo:
|
||||
def test_evaluator_fingerprint_tracks_nested_check_source_not_snapshot(
|
||||
self, tmp_path, monkeypatch
|
||||
):
|
||||
monkeypatch.setattr(gitinfo, "__file__", str(tmp_path / "gitinfo.py"))
|
||||
checks = tmp_path / "datasets"
|
||||
checks.mkdir()
|
||||
source = checks / "builder.py"
|
||||
source.write_text("return old_checks\n")
|
||||
original = gitinfo.get_evaluator_source_hash()
|
||||
(tmp_path / "baseline.json").write_text('{"old_results": true}')
|
||||
assert gitinfo.get_evaluator_source_hash() == original
|
||||
source.write_text("return stronger_checks\n")
|
||||
assert gitinfo.get_evaluator_source_hash() != original
|
||||
|
||||
def test_uses_git_subprocess_when_available(self, monkeypatch):
|
||||
monkeypatch.delenv("BASEROW_EVAL_GIT_BRANCH", raising=False)
|
||||
monkeypatch.delenv("BASEROW_EVAL_GIT_COMMIT", raising=False)
|
||||
@@ -528,6 +557,27 @@ class _ExampleStub:
|
||||
|
||||
|
||||
class TestRunExperimentForFullDataset:
|
||||
@pytest.mark.parametrize("case_ids", [None, ["docs/example"]])
|
||||
def test_docs_without_knowledge_base_fails_before_creating_experiment(
|
||||
self, case_ids
|
||||
):
|
||||
client = _FakeClient(_FakeDataset([]))
|
||||
with (
|
||||
patch(
|
||||
"baserow_enterprise.assistant.evals.run.get_phoenix_client",
|
||||
return_value=client,
|
||||
),
|
||||
patch(
|
||||
"baserow_enterprise.assistant.evals.run.KnowledgeBaseHandler"
|
||||
) as mock_kb_cls,
|
||||
):
|
||||
mock_kb_cls.return_value.can_search.return_value = False
|
||||
with pytest.raises(ValueError, match="sync_knowledge_base"):
|
||||
run_experiment_for("kuma-docs", "groq:test-model", case_ids=case_ids)
|
||||
|
||||
assert not client.experiments.run_experiment_calls
|
||||
assert not client.experiments.create_calls
|
||||
|
||||
def test_calls_run_experiment_with_dataset_and_evaluators(self):
|
||||
registry.register_case(_make_case("db/case-1"))
|
||||
dataset = _FakeDataset([])
|
||||
@@ -571,7 +621,8 @@ class TestRunExperimentForFullDataset:
|
||||
assert call_kwargs["experiment_name"] == "exp-name"
|
||||
assert call_kwargs["experiment_metadata"] == {
|
||||
"model": "groq:test-model",
|
||||
"harness_version": 2,
|
||||
"harness_version": 7,
|
||||
"evaluator_source_hash": gitinfo.get_evaluator_source_hash(),
|
||||
"runner_run_id": "local-run",
|
||||
"model_settings": _expected_model_settings("groq:test-model"),
|
||||
"judge_model": "groq:openai/gpt-oss-120b",
|
||||
@@ -614,7 +665,8 @@ class TestRunExperimentForFullDataset:
|
||||
call_kwargs = client.experiments.run_experiment_calls[0]
|
||||
assert call_kwargs["experiment_metadata"] == {
|
||||
"model": "groq:test-model",
|
||||
"harness_version": 2,
|
||||
"harness_version": 7,
|
||||
"evaluator_source_hash": gitinfo.get_evaluator_source_hash(),
|
||||
"runner_run_id": None,
|
||||
"model_settings": _expected_model_settings("groq:test-model"),
|
||||
"judge_model": "groq:openai/gpt-oss-120b",
|
||||
@@ -1065,7 +1117,8 @@ class TestRunExperimentForCaseSubset:
|
||||
assert create_kwargs["repetitions"] == 1
|
||||
assert create_kwargs["experiment_metadata"] == {
|
||||
"model": "groq:test-model",
|
||||
"harness_version": 2,
|
||||
"harness_version": 7,
|
||||
"evaluator_source_hash": gitinfo.get_evaluator_source_hash(),
|
||||
"runner_run_id": None,
|
||||
"model_settings": _expected_model_settings("groq:test-model"),
|
||||
"judge_model": "groq:openai/gpt-oss-120b",
|
||||
@@ -1982,32 +2035,6 @@ class TestFullDatasetProgressAndStop:
|
||||
|
||||
assert control.total == 12
|
||||
|
||||
def test_a_phoenix_retry_cannot_push_the_counter_past_the_total(self):
|
||||
"""SyncExecutor re-enters the task on failure, so counting every call
|
||||
would report more finished cases than the dataset has."""
|
||||
|
||||
registry.register_case(_make_case("db/case-1"))
|
||||
client = _FakeClient(_FakeDataset([object()]))
|
||||
control = RunControl()
|
||||
task = self._task_for(client, control, [], runs=1)
|
||||
|
||||
example = _ExampleStub("db/case-1", example_id="ex-retried")
|
||||
with (
|
||||
patch(
|
||||
"baserow_enterprise.assistant.evals.run.run_case",
|
||||
return_value=(_make_output(), []),
|
||||
),
|
||||
patch(
|
||||
"baserow_enterprise.assistant.evals.run.KnowledgeBaseHandler"
|
||||
) as mock_kb_cls,
|
||||
):
|
||||
mock_kb_cls.return_value.can_search.return_value = True
|
||||
for _attempt in range(4):
|
||||
task(example)
|
||||
|
||||
assert control.total == 1
|
||||
assert control.completed == 1
|
||||
|
||||
def test_repetitions_of_one_example_each_count_once(self):
|
||||
registry.register_case(_make_case("db/case-1"))
|
||||
client = _FakeClient(_FakeDataset([object()]))
|
||||
@@ -2025,11 +2052,11 @@ class TestFullDatasetProgressAndStop:
|
||||
) as mock_kb_cls,
|
||||
):
|
||||
mock_kb_cls.return_value.can_search.return_value = True
|
||||
for _repetition in range(5):
|
||||
for _repetition in range(3):
|
||||
task(example)
|
||||
|
||||
assert control.total == 3
|
||||
assert control.completed == 3, "capped at the repetition count"
|
||||
assert control.completed == 3
|
||||
|
||||
def test_a_stopped_run_skips_the_case_without_calling_the_agent(self):
|
||||
registry.register_case(_make_case("db/case-1"))
|
||||
@@ -2069,7 +2096,7 @@ class TestTimeoutIsRecordedNotRaised:
|
||||
assert control.completed == 0
|
||||
assert client.experiments.log_run_calls == []
|
||||
|
||||
def test_cleanup_failure_stops_phoenix_retries_and_reaches_the_runner(self):
|
||||
def test_cleanup_failure_skips_remaining_cases_and_reaches_the_runner(self):
|
||||
client = _two_case_client()
|
||||
control = RunControl()
|
||||
calls = []
|
||||
@@ -2078,17 +2105,16 @@ class TestTimeoutIsRecordedNotRaised:
|
||||
calls.append(case.id)
|
||||
raise EvalCaseCleanupError("Restart the eval runner")
|
||||
|
||||
def retry_task(**kwargs):
|
||||
def process_cases(**kwargs):
|
||||
task = kwargs["task"]
|
||||
with pytest.raises(EvalCaseCleanupError):
|
||||
task(_ExampleStub("db/case-1"))
|
||||
assert task(_ExampleStub("db/case-1")) == {"skipped": "run stopped"}
|
||||
assert task(_ExampleStub("db/case-2")) == {"skipped": "run stopped"}
|
||||
return {"experiment_id": "exp-1", "dataset_id": "ds-1"}
|
||||
|
||||
with (
|
||||
_subset_env(client, run_case_side_effect=fail_cleanup),
|
||||
patch.object(client.experiments, "run_experiment", retry_task),
|
||||
patch.object(client.experiments, "run_experiment", process_cases),
|
||||
pytest.raises(EvalCaseCleanupError, match="Restart the eval runner"),
|
||||
):
|
||||
run_experiment_for("kuma-database", "groq:test-model", control=control)
|
||||
@@ -2107,6 +2133,8 @@ class TestTimeoutIsRecordedNotRaised:
|
||||
result = run_case_for_experiment(case, "groq:test-model", True)
|
||||
|
||||
assert result["timed_out"] is True
|
||||
assert result["request_count"] is None
|
||||
assert result["tool_error_count"] is None
|
||||
assert result["score"] == 0.0
|
||||
assert result["passed"] is False
|
||||
assert result["checks"] == [
|
||||
@@ -2160,3 +2188,265 @@ class TestTimeoutIsRecordedNotRaised:
|
||||
assert calls == ["db/case-1", "db/case-2"], "the run stopped at the timeout"
|
||||
assert control.completed == 2
|
||||
assert len(client.experiments.log_run_calls) == 2
|
||||
|
||||
|
||||
class TestModelFailureIsRecordedNotRaised:
|
||||
@pytest.mark.parametrize(
|
||||
"error_type", [UsageLimitExceeded, UnexpectedModelBehavior]
|
||||
)
|
||||
def test_failure_is_scored_without_inventing_unavailable_counts(self, error_type):
|
||||
case = _make_case("docs/exhausted", requires_knowledge_base=True)
|
||||
error = error_type("The next request would exceed the request_limit of 15")
|
||||
reason = str(error)
|
||||
with patch(
|
||||
"baserow_enterprise.assistant.evals.run.run_case",
|
||||
side_effect=EvalCaseModelError(error),
|
||||
):
|
||||
result = run_case_for_experiment(case, "groq:test-model", True)
|
||||
|
||||
assert result["usage_limit_exceeded"] is (error_type is UsageLimitExceeded)
|
||||
assert result["passed"] is False
|
||||
assert result["score"] == 0.0
|
||||
assert result["judge_docs"] is False
|
||||
assert result["execution_error"] == reason
|
||||
assert result["tool_error_count"] is None
|
||||
assert result["request_count"] is None
|
||||
assert result["duration_s"] >= 0
|
||||
assert result["checks"] == [
|
||||
{
|
||||
"name": (
|
||||
"completed_within_request_limit"
|
||||
if error_type is UsageLimitExceeded
|
||||
else "completed_without_execution_error"
|
||||
),
|
||||
"passed": False,
|
||||
"hint": reason,
|
||||
}
|
||||
]
|
||||
assert "skipped" not in result
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error_type", [UsageLimitExceeded, UnexpectedModelBehavior]
|
||||
)
|
||||
def test_subset_records_error_trace_and_continues_without_retrying(
|
||||
self, error_type
|
||||
):
|
||||
client = _two_case_client()
|
||||
control = RunControl()
|
||||
exporter = InMemorySpanExporter()
|
||||
provider = TracerProvider()
|
||||
provider.add_span_processor(SimpleSpanProcessor(exporter))
|
||||
calls = []
|
||||
|
||||
def exhaust_first(case, *args, **kwargs):
|
||||
calls.append((case.id, case.max_iters))
|
||||
if len(calls) == 1:
|
||||
raise EvalCaseModelError(
|
||||
error_type("request or tool retry limit exceeded")
|
||||
)
|
||||
return _make_output(), []
|
||||
|
||||
with (
|
||||
_subset_env(client, run_case_side_effect=exhaust_first),
|
||||
patch(
|
||||
"baserow_enterprise.assistant.evals.run.get_assistant_tracer_provider",
|
||||
return_value=provider,
|
||||
),
|
||||
):
|
||||
run_experiment_for(
|
||||
"kuma-database",
|
||||
"groq:test-model",
|
||||
case_ids=["db/case-1", "db/case-2"],
|
||||
control=control,
|
||||
)
|
||||
|
||||
assert calls == [("db/case-1", 15), ("db/case-2", 15)]
|
||||
assert control.completed == 2
|
||||
first, second = client.experiments.log_run_calls
|
||||
assert first["output"]["score"] == 0
|
||||
assert second["output"]["passed"] is True
|
||||
spans = {s.name: s for s in exporter.get_finished_spans()}
|
||||
failed_span = spans["Task: db/case-1"]
|
||||
assert failed_span.status.status_code == StatusCode.ERROR
|
||||
assert any(event.name == "exception" for event in failed_span.events)
|
||||
assert first["trace_id"] == format(failed_span.context.trace_id, "032x")
|
||||
assert spans["Task: db/case-2"].status.status_code == StatusCode.OK
|
||||
|
||||
|
||||
class TestExecutionErrorsRemainUngraded:
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
UserError("Missing API key"),
|
||||
ModelHTTPError(404, "unknown-model"),
|
||||
OperationalError("Database connection lost"),
|
||||
RuntimeError("Unexpected tool failure"),
|
||||
AttributeError("A case check failed"),
|
||||
UsageLimitExceeded("Raised outside the agent run"),
|
||||
UnexpectedModelBehavior("Raised outside the agent run"),
|
||||
],
|
||||
ids=["config", "provider", "database", "tool", "check", "usage", "model"],
|
||||
)
|
||||
def test_unclassified_errors_propagate_instead_of_becoming_scores(self, error):
|
||||
with (
|
||||
patch("baserow_enterprise.assistant.evals.run.run_case", side_effect=error),
|
||||
pytest.raises(type(error)) as raised,
|
||||
):
|
||||
run_case_for_experiment(_make_case("db/error"), "groq:test-model", True)
|
||||
|
||||
assert raised.value is error
|
||||
|
||||
def test_real_phoenix_records_errors_once_without_scoring_them(self):
|
||||
client = _two_case_client()
|
||||
dataset_info = {"id": "ds-1", "name": "kuma-database"}
|
||||
examples_data = {
|
||||
"version_id": "v1",
|
||||
"examples": client.datasets._dataset.examples,
|
||||
}
|
||||
client.datasets._dataset = Dataset(dataset_info, examples_data)
|
||||
experiment = {
|
||||
"id": "exp-1",
|
||||
"dataset_id": "ds-1",
|
||||
"dataset_version_id": "v1",
|
||||
"project_name": None,
|
||||
"metadata": {},
|
||||
}
|
||||
saved_runs, evaluations, calls, log_records = {}, [], [], []
|
||||
control = RunControl()
|
||||
error = OperationalError("Database connection lost")
|
||||
|
||||
def respond(request):
|
||||
path = request.url.path
|
||||
if request.method == "POST":
|
||||
body = json.loads(request.content)
|
||||
if path.endswith("/runs"):
|
||||
node_id = body["dataset_example_id"]
|
||||
data = saved_runs[node_id] = {**body, "id": f"run-{node_id}"}
|
||||
elif path.endswith("/experiment_evaluations"):
|
||||
evaluations.append(body)
|
||||
data = {"id": f"evaluation-{len(evaluations)}"}
|
||||
elif path.endswith("/experiments"):
|
||||
data = experiment
|
||||
else:
|
||||
raise AssertionError(f"Unexpected request: {request.method} {path}")
|
||||
elif path.endswith("/runs"):
|
||||
data = list(saved_runs.values())
|
||||
elif path.endswith("/examples"):
|
||||
data = examples_data
|
||||
elif path.endswith("/datasets/ds-1"):
|
||||
data = dataset_info
|
||||
elif path.endswith("/experiments/exp-1"):
|
||||
data = experiment
|
||||
else:
|
||||
raise AssertionError(f"Unexpected request: {request.method} {path}")
|
||||
return httpx.Response(200, json={"data": data})
|
||||
|
||||
def fail_first(case, *args, **kwargs):
|
||||
calls.append(case.id)
|
||||
if case.id == "db/case-1":
|
||||
raise error
|
||||
return _make_output(), [CheckResult("saved state is correct", True)]
|
||||
|
||||
with (
|
||||
httpx.Client(
|
||||
base_url="http://phoenix.test/",
|
||||
transport=httpx.MockTransport(respond),
|
||||
) as http_client,
|
||||
_subset_env(client, run_case_side_effect=fail_first),
|
||||
patch(
|
||||
"phoenix.client.resources.experiments._get_tracer",
|
||||
return_value=(TracerProvider().get_tracer("test"), Resource.create({})),
|
||||
),
|
||||
ExitStack() as stack,
|
||||
):
|
||||
client.experiments = Experiments(http_client)
|
||||
sink = logger.add(lambda message: log_records.append(message.record))
|
||||
stack.callback(logger.remove, sink)
|
||||
result = run_experiment_for(
|
||||
"kuma-database", "groq:test-model", control=control
|
||||
)
|
||||
|
||||
assert calls == ["db/case-1", "db/case-2"]
|
||||
assert control.total == 2
|
||||
assert control.completed == 1
|
||||
assert result["task_runs"] == list(saved_runs.values())
|
||||
assert saved_runs["node-1"]["output"] is None
|
||||
assert saved_runs["node-1"]["error"] == repr(error)
|
||||
failed_annotations = [
|
||||
annotation
|
||||
for annotation in evaluations
|
||||
if annotation["experiment_run_id"] == "run-node-1"
|
||||
]
|
||||
assert {annotation["name"] for annotation in failed_annotations} == {
|
||||
"checklist",
|
||||
"passed",
|
||||
"answer_quality",
|
||||
}
|
||||
assert all(
|
||||
annotation["error"] is None and annotation["result"] == {}
|
||||
for annotation in failed_annotations
|
||||
)
|
||||
assert saved_runs["node-2"]["output"]["passed"] is True
|
||||
(logged_error,) = [record for record in log_records if record["exception"]]
|
||||
assert "db/case-1" in logged_error["message"]
|
||||
assert logged_error["exception"].value is error
|
||||
|
||||
def test_subset_records_an_error_run_without_scores_and_stops(self):
|
||||
client = _two_case_client()
|
||||
control = RunControl()
|
||||
exporter = InMemorySpanExporter()
|
||||
provider = TracerProvider()
|
||||
provider.add_span_processor(SimpleSpanProcessor(exporter))
|
||||
error = AttributeError("A case check failed")
|
||||
calls = []
|
||||
|
||||
def fail_check(case, *args, **kwargs):
|
||||
calls.append(case.id)
|
||||
raise error
|
||||
|
||||
with (
|
||||
_subset_env(client, run_case_side_effect=fail_check),
|
||||
patch(
|
||||
"baserow_enterprise.assistant.evals.run.get_assistant_tracer_provider",
|
||||
return_value=provider,
|
||||
),
|
||||
pytest.raises(AttributeError) as raised,
|
||||
):
|
||||
run_experiment_for(
|
||||
"kuma-database",
|
||||
"groq:test-model",
|
||||
case_ids=["db/case-1", "db/case-2"],
|
||||
control=control,
|
||||
)
|
||||
|
||||
assert raised.value is error
|
||||
assert calls == ["db/case-1"]
|
||||
assert control.completed == 0
|
||||
assert client.experiments.log_evaluation_calls == []
|
||||
(logged,) = client.experiments.log_run_calls
|
||||
assert logged["output"] is None
|
||||
assert logged["error"] == repr(error)
|
||||
assert logged["repetition_number"] == 1
|
||||
assert logged["end_time"] >= logged["start_time"]
|
||||
(span,) = exporter.get_finished_spans()
|
||||
assert span.status.status_code == StatusCode.ERROR
|
||||
assert any(event.name == "exception" for event in span.events)
|
||||
assert logged["trace_id"] == format(span.context.trace_id, "032x")
|
||||
|
||||
def test_error_recording_failure_does_not_replace_the_original_error(self):
|
||||
client = _two_case_client()
|
||||
error = AttributeError("A case check failed")
|
||||
|
||||
with (
|
||||
_subset_env(client, run_case_side_effect=error),
|
||||
patch.object(
|
||||
client.experiments, "log_run", side_effect=RuntimeError("Phoenix down")
|
||||
),
|
||||
pytest.raises(AttributeError) as raised,
|
||||
):
|
||||
run_experiment_for(
|
||||
"kuma-database", "groq:test-model", case_ids=["db/case-1"]
|
||||
)
|
||||
|
||||
assert raised.value is error
|
||||
assert client.experiments.log_evaluation_calls == []
|
||||
+340
-7
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import io
|
||||
import json
|
||||
import queue as queue_module
|
||||
import re
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
@@ -16,6 +17,24 @@ import pytest
|
||||
|
||||
from baserow_enterprise.assistant.evals import registry, runner
|
||||
from baserow_enterprise.assistant.evals.types import EvalCase
|
||||
from baserow_enterprise.management.commands import (
|
||||
assistant_eval_runner as eval_runner_command,
|
||||
)
|
||||
|
||||
from . import js_source
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", range(1, runner.HARNESS_VERSION + 1))
|
||||
def test_model_settings_remain_verified_after_scoring_version_change(version):
|
||||
label = runner._settings_label(
|
||||
{"harness_version": version, "model_settings": {"temperature": 0.3}}
|
||||
)
|
||||
|
||||
assert label == (
|
||||
"model settings unverified (legacy harness)"
|
||||
if version == 1
|
||||
else "temperature=0.3"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -331,12 +350,28 @@ class TestResultsEndpoint:
|
||||
"name": "baseline",
|
||||
"createdAt": "2026-08-25T10:00:00Z",
|
||||
"metadata": {"model": "m", "git_branch": "b", "git_commit": "c"},
|
||||
"repetitions": 2,
|
||||
"runCount": 2,
|
||||
"expectedRunCount": 2,
|
||||
"datasetVersion": {"id": "version-1"},
|
||||
"averageRunLatencyMs": 6000.0,
|
||||
"costSummary": {"total": {"cost": 0.05, "tokens": 120000}},
|
||||
"annotationSummaries": [
|
||||
{"annotationName": "passed", "meanScore": 0.8},
|
||||
{"annotationName": "answer_quality", "meanScore": None},
|
||||
{
|
||||
"annotationName": "checklist",
|
||||
"meanScore": 0.9,
|
||||
"scoreCount": 2,
|
||||
},
|
||||
{
|
||||
"annotationName": "passed",
|
||||
"meanScore": 0.8,
|
||||
"scoreCount": 2,
|
||||
},
|
||||
{
|
||||
"annotationName": "answer_quality",
|
||||
"meanScore": None,
|
||||
"scoreCount": 0,
|
||||
},
|
||||
],
|
||||
}
|
||||
]
|
||||
@@ -349,7 +384,18 @@ class TestResultsEndpoint:
|
||||
assert dataset["name"] == "kuma-database"
|
||||
assert dataset["case_count"] == 1
|
||||
experiment = dataset["experiments"][0]
|
||||
assert experiment["scores"] == {"passed": 0.8}
|
||||
assert experiment["scores"] == {"checklist": 0.9, "passed": 0.8}
|
||||
assert experiment["run_count"] == 2
|
||||
assert experiment["expected_run_count"] == 2
|
||||
assert experiment["repetitions"] == 2
|
||||
assert experiment["scored_run_count"] == 2
|
||||
assert experiment["score_counts"] == {
|
||||
"checklist": 2,
|
||||
"passed": 2,
|
||||
"answer_quality": 0,
|
||||
}
|
||||
assert experiment["complete"] is True
|
||||
assert experiment["dataset_version_id"] == "version-1"
|
||||
assert experiment["git_label"] == "b@c"
|
||||
assert experiment["time_s"] == 12.0
|
||||
assert experiment["cost"] == 0.05
|
||||
@@ -358,6 +404,130 @@ class TestResultsEndpoint:
|
||||
"http://localhost:6060/datasets/ds-node-1/compare?experimentId=exp-1"
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name, metadata, imported, source_hash",
|
||||
[
|
||||
(
|
||||
"renamed historical run",
|
||||
{"baseline": True, "evaluator_source_hash": "old-checks"},
|
||||
True,
|
||||
"old-checks",
|
||||
),
|
||||
("baseline", {}, False, None),
|
||||
(
|
||||
"candidate",
|
||||
{"baseline": False, "evaluator_source_hash": "current-checks"},
|
||||
False,
|
||||
"current-checks",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_results_json_preserves_comparison_provenance(
|
||||
self, monkeypatch, name, metadata, imported, source_hash
|
||||
):
|
||||
_register_case("database/list-tables")
|
||||
monkeypatch.setattr(runner, "_dataset_ids", {"kuma-database": "ds-node-1"})
|
||||
monkeypatch.setattr(
|
||||
runner,
|
||||
"_experiment_summaries",
|
||||
lambda node_id: [{"id": "exp-1", "name": name, "metadata": metadata}],
|
||||
)
|
||||
|
||||
_status, _headers, body = _call_wsgi(
|
||||
runner.make_wsgi_app(), "GET", "/results.json"
|
||||
)
|
||||
|
||||
experiment = json.loads(body)["datasets"][0]["experiments"][0]
|
||||
assert experiment["imported_baseline"] is imported
|
||||
assert experiment["evaluator_source_hash"] == source_hash
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"expected_runs, repetitions, expected_cases",
|
||||
[
|
||||
(2, 1, 2),
|
||||
(6, 3, 2),
|
||||
(2, None, 2),
|
||||
(None, 1, None),
|
||||
(0, 1, None),
|
||||
(3, 2, None),
|
||||
(-2, 1, None),
|
||||
(2, -1, None),
|
||||
],
|
||||
)
|
||||
def test_results_json_counts_recorded_cases_instead_of_current_registry(
|
||||
self, monkeypatch, expected_runs, repetitions, expected_cases
|
||||
):
|
||||
_register_case("database/current-case")
|
||||
monkeypatch.setattr(runner, "_dataset_ids", {"kuma-database": "ds-node-1"})
|
||||
monkeypatch.setattr(
|
||||
runner,
|
||||
"_experiment_summaries",
|
||||
lambda node_id: [
|
||||
{
|
||||
"id": "exp-1",
|
||||
"expectedRunCount": expected_runs,
|
||||
"repetitions": repetitions,
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
_status, _headers, body = _call_wsgi(
|
||||
runner.make_wsgi_app(), "GET", "/results.json"
|
||||
)
|
||||
|
||||
dataset = json.loads(body)["datasets"][0]
|
||||
assert dataset["case_count"] == 1
|
||||
assert dataset["experiments"][0]["case_count"] == expected_cases
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("score_counts", "scored_run_count"),
|
||||
[
|
||||
({"checklist": 1, "passed": 2}, 1),
|
||||
({"checklist": 2, "passed": 1}, 1),
|
||||
({"checklist": 0, "passed": 0}, 0),
|
||||
],
|
||||
ids=("partial-checklist", "partial-passed", "all-skipped"),
|
||||
)
|
||||
def test_results_json_marks_incomplete_without_all_mandatory_scores(
|
||||
self, monkeypatch, score_counts, scored_run_count
|
||||
):
|
||||
_register_case("database/list-tables")
|
||||
monkeypatch.setattr(runner, "_dataset_ids", {"kuma-database": "ds-node-1"})
|
||||
summaries = [
|
||||
{
|
||||
"id": "exp-1",
|
||||
"name": "candidate",
|
||||
"runCount": 2,
|
||||
"expectedRunCount": 2,
|
||||
"annotationSummaries": [
|
||||
{
|
||||
"annotationName": name,
|
||||
"meanScore": 1.0 if count else None,
|
||||
"scoreCount": count,
|
||||
}
|
||||
for name, count in score_counts.items()
|
||||
],
|
||||
}
|
||||
]
|
||||
monkeypatch.setattr(runner, "_experiment_summaries", lambda node_id: summaries)
|
||||
app = runner.make_wsgi_app()
|
||||
|
||||
_status, _headers, body = _call_wsgi(app, "GET", "/results.json")
|
||||
|
||||
experiment = json.loads(body)["datasets"][0]["experiments"][0]
|
||||
assert experiment["run_count"] == 2
|
||||
assert experiment["expected_run_count"] == 2
|
||||
assert experiment["scored_run_count"] == scored_run_count
|
||||
assert experiment["score_counts"] == score_counts
|
||||
assert experiment["complete"] is False
|
||||
|
||||
def test_results_summary_query_requests_completeness_counts(self):
|
||||
assert "expectedRunCount" in runner._EXPERIMENT_SUMMARIES_QUERY
|
||||
assert "scoreCount" in runner._EXPERIMENT_SUMMARIES_QUERY
|
||||
|
||||
def test_results_summary_query_requests_the_case_population(self):
|
||||
assert "datasetVersion { id }" in runner._EXPERIMENT_SUMMARIES_QUERY
|
||||
|
||||
def test_results_json_falls_back_to_frozen_baseline_totals(self, monkeypatch):
|
||||
_register_case("database/list-tables")
|
||||
monkeypatch.setattr(runner, "_dataset_ids", {"kuma-database": "ds-node-1"})
|
||||
@@ -406,6 +576,135 @@ class TestResultsEndpoint:
|
||||
|
||||
assert b'data-tab="__results"' in body
|
||||
|
||||
def test_results_tab_compares_across_repetition_counts(self):
|
||||
"""A --runs 3 experiment must still show deltas against a 1-pass
|
||||
baseline: means compare directly, totals are divided by repetitions."""
|
||||
|
||||
_register_case("database/list-tables")
|
||||
app = runner.make_wsgi_app()
|
||||
|
||||
_status, _headers, body = _call_wsgi(app, "GET", "/")
|
||||
|
||||
page = body.decode("utf-8")
|
||||
assert (
|
||||
"experiment.expected_run_count === baseline.expected_run_count" not in page
|
||||
)
|
||||
assert "candidate.repetitions" in page
|
||||
assert 'perPass(experiment, "time_s")' in page
|
||||
assert 'perPass(baseline, "cost")' in page
|
||||
assert "time and cost shown per pass" in page
|
||||
|
||||
def test_results_tab_compares_only_the_same_case_population(self):
|
||||
"""Different recorded populations must not receive baseline deltas."""
|
||||
|
||||
_register_case("database/list-tables")
|
||||
app = runner.make_wsgi_app()
|
||||
|
||||
_status, _headers, body = _call_wsgi(app, "GET", "/")
|
||||
|
||||
page = body.decode("utf-8")
|
||||
assert "experiment.dataset_version_id === baseline.dataset_version_id" in page
|
||||
|
||||
def test_results_tab_rejects_imported_or_unverified_comparisons(self):
|
||||
"""Imports carry today's Phoenix version, not their original population."""
|
||||
|
||||
_register_case("database/list-tables")
|
||||
_status, _headers, body = _call_wsgi(runner.make_wsgi_app(), "GET", "/")
|
||||
renderer = js_source.function_body(
|
||||
js_source.inline_script(body.decode("utf-8")), "renderResults"
|
||||
)
|
||||
|
||||
assert "(experiment && experiment.imported_baseline)" in renderer
|
||||
assert "(baseline && baseline.imported_baseline)" in renderer
|
||||
assert "!importedBaseline" in renderer
|
||||
assert "experiment.dataset_version_id &&" in renderer
|
||||
assert "experiment.evaluator_source_hash &&" in renderer
|
||||
assert (
|
||||
"experiment.evaluator_source_hash === baseline.evaluator_source_hash"
|
||||
in renderer
|
||||
)
|
||||
|
||||
def test_results_tab_requires_full_metric_coverage_on_both_sides(self):
|
||||
"""answer_quality only compares when the judge scored every run in both
|
||||
the experiment and the baseline, not merely the same number of runs."""
|
||||
|
||||
_register_case("database/list-tables")
|
||||
app = runner.make_wsgi_app()
|
||||
|
||||
_status, _headers, body = _call_wsgi(app, "GET", "/")
|
||||
|
||||
page = body.decode("utf-8")
|
||||
assert (
|
||||
"experiment.score_counts[metric] === experiment.expected_run_count" in page
|
||||
)
|
||||
assert "baseline.score_counts[metric] === baseline.expected_run_count" in page
|
||||
assert (
|
||||
"experiment.score_counts[metric] === baseline.score_counts[metric]"
|
||||
not in page
|
||||
)
|
||||
|
||||
|
||||
class TestResultsPageScript:
|
||||
"""The substring assertions above pass against a page that cannot run."""
|
||||
|
||||
@pytest.fixture
|
||||
def script(self):
|
||||
_register_case("database/list-tables")
|
||||
app = runner.make_wsgi_app()
|
||||
_status, _headers, body = _call_wsgi(app, "GET", "/")
|
||||
return js_source.inline_script(body.decode("utf-8"))
|
||||
|
||||
def test_index_script_braces_are_balanced(self, script):
|
||||
assert js_source.brace_problems(script) == []
|
||||
|
||||
def test_index_script_declares_every_function_the_page_wires_up(self, script):
|
||||
declared = js_source.declared_functions(script)
|
||||
|
||||
assert len(declared) > 20
|
||||
assert "renderResults" in declared
|
||||
assert "usageCell" in declared
|
||||
|
||||
def test_results_renderer_declares_its_own_totals(self, script):
|
||||
renderer = js_source.function_body(script, "renderResults")
|
||||
|
||||
assert re.search(r"\b(?:var|let|const)\s+totals\b", renderer)
|
||||
|
||||
def test_overall_row_has_a_cell_for_each_descriptive_column(self, script):
|
||||
renderer = js_source.function_body(script, "renderResults")
|
||||
header = re.search(r"(\[\"Dataset\"[^\n]+\])\.concat\(METRICS\)", renderer)
|
||||
total = re.search(
|
||||
r'\[("Overall \(comparable cases\)"[^\n]+)\]\.forEach', renderer
|
||||
)
|
||||
assert header and total
|
||||
|
||||
leading_cells = js_source.call_arguments(f"columns({total[1]})", "columns")
|
||||
|
||||
assert len(leading_cells[0]) == len(json.loads(header[1]))
|
||||
|
||||
def test_overall_uses_each_experiments_recorded_population(self, script):
|
||||
renderer = js_source.function_body(script, "renderResults")
|
||||
|
||||
assert "dataset.case_count" not in renderer
|
||||
assert "experiment.case_count" in renderer
|
||||
assert "experiment.case_count === baseline.case_count" in renderer
|
||||
|
||||
def test_results_renderer_clears_the_pane_before_appending_anything(self, script):
|
||||
renderer = js_source.function_body(script, "renderResults")
|
||||
|
||||
clears = [m.start() for m in re.finditer(r"body\.textContent = \"\"", renderer)]
|
||||
appends = [m.start() for m in re.finditer(r"body\.appendChild\(", renderer)]
|
||||
assert len(clears) == 1
|
||||
assert clears[0] < min(appends)
|
||||
|
||||
def test_usage_cells_pass_the_formatter_in_its_own_position(self, script):
|
||||
calls = js_source.call_arguments(script, "usageCell")
|
||||
|
||||
assert len(calls) == 4
|
||||
for arguments in calls:
|
||||
assert len(arguments) in (4, 5), arguments
|
||||
formatter = arguments[3]
|
||||
assert formatter == "fmtDuration" or formatter.startswith("function")
|
||||
|
||||
|
||||
class TestDocsEndpoint:
|
||||
def test_docs_json_serves_the_help_docs(self):
|
||||
@@ -730,15 +1029,48 @@ class TestSubmitRunWorker:
|
||||
assert state.status == "done"
|
||||
|
||||
|
||||
class TestKnowledgeBaseStartup:
|
||||
def test_syncs_a_capable_empty_knowledge_base(self):
|
||||
handler = MagicMock()
|
||||
handler.can_have_knowledge_base.return_value = True
|
||||
handler.can_search.return_value = False
|
||||
|
||||
with patch.object(
|
||||
eval_runner_command, "KnowledgeBaseHandler", return_value=handler
|
||||
):
|
||||
eval_runner_command.sync_knowledge_base_if_needed()
|
||||
|
||||
handler.sync_knowledge_base.assert_called_once_with()
|
||||
|
||||
def test_does_not_sync_an_already_searchable_knowledge_base(self):
|
||||
handler = MagicMock()
|
||||
handler.can_have_knowledge_base.return_value = True
|
||||
handler.can_search.return_value = True
|
||||
|
||||
with patch.object(
|
||||
eval_runner_command, "KnowledgeBaseHandler", return_value=handler
|
||||
):
|
||||
eval_runner_command.sync_knowledge_base_if_needed()
|
||||
|
||||
handler.sync_knowledge_base.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestAssistantEvalRunnerCommand:
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_baseline_import(self):
|
||||
with patch(
|
||||
"baserow_enterprise.management.commands.assistant_eval_runner."
|
||||
"import_baseline"
|
||||
) as mock_import:
|
||||
with (
|
||||
patch(
|
||||
"baserow_enterprise.management.commands.assistant_eval_runner."
|
||||
"import_baseline"
|
||||
) as mock_import,
|
||||
patch(
|
||||
"baserow_enterprise.management.commands.assistant_eval_runner."
|
||||
"sync_knowledge_base_if_needed"
|
||||
) as mock_sync_knowledge_base,
|
||||
):
|
||||
self.mock_import_baseline = mock_import
|
||||
self.mock_sync_knowledge_base = mock_sync_knowledge_base
|
||||
yield
|
||||
|
||||
def test_startup_imports_the_baseline(self):
|
||||
@@ -825,6 +1157,7 @@ class TestAssistantEvalRunnerCommand:
|
||||
mock_load_all.assert_called_once()
|
||||
mock_sync.assert_called_once_with(mock_get_client.return_value)
|
||||
mock_sync_prompts.assert_called_once_with(mock_get_client.return_value)
|
||||
self.mock_sync_knowledge_base.assert_called_once_with()
|
||||
mock_start_worker.assert_called_once()
|
||||
mock_make_server.assert_called_once()
|
||||
assert mock_make_server.call_args[0][0] == "127.0.0.1"
|
||||
|
||||
+20
@@ -20,6 +20,26 @@ class TestMakeFixtures:
|
||||
assert user.pk is not None
|
||||
assert user.email
|
||||
|
||||
def test_new_scenarios_do_not_reuse_generated_usernames(self):
|
||||
first = make_fixtures()
|
||||
second = make_fixtures()
|
||||
first.fake.seed_instance(42)
|
||||
second.fake.seed_instance(42)
|
||||
|
||||
first_user = first.create_user()
|
||||
second_user = second.create_user()
|
||||
|
||||
assert first_user.username != second_user.username
|
||||
assert first_user.email != second_user.email
|
||||
|
||||
def test_preserves_explicit_user_identity(self):
|
||||
user = make_fixtures().create_user(
|
||||
username="explicit-user", email="explicit@example.com"
|
||||
)
|
||||
|
||||
assert user.username == "explicit-user"
|
||||
assert user.email == "explicit@example.com"
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestBuildDatabaseUiContext:
|
||||
|
||||
+39
-34
@@ -1,9 +1,9 @@
|
||||
import json
|
||||
import os
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from asgiref.sync import async_to_sync
|
||||
from pydantic_ai.models.groq import GroqModel
|
||||
from pydantic_ai.providers.groq import GroqProvider
|
||||
|
||||
@@ -20,9 +20,20 @@ from baserow_enterprise.assistant.tools.search_user_docs.tools import (
|
||||
|
||||
from .utils import make_test_ctx
|
||||
|
||||
# search_user_docs is async, so we need this to allow sync ORM calls from
|
||||
# data_fixture inside async tests.
|
||||
os.environ.setdefault("DJANGO_ALLOW_ASYNC_UNSAFE", "true")
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def enforce_async_db_safety(monkeypatch):
|
||||
# Other test modules enable this globally. Keep Django's guard active here
|
||||
# so ORM writes cannot escape pytest's rollback through an async connection.
|
||||
monkeypatch.delenv("DJANGO_ALLOW_ASYNC_UNSAFE", raising=False)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def docs_user_workspace(data_fixture):
|
||||
# Create records inside pytest's synchronous rollback transaction.
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
return user, workspace
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@@ -38,11 +49,10 @@ os.environ.setdefault("DJANGO_ALLOW_ASYNC_UNSAFE", "true")
|
||||
],
|
||||
)
|
||||
async def test_docs_synthesis_uses_supported_output_protocol(
|
||||
data_fixture, model_name, native, first_error
|
||||
docs_user_workspace, model_name, native, first_error
|
||||
):
|
||||
"""Exercise the real agent and Groq wire format, including typed validation."""
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
user, workspace = docs_user_workspace
|
||||
source = "https://example.com/tokens"
|
||||
answer = "Create a database token in Settings."
|
||||
requests = []
|
||||
@@ -156,9 +166,8 @@ class TestToolQueryGuard:
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_user_docs_rejects_tool_introspection(data_fixture):
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
async def test_search_user_docs_rejects_tool_introspection(docs_user_workspace):
|
||||
user, workspace = docs_user_workspace
|
||||
ctx = make_test_ctx(user, workspace)
|
||||
|
||||
result = await search_user_docs(
|
||||
@@ -172,9 +181,8 @@ async def test_search_user_docs_rejects_tool_introspection(data_fixture):
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_user_docs_handles_empty_results(data_fixture):
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
async def test_search_user_docs_handles_empty_results(docs_user_workspace):
|
||||
user, workspace = docs_user_workspace
|
||||
ctx = make_test_ctx(user, workspace)
|
||||
|
||||
with patch(
|
||||
@@ -201,11 +209,10 @@ async def test_search_user_docs_handles_empty_results(data_fixture):
|
||||
],
|
||||
)
|
||||
async def test_search_user_docs_does_not_add_sources_for_nothing_found_prediction(
|
||||
data_fixture,
|
||||
docs_user_workspace,
|
||||
answer,
|
||||
):
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
user, workspace = docs_user_workspace
|
||||
model_profile = MagicMock()
|
||||
ctx = make_test_ctx(user, workspace, model_profile=model_profile)
|
||||
chunk = MagicMock(content="Some unrelated documentation.")
|
||||
@@ -246,9 +253,8 @@ async def test_search_user_docs_does_not_add_sources_for_nothing_found_predictio
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_user_docs_handles_error(data_fixture):
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
async def test_search_user_docs_handles_error(docs_user_workspace):
|
||||
user, workspace = docs_user_workspace
|
||||
ctx = make_test_ctx(user, workspace)
|
||||
|
||||
with patch(
|
||||
@@ -268,10 +274,9 @@ async def test_search_user_docs_handles_error(data_fixture):
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sources", [[], ["https://example.com/invented"]])
|
||||
async def test_search_user_docs_does_not_invent_source_attribution(
|
||||
data_fixture, sources
|
||||
docs_user_workspace, sources
|
||||
):
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
user, workspace = docs_user_workspace
|
||||
profile = MagicMock()
|
||||
ctx = make_test_ctx(user, workspace, model_profile=profile)
|
||||
chunk = MagicMock(content="The rows guide describes editing rows.")
|
||||
@@ -318,9 +323,10 @@ async def test_search_user_docs_does_not_invent_source_attribution(
|
||||
"Nothing found in the documentation about cropping. You can choose the cover field.",
|
||||
],
|
||||
)
|
||||
async def test_search_user_docs_preserves_cited_partial_answer(data_fixture, answer):
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
async def test_search_user_docs_preserves_cited_partial_answer(
|
||||
docs_user_workspace, answer
|
||||
):
|
||||
user, workspace = docs_user_workspace
|
||||
profile = MagicMock(spec=ResolvedAssistantModelProfile)
|
||||
profile.get_settings.return_value = {"temperature": 0.3}
|
||||
profile.get_output_type.return_value = SearchDocsResult
|
||||
@@ -368,9 +374,10 @@ async def test_search_user_docs_preserves_cited_partial_answer(data_fixture, ans
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_user_docs_recovers_supported_partial_facts_once(data_fixture):
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
async def test_search_user_docs_recovers_supported_partial_facts_once(
|
||||
docs_user_workspace,
|
||||
):
|
||||
user, workspace = docs_user_workspace
|
||||
profile = MagicMock()
|
||||
profile.get_settings.return_value = {"temperature": 0.3}
|
||||
ctx = make_test_ctx(user, workspace, model_profile=profile)
|
||||
@@ -417,8 +424,7 @@ async def test_search_user_docs_recovers_supported_partial_facts_once(data_fixtu
|
||||
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
@pytest.mark.asyncio
|
||||
async def test_hybrid_context_retains_midrank_semantic_evidence(data_fixture):
|
||||
def test_hybrid_context_retains_midrank_semantic_evidence(data_fixture):
|
||||
import json
|
||||
|
||||
from baserow.core.pgvector import DEFAULT_EMBEDDING_DIMENSIONS
|
||||
@@ -467,7 +473,7 @@ async def test_hybrid_context_retains_midrank_semantic_evidence(data_fixture):
|
||||
reliability=1.0,
|
||||
)
|
||||
)
|
||||
result = await search_user_docs(
|
||||
result = async_to_sync(search_user_docs)(
|
||||
ctx, question="How do I use reference phrase?", thought="user asks"
|
||||
)
|
||||
passages = json.loads(
|
||||
@@ -482,11 +488,10 @@ async def test_hybrid_context_retains_midrank_semantic_evidence(data_fixture):
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_user_docs_searches_with_the_users_own_words(data_fixture):
|
||||
async def test_search_user_docs_searches_with_the_users_own_words(docs_user_workspace):
|
||||
"""A rewritten question can drop the concern that decides the relevant page."""
|
||||
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
user, workspace = docs_user_workspace
|
||||
ctx = make_test_ctx(user, workspace)
|
||||
ctx.prompt = "Where is the save button? I don't want to lose my work."
|
||||
chunk = MagicMock(content="Baserow saves every change automatically.")
|
||||
|
||||
+964
@@ -0,0 +1,964 @@
|
||||
"""
|
||||
Cross-tool chain tests for the builder and automation assistant tools.
|
||||
|
||||
Every test here drives the real tool functions in the order the agent drives
|
||||
them and feeds each tool's OUTPUT into the next tool's INPUT — no LLM, no
|
||||
network. Per-tool coverage cannot see a broken handoff: both regressions this
|
||||
suite exists for wrote their objects successfully and only failed one step
|
||||
later, when the next tool consumed the result.
|
||||
|
||||
- ``Element.order`` was renamed by a backend refactor while ``list_elements``
|
||||
still read it: elements were created fine, but every read-back raised
|
||||
``AttributeError``.
|
||||
- ``setup_page`` is the composite the model is told to prefer over the granular
|
||||
create tools. Nothing today pins the two paths together, so the composite can
|
||||
silently drift into building a different page.
|
||||
|
||||
A failure here means a contract changed — a backend model, a serializer field,
|
||||
or a tool's return shape — and the tools under
|
||||
``baserow_enterprise/assistant/tools/`` must be updated to match.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable
|
||||
|
||||
from django.contrib.auth.models import AbstractUser
|
||||
|
||||
import pytest
|
||||
|
||||
from baserow.contrib.automation.nodes.models import AutomationNode
|
||||
from baserow.contrib.automation.nodes.registries import automation_node_type_registry
|
||||
from baserow.contrib.builder.elements.models import Element
|
||||
from baserow.contrib.builder.workflow_actions.models import BuilderWorkflowAction
|
||||
from baserow.core.models import Workspace
|
||||
from baserow_enterprise.assistant.tools.automation.tools import (
|
||||
add_nodes,
|
||||
create_workflows,
|
||||
list_nodes,
|
||||
list_workflows,
|
||||
update_nodes,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.automation.types import (
|
||||
ActionNodeCreate,
|
||||
NodeUpdate,
|
||||
TriggerNodeCreate,
|
||||
WorkflowCreate,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.automation.types.node import (
|
||||
AutomationFieldValue,
|
||||
RowsTriggersSettings,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.builder.tools import (
|
||||
create_actions,
|
||||
create_collection_elements,
|
||||
create_data_sources,
|
||||
create_display_elements,
|
||||
create_layout_elements,
|
||||
create_pages,
|
||||
list_actions,
|
||||
list_data_sources,
|
||||
list_elements,
|
||||
setup_page,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.builder.types import (
|
||||
ActionCreate,
|
||||
CollectionElementCreate,
|
||||
DataSourceCreate,
|
||||
DisplayElementCreate,
|
||||
ElementItemCreate,
|
||||
FieldValueMapping,
|
||||
LayoutElementCreate,
|
||||
PageCreate,
|
||||
TableFieldConfig,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.core.tools import create_builders
|
||||
from baserow_enterprise.assistant.tools.core.types import BuilderItemCreate
|
||||
from baserow_enterprise.assistant.tools.database.tools import create_tables
|
||||
from baserow_enterprise.assistant.tools.database.types import (
|
||||
FieldItemCreate,
|
||||
SelectOptionCreate,
|
||||
TableItemCreate,
|
||||
)
|
||||
|
||||
from .utils import create_fake_tool_helpers, make_test_ctx
|
||||
|
||||
READ_BACK_HINT = (
|
||||
"CONTRACT BREAK — the objects were written fine, but the assistant can no "
|
||||
"longer read them back. A backend model, serializer or tool return shape "
|
||||
"changed under the read tool (this is exactly how the removal of "
|
||||
"Element.order broke list_elements). Fix the "
|
||||
"read path in baserow_enterprise/assistant/tools/; do not delete this test."
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_llm(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Fail loudly instead of reaching a live model: chains must stay literal."""
|
||||
|
||||
def forbid_generator(*args: Any, **kwargs: Any) -> Callable[..., dict[str, str]]:
|
||||
def generate(*inner_args: Any, **inner_kwargs: Any) -> dict[str, str]:
|
||||
raise AssertionError(
|
||||
"A tool in the chain asked the formula-generation agent for a "
|
||||
"formula. Chain tests must stay deterministic — pass literal "
|
||||
"values, never '$formula:' intents."
|
||||
)
|
||||
|
||||
return generate
|
||||
|
||||
monkeypatch.setattr(
|
||||
"baserow_enterprise.assistant.tools.builder.agents.get_formula_generator",
|
||||
forbid_generator,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"baserow_enterprise.assistant.tools.automation.agents.get_formula_generator",
|
||||
forbid_generator,
|
||||
)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# Chain helpers
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SeededTable:
|
||||
"""A workspace plus the one table every chain below is built on."""
|
||||
|
||||
user: AbstractUser
|
||||
workspace: Workspace
|
||||
ctx: Any
|
||||
table_id: int
|
||||
name_field_id: int
|
||||
status_field_id: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PageFingerprint:
|
||||
"""A page as the read tools describe it, with database ids normalised out."""
|
||||
|
||||
elements: tuple[tuple[Any, ...], ...]
|
||||
data_sources: tuple[tuple[Any, ...], ...]
|
||||
actions: tuple[tuple[Any, ...], ...]
|
||||
|
||||
|
||||
def _read_back(tool: Callable[..., dict[str, Any]], **kwargs: Any) -> dict[str, Any]:
|
||||
"""Call a read tool, turning any exception into a contract-break failure."""
|
||||
|
||||
try:
|
||||
return tool(**kwargs)
|
||||
except Exception as exc:
|
||||
pytest.fail(
|
||||
f"{tool.__name__}() raised {type(exc).__name__}: {exc}\n{READ_BACK_HINT}"
|
||||
)
|
||||
|
||||
|
||||
def _seed_table(data_fixture: Any) -> SeededTable:
|
||||
"""Create the workspace and, through create_tables, the Projects table."""
|
||||
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
database = data_fixture.create_database_application(
|
||||
user=user, workspace=workspace, name="Portfolio"
|
||||
)
|
||||
ctx = make_test_ctx(user, workspace, create_fake_tool_helpers())
|
||||
|
||||
result = create_tables(
|
||||
ctx,
|
||||
database_id=database.id,
|
||||
tables=[
|
||||
TableItemCreate(
|
||||
name="Projects",
|
||||
primary_field_name="Name",
|
||||
fields=[
|
||||
FieldItemCreate(name="Budget", type="number", decimal_places=2),
|
||||
FieldItemCreate(
|
||||
name="Status",
|
||||
type="single_select",
|
||||
options=[
|
||||
SelectOptionCreate(value="Active", color="green"),
|
||||
SelectOptionCreate(value="Done", color="blue"),
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
],
|
||||
add_sample_rows=False,
|
||||
thought="chain: the table the page and the workflow are built on",
|
||||
)
|
||||
|
||||
assert result["notes"] == [], (
|
||||
f"create_tables reported problems while seeding the chain: "
|
||||
f"{result['notes']}. Every later step consumes the field ids it "
|
||||
f"returns, so fix the table creation contract first."
|
||||
)
|
||||
table = result["created_tables"][0]
|
||||
fields_by_name = {f["name"]: f["id"] for f in table["fields"]}
|
||||
assert "Status" in fields_by_name, (
|
||||
f"create_tables no longer reports non-primary fields under 'fields' "
|
||||
f"(got keys {sorted(table)} / field names {sorted(fields_by_name)}). "
|
||||
f"Everything downstream — data sources, table columns, row actions, "
|
||||
f"automation field values — reads field ids from this payload."
|
||||
)
|
||||
|
||||
return SeededTable(
|
||||
user=user,
|
||||
workspace=workspace,
|
||||
ctx=ctx,
|
||||
table_id=table["id"],
|
||||
name_field_id=table["primary_field"]["id"],
|
||||
status_field_id=fields_by_name["Status"],
|
||||
)
|
||||
|
||||
|
||||
def _create_builder_app(ctx: Any, name: str) -> int:
|
||||
"""Create a builder application through the tool and return its id."""
|
||||
|
||||
created = create_builders(
|
||||
ctx,
|
||||
builders=[BuilderItemCreate(name=name, type="application")],
|
||||
thought="chain: the application the page lives in",
|
||||
)["created_builders"]
|
||||
|
||||
assert len(created) == 1 and "id" in created[0], (
|
||||
f"create_builders no longer returns [{{'id': ...}}] (got {created}). "
|
||||
f"create_pages, setup_page and list_pages all take that id as their "
|
||||
f"application_id."
|
||||
)
|
||||
return created[0]["id"]
|
||||
|
||||
|
||||
def _create_page(ctx: Any, application_id: int, name: str, path: str) -> int:
|
||||
"""Create a page through the tool and return its id."""
|
||||
|
||||
created = create_pages(
|
||||
ctx,
|
||||
application_id=application_id,
|
||||
pages=[PageCreate(name=name, path=path)],
|
||||
thought="chain: the page the data sources and elements attach to",
|
||||
)["created_pages"]
|
||||
|
||||
assert len(created) == 1 and "id" in created[0], (
|
||||
f"create_pages no longer returns [{{'id': ...}}] (got {created}). "
|
||||
f"Every builder tool after it is addressed by that page_id."
|
||||
)
|
||||
return created[0]["id"]
|
||||
|
||||
|
||||
def _fingerprint_page(ctx: Any, page_id: int) -> PageFingerprint:
|
||||
"""Describe a page through the read tools, with ids replaced by positions."""
|
||||
|
||||
elements = _read_back(
|
||||
list_elements, ctx=ctx, page_id=page_id, thought="chain: read the tree back"
|
||||
)["elements"]
|
||||
data_sources = _read_back(
|
||||
list_data_sources, ctx=ctx, page_id=page_id, thought="chain: read the tree back"
|
||||
)["data_sources"]
|
||||
actions = _read_back(
|
||||
list_actions, ctx=ctx, page_id=page_id, thought="chain: read the tree back"
|
||||
)["workflow_actions"]
|
||||
|
||||
at = {element["id"]: position for position, element in enumerate(elements)}
|
||||
return PageFingerprint(
|
||||
elements=tuple(
|
||||
(
|
||||
element["type"],
|
||||
element["label"],
|
||||
element["is_container"],
|
||||
element["place_in_container"],
|
||||
at.get(element["parent_element_id"]),
|
||||
)
|
||||
for element in elements
|
||||
),
|
||||
data_sources=tuple(
|
||||
(ds["name"], ds["type"], ds["table_id"]) for ds in data_sources
|
||||
),
|
||||
actions=tuple(
|
||||
(
|
||||
action["type"],
|
||||
action["event"],
|
||||
at.get(action["element_id"]),
|
||||
action["table_id"],
|
||||
tuple(
|
||||
sorted(
|
||||
(m["field_id"], m["value"])
|
||||
for m in action["field_mappings"] or []
|
||||
)
|
||||
),
|
||||
)
|
||||
for action in actions
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _reported_node_type(tool_vocabulary_type: str) -> str:
|
||||
"""Map a node type the tools accept onto the type list_nodes reports back."""
|
||||
|
||||
try:
|
||||
return automation_node_type_registry.get(tool_vocabulary_type).type
|
||||
except Exception as exc:
|
||||
pytest.fail(
|
||||
f"The automation tools accept type={tool_vocabulary_type!r} but the "
|
||||
f"node registry no longer resolves it ({type(exc).__name__}: {exc}). "
|
||||
f"The Literal vocabulary in assistant/tools/automation/types/node.py "
|
||||
f"survives only as a compat_type alias of the registered node type — "
|
||||
f"if the alias is dropped, every create_workflows/add_nodes call "
|
||||
f"fails. Update the tool types together with the registry."
|
||||
)
|
||||
|
||||
|
||||
def _element_ids_by_ref(result: dict[str, Any], tool_name: str) -> dict[str, int]:
|
||||
"""Read the ref → id mapping a create_*_elements call returned."""
|
||||
|
||||
created = result.get("created_elements")
|
||||
assert created and not result.get("errors"), (
|
||||
f"{tool_name} created nothing usable: {result}. The refs it returns are "
|
||||
f"how the next tool in the chain addresses these elements."
|
||||
)
|
||||
return {element["ref"]: element["id"] for element in created}
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# Chain 1: table -> application -> page -> data source -> elements -> actions
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
def test_chain_builds_a_page_against_a_real_table(data_fixture):
|
||||
"""Drive the whole builder chain, passing each tool's output to the next."""
|
||||
|
||||
seed = _seed_table(data_fixture)
|
||||
ctx = seed.ctx
|
||||
|
||||
application_id = _create_builder_app(ctx, "Project Portal")
|
||||
page_id = _create_page(ctx, application_id, "Projects", "/projects")
|
||||
|
||||
# Data source, bound to the table id create_tables returned.
|
||||
ds_result = create_data_sources(
|
||||
ctx,
|
||||
page_id=page_id,
|
||||
data_sources=[
|
||||
DataSourceCreate(
|
||||
ref="projects_ds",
|
||||
name="Projects",
|
||||
type="list_rows",
|
||||
table_id=seed.table_id,
|
||||
)
|
||||
],
|
||||
thought="chain: feed the page from the table just created",
|
||||
)
|
||||
ds_id = ds_result["ref_to_id_map"].get("projects_ds")
|
||||
assert isinstance(ds_id, int), (
|
||||
f"create_data_sources no longer maps refs to ids in 'ref_to_id_map' "
|
||||
f"(got {ds_result}). Collection elements and refresh actions bind to "
|
||||
f"data sources through that ref."
|
||||
)
|
||||
|
||||
# Collection element, bound to the data source by ref (not by id).
|
||||
table_result = create_collection_elements(
|
||||
ctx,
|
||||
page_id=page_id,
|
||||
elements=[
|
||||
CollectionElementCreate(
|
||||
ref="projects_table",
|
||||
type="table",
|
||||
data_source="projects_ds",
|
||||
fields=[
|
||||
TableFieldConfig(name="Name"),
|
||||
TableFieldConfig(name="Status"),
|
||||
],
|
||||
)
|
||||
],
|
||||
thought="chain: show the data source rows",
|
||||
)
|
||||
table_element_id = _element_ids_by_ref(table_result, "create_collection_elements")[
|
||||
"projects_table"
|
||||
]
|
||||
|
||||
layout_result = create_layout_elements(
|
||||
ctx,
|
||||
page_id=page_id,
|
||||
elements=[
|
||||
LayoutElementCreate(ref="cols", type="column", column_amount=2),
|
||||
],
|
||||
thought="chain: a container for the heading and the button",
|
||||
)
|
||||
column_element_id = _element_ids_by_ref(layout_result, "create_layout_elements")[
|
||||
"cols"
|
||||
]
|
||||
|
||||
# Children reference the container by the ref returned in the previous call.
|
||||
display_result = create_display_elements(
|
||||
ctx,
|
||||
page_id=page_id,
|
||||
elements=[
|
||||
DisplayElementCreate(
|
||||
ref="title",
|
||||
type="heading",
|
||||
value="Projects",
|
||||
level=1,
|
||||
parent_element="cols",
|
||||
place_in_container="0",
|
||||
),
|
||||
DisplayElementCreate(
|
||||
ref="new_btn",
|
||||
type="button",
|
||||
value="New project",
|
||||
parent_element="cols",
|
||||
place_in_container="1",
|
||||
),
|
||||
],
|
||||
thought="chain: title and call to action inside the container",
|
||||
)
|
||||
display_ids = _element_ids_by_ref(display_result, "create_display_elements")
|
||||
|
||||
# Action attached to the button by ref, writing to the seeded table.
|
||||
action_result = create_actions(
|
||||
ctx,
|
||||
page_id=page_id,
|
||||
actions=[
|
||||
ActionCreate(
|
||||
type="create_row",
|
||||
element="new_btn",
|
||||
event="click",
|
||||
table_id=seed.table_id,
|
||||
field_values=[
|
||||
FieldValueMapping(field_id=str(seed.name_field_id), value="'New'"),
|
||||
FieldValueMapping(
|
||||
field_id=str(seed.status_field_id), value="'Active'"
|
||||
),
|
||||
],
|
||||
)
|
||||
],
|
||||
thought="chain: the button writes a row into the seeded table",
|
||||
)
|
||||
assert not action_result.get("errors") and action_result["created_actions"], (
|
||||
f"create_actions could not attach an action to the 'new_btn' ref created "
|
||||
f"by the previous call: {action_result}. Element refs are tracked per "
|
||||
f"page in ToolHelpers.request_context — a change there breaks every "
|
||||
f"multi-call page build."
|
||||
)
|
||||
action_id = action_result["created_actions"][0]["id"]
|
||||
|
||||
# --- read the whole tree back -----------------------------------------
|
||||
|
||||
elements = _read_back(
|
||||
list_elements, ctx=ctx, page_id=page_id, thought="chain: verify the tree"
|
||||
)["elements"]
|
||||
by_id = {element["id"]: element for element in elements}
|
||||
expected_ids = {
|
||||
table_element_id,
|
||||
column_element_id,
|
||||
display_ids["title"],
|
||||
display_ids["new_btn"],
|
||||
}
|
||||
assert expected_ids <= set(by_id), (
|
||||
f"list_elements did not return the elements the create tools reported "
|
||||
f"creating (missing {sorted(expected_ids - set(by_id))}, got "
|
||||
f"{sorted(by_id)}). Either creation silently dropped elements or the "
|
||||
f"listing no longer covers this page."
|
||||
)
|
||||
assert by_id[table_element_id]["type"] == "table", (
|
||||
f"list_elements reports the collection element as "
|
||||
f"{by_id[table_element_id]['type']!r}, not 'table'."
|
||||
)
|
||||
assert by_id[column_element_id]["is_container"] is True, (
|
||||
"list_elements no longer flags the column element as a container; the "
|
||||
"model uses is_container to decide what it may nest elements into."
|
||||
)
|
||||
for ref in ("title", "new_btn"):
|
||||
assert by_id[display_ids[ref]]["parent_element_id"] == column_element_id, (
|
||||
f"element {ref!r} was created with parent_element='cols' but reads "
|
||||
f"back with parent_element_id="
|
||||
f"{by_id[display_ids[ref]]['parent_element_id']} instead of "
|
||||
f"{column_element_id}. The ref → parent handoff is broken."
|
||||
)
|
||||
assert by_id[display_ids["title"]]["label"] == "'Projects'", (
|
||||
f"list_elements returns label "
|
||||
f"{by_id[display_ids['title']]['label']!r} for the heading; the label "
|
||||
f"preview is read off the element's formula value and its storage "
|
||||
f"shape changed."
|
||||
)
|
||||
|
||||
read_data_sources = _read_back(
|
||||
list_data_sources, ctx=ctx, page_id=page_id, thought="chain: verify the data"
|
||||
)["data_sources"]
|
||||
assert [ds["id"] for ds in read_data_sources] == [ds_id], (
|
||||
f"list_data_sources returned {read_data_sources}, but "
|
||||
f"create_data_sources reported id {ds_id}."
|
||||
)
|
||||
assert read_data_sources[0]["table_id"] == seed.table_id, (
|
||||
f"the data source reads back bound to table "
|
||||
f"{read_data_sources[0]['table_id']}, not to the table create_tables "
|
||||
f"returned ({seed.table_id})."
|
||||
)
|
||||
|
||||
read_actions = _read_back(
|
||||
list_actions, ctx=ctx, page_id=page_id, thought="chain: verify the actions"
|
||||
)["workflow_actions"]
|
||||
assert [action["id"] for action in read_actions] == [action_id], (
|
||||
f"list_actions returned {read_actions}, but create_actions reported id "
|
||||
f"{action_id}."
|
||||
)
|
||||
assert read_actions[0]["element_id"] == display_ids["new_btn"], (
|
||||
f"the action reads back attached to element "
|
||||
f"{read_actions[0]['element_id']} instead of the button "
|
||||
f"{display_ids['new_btn']} it was created against."
|
||||
)
|
||||
assert read_actions[0]["table_id"] == seed.table_id, (
|
||||
f"the create_row action reads back targeting table "
|
||||
f"{read_actions[0]['table_id']} instead of {seed.table_id}."
|
||||
)
|
||||
mapped_field_ids = {m["field_id"] for m in read_actions[0]["field_mappings"] or []}
|
||||
assert mapped_field_ids == {seed.name_field_id, seed.status_field_id}, (
|
||||
f"the action maps fields {sorted(mapped_field_ids)}, not the field ids "
|
||||
f"create_tables returned "
|
||||
f"({sorted([seed.name_field_id, seed.status_field_id])}). The "
|
||||
f"database → builder field-id handoff is broken."
|
||||
)
|
||||
|
||||
# --- final database state ---------------------------------------------
|
||||
|
||||
table_element = Element.objects.get(id=table_element_id).specific
|
||||
assert table_element.data_source_id == ds_id, (
|
||||
f"the table element is stored against data source "
|
||||
f"{table_element.data_source_id}, not the {ds_id} that "
|
||||
f"create_data_sources returned for ref 'projects_ds'."
|
||||
)
|
||||
action_service = BuilderWorkflowAction.objects.get(id=action_id).specific.service
|
||||
assert action_service.specific.table_id == seed.table_id, (
|
||||
f"the stored workflow action service points at table "
|
||||
f"{action_service.specific.table_id}, not {seed.table_id}."
|
||||
)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# Chain 2: setup_page must agree with the granular tools
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
def _build_page_step_by_step(
|
||||
ctx: Any, application_id: int, table_id: int, field_id: int
|
||||
) -> int:
|
||||
"""Build a page with the granular create tools and return its id."""
|
||||
|
||||
page_id = _create_page(ctx, application_id, "Step by step", "/step-by-step")
|
||||
|
||||
create_data_sources(
|
||||
ctx,
|
||||
page_id=page_id,
|
||||
data_sources=[
|
||||
DataSourceCreate(
|
||||
ref="ds", name="Projects", type="list_rows", table_id=table_id
|
||||
)
|
||||
],
|
||||
thought="chain: granular build",
|
||||
)
|
||||
create_collection_elements(
|
||||
ctx,
|
||||
page_id=page_id,
|
||||
elements=[
|
||||
CollectionElementCreate(
|
||||
ref="grid",
|
||||
type="table",
|
||||
data_source="ds",
|
||||
fields=[TableFieldConfig(name="Name")],
|
||||
)
|
||||
],
|
||||
thought="chain: granular build",
|
||||
)
|
||||
create_layout_elements(
|
||||
ctx,
|
||||
page_id=page_id,
|
||||
elements=[LayoutElementCreate(ref="cols", type="column", column_amount=2)],
|
||||
thought="chain: granular build",
|
||||
)
|
||||
create_display_elements(
|
||||
ctx,
|
||||
page_id=page_id,
|
||||
elements=[
|
||||
DisplayElementCreate(
|
||||
ref="title",
|
||||
type="heading",
|
||||
value="Projects",
|
||||
level=1,
|
||||
parent_element="cols",
|
||||
place_in_container="0",
|
||||
),
|
||||
DisplayElementCreate(
|
||||
ref="btn",
|
||||
type="button",
|
||||
value="New project",
|
||||
parent_element="cols",
|
||||
place_in_container="1",
|
||||
),
|
||||
],
|
||||
thought="chain: granular build",
|
||||
)
|
||||
create_actions(
|
||||
ctx,
|
||||
page_id=page_id,
|
||||
actions=[
|
||||
ActionCreate(
|
||||
type="create_row",
|
||||
element="btn",
|
||||
event="click",
|
||||
table_id=table_id,
|
||||
field_values=[FieldValueMapping(field_id=str(field_id), value="'New'")],
|
||||
)
|
||||
],
|
||||
thought="chain: granular build",
|
||||
)
|
||||
return page_id
|
||||
|
||||
|
||||
def _build_page_with_setup_page(
|
||||
ctx: Any, application_id: int, table_id: int, field_id: int
|
||||
) -> int:
|
||||
"""Build the same page in a single setup_page call and return its id."""
|
||||
|
||||
page_id = _create_page(ctx, application_id, "One shot", "/one-shot")
|
||||
|
||||
result = setup_page(
|
||||
ctx,
|
||||
page_id=page_id,
|
||||
data_sources=[
|
||||
DataSourceCreate(
|
||||
ref="ds", name="Projects", type="list_rows", table_id=table_id
|
||||
)
|
||||
],
|
||||
elements=[
|
||||
ElementItemCreate(
|
||||
ref="grid",
|
||||
type="table",
|
||||
data_source="ds",
|
||||
fields=[TableFieldConfig(name="Name")],
|
||||
),
|
||||
ElementItemCreate(ref="cols", type="column", column_amount=2),
|
||||
ElementItemCreate(
|
||||
ref="title",
|
||||
type="heading",
|
||||
value="Projects",
|
||||
level=1,
|
||||
parent_element="cols",
|
||||
place_in_container="0",
|
||||
),
|
||||
ElementItemCreate(
|
||||
ref="btn",
|
||||
type="button",
|
||||
value="New project",
|
||||
parent_element="cols",
|
||||
place_in_container="1",
|
||||
),
|
||||
],
|
||||
actions=[
|
||||
ActionCreate(
|
||||
type="create_row",
|
||||
element="btn",
|
||||
event="click",
|
||||
table_id=table_id,
|
||||
field_values=[FieldValueMapping(field_id=str(field_id), value="'New'")],
|
||||
)
|
||||
],
|
||||
thought="chain: composite build",
|
||||
)
|
||||
|
||||
assert not result.get("errors"), (
|
||||
f"setup_page reported errors while building the same page the granular "
|
||||
f"tools build without complaint: {result['errors']}. The composite and "
|
||||
f"the granular tools share the same phase helpers — one of them changed."
|
||||
)
|
||||
return page_id
|
||||
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
def test_setup_page_matches_the_granular_tools(data_fixture):
|
||||
"""The composite tool and the step-by-step chain must build the same page."""
|
||||
|
||||
seed = _seed_table(data_fixture)
|
||||
ctx = seed.ctx
|
||||
application_id = _create_builder_app(ctx, "Comparison")
|
||||
|
||||
step_page_id = _build_page_step_by_step(
|
||||
ctx, application_id, seed.table_id, seed.name_field_id
|
||||
)
|
||||
one_shot_page_id = _build_page_with_setup_page(
|
||||
ctx, application_id, seed.table_id, seed.name_field_id
|
||||
)
|
||||
|
||||
step = _fingerprint_page(ctx, step_page_id)
|
||||
one_shot = _fingerprint_page(ctx, one_shot_page_id)
|
||||
|
||||
assert one_shot.data_sources == step.data_sources, (
|
||||
f"setup_page produced different data sources than create_data_sources:\n"
|
||||
f" setup_page: {one_shot.data_sources}\n"
|
||||
f" granular: {step.data_sources}\n"
|
||||
f"The two paths are documented as interchangeable and the model is told "
|
||||
f"to prefer setup_page, so this drift ships as a silent behaviour change."
|
||||
)
|
||||
assert one_shot.elements == step.elements, (
|
||||
f"setup_page produced a different element tree than the create_*_elements "
|
||||
f"tools:\n"
|
||||
f" setup_page: {one_shot.elements}\n"
|
||||
f" granular: {step.elements}\n"
|
||||
f"Tuples are (type, label, is_container, place_in_container, "
|
||||
f"parent position). The two paths are documented as interchangeable."
|
||||
)
|
||||
assert one_shot.actions == step.actions, (
|
||||
f"setup_page produced different workflow actions than create_actions:\n"
|
||||
f" setup_page: {one_shot.actions}\n"
|
||||
f" granular: {step.actions}\n"
|
||||
f"Tuples are (type, event, element position, table_id, field mappings)."
|
||||
)
|
||||
# Each page must own its data source: refs are tracked per page.
|
||||
step_grid, one_shot_grid = (
|
||||
Element.objects.filter(page_id=page_id, content_type__model="tableelement")
|
||||
.first()
|
||||
.specific
|
||||
for page_id in (step_page_id, one_shot_page_id)
|
||||
)
|
||||
assert step_grid.data_source_id != one_shot_grid.data_source_id, (
|
||||
"both pages' table elements point at the same data source; data source "
|
||||
"refs are tracked per page and must not leak across pages."
|
||||
)
|
||||
assert None not in (step_grid.data_source_id, one_shot_grid.data_source_id), (
|
||||
"a table element was stored without a data source: the ref → id "
|
||||
"resolution in the element creation path is broken."
|
||||
)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# Chain 3: automation -> workflow -> nodes
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
def test_chain_builds_an_automation_workflow(data_fixture):
|
||||
"""Drive automation creation, workflow, node insertion and node update."""
|
||||
|
||||
seed = _seed_table(data_fixture)
|
||||
ctx = seed.ctx
|
||||
|
||||
created_builders = create_builders(
|
||||
ctx,
|
||||
builders=[BuilderItemCreate(name="Project Ops", type="automation")],
|
||||
thought="chain: the automation the workflow lives in",
|
||||
)["created_builders"]
|
||||
assert len(created_builders) == 1 and "id" in created_builders[0], (
|
||||
f"create_builders no longer returns [{{'id': ...}}] for automations "
|
||||
f"(got {created_builders}); create_workflows takes that id."
|
||||
)
|
||||
automation_id = created_builders[0]["id"]
|
||||
|
||||
workflow_result = create_workflows(
|
||||
ctx,
|
||||
automation_id=automation_id,
|
||||
workflows=[
|
||||
WorkflowCreate(
|
||||
name="On new project",
|
||||
trigger=TriggerNodeCreate(
|
||||
ref="trigger",
|
||||
label="Project created",
|
||||
type="rows_created",
|
||||
rows_triggers_settings=RowsTriggersSettings(table_id=seed.table_id),
|
||||
),
|
||||
)
|
||||
],
|
||||
thought="chain: watch the table create_tables returned",
|
||||
)
|
||||
created_workflows = workflow_result["created_workflows"]
|
||||
assert len(created_workflows) == 1 and "id" in created_workflows[0], (
|
||||
f"create_workflows no longer returns [{{'id': ...}}] (got "
|
||||
f"{created_workflows}); add_nodes, update_nodes and list_nodes are all "
|
||||
f"addressed by that workflow id."
|
||||
)
|
||||
workflow_id = created_workflows[0]["id"]
|
||||
|
||||
trigger_nodes = _read_back(
|
||||
list_nodes,
|
||||
ctx=ctx,
|
||||
workflow_id=workflow_id,
|
||||
thought="chain: find the node to attach to",
|
||||
)["nodes"]
|
||||
assert len(trigger_nodes) == 1 and trigger_nodes[0]["type"] == _reported_node_type(
|
||||
"rows_created"
|
||||
), (
|
||||
f"list_nodes reports {trigger_nodes} for a workflow created with a "
|
||||
f"single rows_created trigger. Note the two vocabularies: the tools take "
|
||||
f"'rows_created' and read back the registered "
|
||||
f"{_reported_node_type('rows_created')!r}. add_nodes attaches to the node "
|
||||
f"id read from here, so a wrong or empty listing strands every later node."
|
||||
)
|
||||
trigger_id = trigger_nodes[0]["id"]
|
||||
|
||||
# Node one wires to an existing node id, node two to a temp ref.
|
||||
add_result = add_nodes(
|
||||
ctx,
|
||||
workflow_id=workflow_id,
|
||||
nodes=[
|
||||
ActionNodeCreate(
|
||||
ref="log_row",
|
||||
label="Log the project",
|
||||
type="create_row",
|
||||
previous_node_ref=str(trigger_id),
|
||||
table_id=seed.table_id,
|
||||
values=[
|
||||
AutomationFieldValue(field_id=seed.name_field_id, value="Logged")
|
||||
],
|
||||
),
|
||||
ActionNodeCreate(
|
||||
ref="notify",
|
||||
label="Notify the team",
|
||||
type="smtp_email",
|
||||
previous_node_ref="log_row",
|
||||
to_emails="team@baserow.io",
|
||||
subject="A project was created",
|
||||
body="Check the portal.",
|
||||
),
|
||||
],
|
||||
thought="chain: append the actions after the trigger",
|
||||
)
|
||||
created_nodes = add_result["created_nodes"]
|
||||
assert [node["type"] for node in created_nodes] == [
|
||||
_reported_node_type("create_row"),
|
||||
_reported_node_type("smtp_email"),
|
||||
], (
|
||||
f"add_nodes returned {created_nodes}. The first node references the "
|
||||
f"trigger id list_nodes reported and the second references the first "
|
||||
f"node's ref — a break in either wiring loses nodes silently."
|
||||
)
|
||||
log_node_id, notify_node_id = (node["id"] for node in created_nodes)
|
||||
|
||||
update_result = update_nodes(
|
||||
ctx,
|
||||
workflow_id=workflow_id,
|
||||
nodes=[
|
||||
NodeUpdate(
|
||||
node_id=notify_node_id,
|
||||
label="Email the team",
|
||||
subject="A new project was created",
|
||||
)
|
||||
],
|
||||
thought="chain: rename and retitle the node just created",
|
||||
)
|
||||
assert update_result["updated_nodes"] == [
|
||||
{"node_id": notify_node_id, "label": "Email the team"}
|
||||
], (
|
||||
f"update_nodes returned {update_result} for the node id add_nodes "
|
||||
f"reported ({notify_node_id}); the create → update handoff is broken."
|
||||
)
|
||||
|
||||
# --- read the workflow back -------------------------------------------
|
||||
|
||||
nodes = _read_back(
|
||||
list_nodes,
|
||||
ctx=ctx,
|
||||
workflow_id=workflow_id,
|
||||
thought="chain: verify the workflow",
|
||||
)["nodes"]
|
||||
assert [node["id"] for node in nodes] == [
|
||||
trigger_id,
|
||||
log_node_id,
|
||||
notify_node_id,
|
||||
], (
|
||||
f"list_nodes returned {[n['id'] for n in nodes]}; the chain built "
|
||||
f"trigger {trigger_id} → create_row {log_node_id} → smtp_email "
|
||||
f"{notify_node_id}. list_nodes walks the workflow graph, so a change to "
|
||||
f"the graph's edge storage reorders or truncates it."
|
||||
)
|
||||
assert nodes[2]["label"] == "Email the team", (
|
||||
f"the node reads back labelled {nodes[2]['label']!r} after update_nodes "
|
||||
f"set 'Email the team'."
|
||||
)
|
||||
|
||||
workflows = _read_back(
|
||||
list_workflows,
|
||||
ctx=ctx,
|
||||
automation_id=automation_id,
|
||||
thought="chain: verify the workflow list",
|
||||
)["workflows"]
|
||||
assert workflows == [
|
||||
{"id": workflow_id, "name": "On new project", "state": "draft"}
|
||||
], (
|
||||
f"list_workflows returned {workflows} for the automation "
|
||||
f"create_builders returned; create_workflows reported id {workflow_id}."
|
||||
)
|
||||
|
||||
# --- final database state ---------------------------------------------
|
||||
|
||||
log_service = AutomationNode.objects.get(id=log_node_id).service.specific
|
||||
assert log_service.table_id == seed.table_id, (
|
||||
f"the create_row node is stored against table {log_service.table_id}, "
|
||||
f"not the table id create_tables returned ({seed.table_id})."
|
||||
)
|
||||
notify_service = AutomationNode.objects.get(id=notify_node_id).service.specific
|
||||
assert "A new project was created" in str(notify_service.subject), (
|
||||
f"update_nodes did not persist the new subject (stored: "
|
||||
f"{notify_service.subject!r})."
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
def test_add_nodes_persists_literal_field_values_like_create_workflows(data_fixture):
|
||||
"""Both node-creation paths must store the literal values they were given."""
|
||||
|
||||
seed = _seed_table(data_fixture)
|
||||
ctx = seed.ctx
|
||||
automation_id = create_builders(
|
||||
ctx,
|
||||
builders=[BuilderItemCreate(name="Parity", type="automation")],
|
||||
thought="chain: compare the two node creation paths",
|
||||
)["created_builders"][0]["id"]
|
||||
|
||||
def create_row_node(
|
||||
ref: str, previous_node_ref: str, value: str
|
||||
) -> ActionNodeCreate:
|
||||
return ActionNodeCreate(
|
||||
ref=ref,
|
||||
label=ref,
|
||||
type="create_row",
|
||||
previous_node_ref=previous_node_ref,
|
||||
table_id=seed.table_id,
|
||||
values=[AutomationFieldValue(field_id=seed.name_field_id, value=value)],
|
||||
)
|
||||
|
||||
workflow_id = create_workflows(
|
||||
ctx,
|
||||
automation_id=automation_id,
|
||||
workflows=[
|
||||
WorkflowCreate(
|
||||
name="Parity",
|
||||
trigger=TriggerNodeCreate(
|
||||
ref="trigger",
|
||||
label="Project created",
|
||||
type="rows_created",
|
||||
rows_triggers_settings=RowsTriggersSettings(table_id=seed.table_id),
|
||||
),
|
||||
nodes=[create_row_node("inline", "trigger", "from create_workflows")],
|
||||
)
|
||||
],
|
||||
thought="chain: node created together with the workflow",
|
||||
)["created_workflows"][0]["id"]
|
||||
|
||||
inline_node_id = _read_back(
|
||||
list_nodes, ctx=ctx, workflow_id=workflow_id, thought="chain: find the node"
|
||||
)["nodes"][1]["id"]
|
||||
appended_node_id = add_nodes(
|
||||
ctx,
|
||||
workflow_id=workflow_id,
|
||||
nodes=[create_row_node("appended", str(inline_node_id), "from add_nodes")],
|
||||
thought="chain: same node appended to the same workflow",
|
||||
)["created_nodes"][0]["id"]
|
||||
|
||||
def mapped_field_ids(node_id: int) -> set[int]:
|
||||
service = AutomationNode.objects.get(id=node_id).service.specific
|
||||
return {mapping.field_id for mapping in service.field_mappings.all()}
|
||||
|
||||
assert mapped_field_ids(inline_node_id) == {seed.name_field_id}, (
|
||||
f"create_workflows did not store the literal field value it was given "
|
||||
f"for field {seed.name_field_id}."
|
||||
)
|
||||
assert mapped_field_ids(appended_node_id) == {seed.name_field_id}, (
|
||||
f"add_nodes stored no field mapping for field {seed.name_field_id}, "
|
||||
f"while create_workflows stored one for the identical node. The node the "
|
||||
f"assistant appends to an existing workflow will create empty rows."
|
||||
)
|
||||
+403
@@ -0,0 +1,403 @@
|
||||
"""
|
||||
Deterministic tool-CHAIN suite for the Kuma assistant's database tools.
|
||||
|
||||
The sibling suites call one tool at a time. These tests drive the tools in the
|
||||
order a real turn does — the id a tool RETURNS is the id the next tool is CALLED
|
||||
with — so they fail when a tool starts returning a shape the next tool can no
|
||||
longer consume. That is the regression class that hurts users: a refactor
|
||||
removed ``Element.order`` and ``list_elements`` failed on every call, and
|
||||
reloading row tools for an
|
||||
already-loaded table used to raise a tool-name conflict.
|
||||
|
||||
No LLM and no network: ``add_sample_rows`` is always False, and tools needing a
|
||||
live model (``generate_formula``, ``search_user_docs``) are out of scope.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from pydantic_ai import Tool
|
||||
|
||||
from baserow.contrib.database.fields.models import Field as BaserowField
|
||||
from baserow.contrib.database.table.models import Table
|
||||
from baserow.contrib.database.views.models import View, ViewFilter
|
||||
from baserow_enterprise.assistant.agents import dynamic_toolset
|
||||
from baserow_enterprise.assistant.tools.core.tools import create_builders
|
||||
from baserow_enterprise.assistant.tools.core.types import BuilderItemCreate
|
||||
from baserow_enterprise.assistant.tools.database.tools import (
|
||||
create_fields,
|
||||
create_tables,
|
||||
create_view_filters,
|
||||
create_views,
|
||||
get_tables_schema,
|
||||
list_tables,
|
||||
list_views,
|
||||
load_row_tools,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.database.types import (
|
||||
FieldItemCreate,
|
||||
ListTablesFilterArg,
|
||||
SelectOptionCreate,
|
||||
TableItemCreate,
|
||||
ViewFilterItemCreate,
|
||||
ViewFiltersArgs,
|
||||
ViewItemCreate,
|
||||
)
|
||||
|
||||
from .utils import make_test_ctx
|
||||
|
||||
# ===========================================================================
|
||||
# Chain helpers — a failure below means a tool contract changed
|
||||
# ===========================================================================
|
||||
|
||||
CONTRACT_CHANGED = (
|
||||
"A tool contract, model or data type changed: the tools on both sides of "
|
||||
"this handoff must be updated together."
|
||||
)
|
||||
|
||||
|
||||
def schema_field(table_schema: dict[str, Any], name: str) -> dict[str, Any]:
|
||||
"""Find a field by name in a table schema, primary field included."""
|
||||
|
||||
fields = [table_schema["primary_field"], *table_schema["fields"]]
|
||||
match = next((f for f in fields if f["name"] == name), None)
|
||||
assert match is not None, (
|
||||
f"field {name!r} is missing from the returned schema "
|
||||
f"(has: {[f['name'] for f in fields]}). {CONTRACT_CHANGED}"
|
||||
)
|
||||
return match
|
||||
|
||||
|
||||
def schema_field_names(table_schema: dict[str, Any]) -> set[str]:
|
||||
"""Every field name in a table schema, primary field included."""
|
||||
|
||||
return {
|
||||
field["name"]
|
||||
for field in [table_schema["primary_field"], *table_schema["fields"]]
|
||||
}
|
||||
|
||||
|
||||
def row_tool_field_names(tool: Tool) -> set[str]:
|
||||
"""Field names a dynamic row tool accepts, read from its own JSON schema."""
|
||||
|
||||
schema = tool.function_schema.json_schema
|
||||
return set(schema["properties"]["rows"]["items"]["properties"])
|
||||
|
||||
|
||||
def call_row_tool(tool: Tool, **kwargs: Any) -> Any:
|
||||
"""Validate arguments against the generated schema, then run the tool."""
|
||||
|
||||
validated = tool.function_schema.validator.validate_python(kwargs)
|
||||
return tool.function(**validated)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# CHAIN 1 — build a database from nothing (the onboarding path)
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
def onboarding_tables() -> list[TableItemCreate]:
|
||||
"""Two related tables, as the agent sends them in one create_tables call."""
|
||||
|
||||
return [
|
||||
TableItemCreate(
|
||||
name="Customers",
|
||||
primary_field_name="Name",
|
||||
fields=[FieldItemCreate(name="City", type="text")],
|
||||
),
|
||||
TableItemCreate(
|
||||
name="Orders",
|
||||
primary_field_name="Order",
|
||||
fields=[
|
||||
FieldItemCreate(name="Amount", type="number", decimal_places=2),
|
||||
FieldItemCreate(name="Due", type="date"),
|
||||
FieldItemCreate(
|
||||
name="Status",
|
||||
type="single_select",
|
||||
options=[
|
||||
SelectOptionCreate(value="Open", color="green"),
|
||||
SelectOptionCreate(value="Closed", color="red"),
|
||||
],
|
||||
),
|
||||
FieldItemCreate(
|
||||
name="Customer", type="link_row", linked_table="Customers"
|
||||
),
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_chain_build_a_database_from_nothing(data_fixture):
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
ctx = make_test_ctx(user, workspace)
|
||||
|
||||
# --- create_builders -> database id -----------------------------------
|
||||
builders = create_builders(
|
||||
ctx,
|
||||
builders=[BuilderItemCreate(name="Sales", type="database")],
|
||||
thought="chain",
|
||||
)["created_builders"]
|
||||
assert len(builders) == 1
|
||||
database_id = builders[0]["id"]
|
||||
|
||||
# --- database id -> create_tables -------------------------------------
|
||||
result = create_tables(
|
||||
ctx,
|
||||
database_id=database_id,
|
||||
tables=onboarding_tables(),
|
||||
add_sample_rows=False,
|
||||
thought="chain",
|
||||
)
|
||||
assert result["notes"] == [], (
|
||||
f"create_tables reported errors while building the chain's tables: "
|
||||
f"{result['notes']}"
|
||||
)
|
||||
created = result["created_tables"]
|
||||
assert len(created) == 2
|
||||
customers_id = created[0]["id"]
|
||||
orders_id = created[1]["id"]
|
||||
|
||||
# --- table ids -> get_tables_schema -> field ids ----------------------
|
||||
schemas = get_tables_schema(
|
||||
ctx,
|
||||
table_ids=[customers_id, orders_id],
|
||||
full_schema=True,
|
||||
thought="chain",
|
||||
)["tables_schema"]
|
||||
assert [s["id"] for s in schemas] == [customers_id, orders_id]
|
||||
orders_schema = schemas[1]
|
||||
|
||||
# Disagreement here means the agent silently works from stale field ids.
|
||||
assert schema_field_names(orders_schema) == schema_field_names(created[1]), (
|
||||
"create_tables and get_tables_schema disagree about the fields of the "
|
||||
f"same table: {sorted(schema_field_names(created[1]))} vs "
|
||||
f"{sorted(schema_field_names(orders_schema))}. {CONTRACT_CHANGED}"
|
||||
)
|
||||
|
||||
link = schema_field(orders_schema, "Customer")
|
||||
assert link["linked_table"] == customers_id
|
||||
|
||||
status = schema_field(orders_schema, "Status")
|
||||
status_id = status["id"]
|
||||
amount_id = schema_field(orders_schema, "Amount")["id"]
|
||||
options = status["options"]
|
||||
open_option = next((o for o in options if o["value"] == "Open"), None)
|
||||
assert open_option is not None, (
|
||||
f"the single_select schema no longer carries its options (got "
|
||||
f"{options!r}), so a filter cannot be built from it. {CONTRACT_CHANGED}"
|
||||
)
|
||||
|
||||
# --- table id -> create_fields -> new field ids -----------------------
|
||||
result = create_fields(
|
||||
ctx,
|
||||
table_id=orders_id,
|
||||
fields=[
|
||||
FieldItemCreate(name="Cover", type="file"),
|
||||
FieldItemCreate(name="Priority", type="rating", max_value=5),
|
||||
],
|
||||
thought="chain",
|
||||
)
|
||||
assert "field_errors" not in result and "formula_errors" not in result, (
|
||||
f"create_fields could not add fields to the table create_tables built: {result}"
|
||||
)
|
||||
cover_id = next(f for f in result["created_fields"] if f["name"] == "Cover")["id"]
|
||||
|
||||
# --- field ids -> create_views ----------------------------------------
|
||||
views = create_views(
|
||||
ctx,
|
||||
table_id=orders_id,
|
||||
views=[
|
||||
ViewItemCreate(name="All orders", public=False, type="grid"),
|
||||
ViewItemCreate(
|
||||
name="Board", public=False, type="kanban", column_field_id=status_id
|
||||
),
|
||||
ViewItemCreate(
|
||||
name="Covers", public=False, type="gallery", cover_field_id=cover_id
|
||||
),
|
||||
],
|
||||
thought="chain",
|
||||
)["created_views"]
|
||||
assert [v["name"] for v in views] == ["All orders", "Board", "Covers"]
|
||||
grid_view_id = views[0]["id"]
|
||||
|
||||
# --- view id + field ids -> create_view_filters -----------------------
|
||||
per_view = create_view_filters(
|
||||
ctx,
|
||||
view_filters=[
|
||||
ViewFiltersArgs(
|
||||
view_id=grid_view_id,
|
||||
filters=[
|
||||
ViewFilterItemCreate(
|
||||
field_id=status_id,
|
||||
type="single_select",
|
||||
operator="is_any_of",
|
||||
value=["Open"],
|
||||
),
|
||||
ViewFilterItemCreate(
|
||||
field_id=amount_id,
|
||||
type="number",
|
||||
operator="higher_than",
|
||||
value=100,
|
||||
),
|
||||
],
|
||||
)
|
||||
],
|
||||
thought="chain",
|
||||
)["created_view_filters"]
|
||||
assert len(per_view) == 1 and per_view[0]["view_id"] == grid_view_id
|
||||
# create_view_filters logs and skips filters it cannot build, hence the count.
|
||||
assert len(per_view[0]["filters"]) == 2, (
|
||||
f"only {len(per_view[0]['filters'])} of 2 filters were created; the rest "
|
||||
f"were skipped because the field ids or types no longer match what the "
|
||||
f"schema reports. {CONTRACT_CHANGED}"
|
||||
)
|
||||
|
||||
# --- list_views / list_tables confirm what the chain built -------------
|
||||
listed = list_views(ctx, table_id=orders_id, thought="chain")["views"]
|
||||
by_name = {v["name"]: v for v in listed}
|
||||
assert {"All orders", "Board", "Covers"} <= set(by_name)
|
||||
assert by_name["Board"]["column_field_id"] == status_id
|
||||
# The gallery cover round-trip has its own regression test below.
|
||||
assert views[2]["cover_field_id"] == cover_id
|
||||
|
||||
listed_tables = list_tables(
|
||||
ctx,
|
||||
filters=ListTablesFilterArg(
|
||||
database_id_or_name=database_id, table_ids_or_names=None
|
||||
),
|
||||
thought="chain",
|
||||
)["tables"]
|
||||
assert {t["id"] for t in listed_tables} == {customers_id, orders_id}
|
||||
|
||||
# --- final ORM state ---------------------------------------------------
|
||||
orders = Table.objects.get(id=orders_id)
|
||||
assert orders.database_id == database_id
|
||||
assert orders.database.workspace_id == workspace.id
|
||||
assert set(
|
||||
BaserowField.objects.filter(table=orders).values_list("name", flat=True)
|
||||
) == {"Order", "Amount", "Due", "Status", "Customer", "Cover", "Priority"}
|
||||
# The default grid view every new table gets, plus the three created here.
|
||||
assert View.objects.filter(table=orders).count() == 4
|
||||
assert ViewFilter.objects.filter(view_id=grid_view_id).count() == 2
|
||||
select_filter = ViewFilter.objects.get(view_id=grid_view_id, field_id=status_id)
|
||||
assert select_filter.value == str(open_option["id"]), (
|
||||
f"the 'Open' option id get_tables_schema reported ({open_option['id']}) "
|
||||
f"is not what the stored filter resolves to ({select_filter.value!r}). "
|
||||
f"{CONTRACT_CHANGED}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_chain_gallery_cover_field_survives_create_views(data_fixture):
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
database = data_fixture.create_database_application(workspace=workspace)
|
||||
ctx = make_test_ctx(user, workspace)
|
||||
|
||||
result = create_tables(
|
||||
ctx,
|
||||
database_id=database.id,
|
||||
tables=[
|
||||
TableItemCreate(
|
||||
name="Products",
|
||||
primary_field_name="Product",
|
||||
fields=[FieldItemCreate(name="Photo", type="file")],
|
||||
)
|
||||
],
|
||||
add_sample_rows=False,
|
||||
thought="chain",
|
||||
)
|
||||
table_id = result["created_tables"][0]["id"]
|
||||
|
||||
schemas = get_tables_schema(
|
||||
ctx, table_ids=[table_id], full_schema=True, thought="chain"
|
||||
)["tables_schema"]
|
||||
photo_id = schema_field(schemas[0], "Photo")["id"]
|
||||
|
||||
views = create_views(
|
||||
ctx,
|
||||
table_id=table_id,
|
||||
views=[
|
||||
ViewItemCreate(
|
||||
name="Catalogue",
|
||||
public=False,
|
||||
type="gallery",
|
||||
cover_field_id=photo_id,
|
||||
)
|
||||
],
|
||||
thought="chain",
|
||||
)["created_views"]
|
||||
view_id = views[0]["id"]
|
||||
|
||||
listed = list_views(ctx, table_id=table_id, thought="chain")["views"]
|
||||
gallery = next(v for v in listed if v["id"] == view_id)
|
||||
assert gallery["cover_field_id"] == photo_id, (
|
||||
f"create_views was given cover_field_id={photo_id} and echoed it back, "
|
||||
f"but list_views reads {gallery['cover_field_id']!r}: the cover field "
|
||||
"was never persisted, so the user gets a gallery with no cover image."
|
||||
)
|
||||
assert View.objects.get(id=view_id).specific.card_cover_image_field_id == photo_id
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# CHAIN 2 — reloading row tools for a table the agent already loaded
|
||||
# ===========================================================================
|
||||
|
||||
ROW_OPERATIONS = ["create", "update", "delete"]
|
||||
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
def test_chain_reloading_row_tools_for_the_same_table_is_harmless(data_fixture):
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
database = data_fixture.create_database_application(workspace=workspace)
|
||||
ctx = make_test_ctx(user, workspace)
|
||||
|
||||
result = create_tables(
|
||||
ctx,
|
||||
database_id=database.id,
|
||||
tables=[
|
||||
TableItemCreate(
|
||||
name="Tasks",
|
||||
primary_field_name="Task",
|
||||
fields=[FieldItemCreate(name="Notes", type="long_text")],
|
||||
)
|
||||
],
|
||||
add_sample_rows=False,
|
||||
thought="chain",
|
||||
)
|
||||
created = result["created_tables"][0]
|
||||
table_id = created["id"]
|
||||
|
||||
load_row_tools(
|
||||
ctx, table_ids=[table_id], operations=ROW_OPERATIONS, thought="chain"
|
||||
)
|
||||
load_row_tools(
|
||||
ctx, table_ids=[table_id], operations=ROW_OPERATIONS, thought="chain"
|
||||
)
|
||||
|
||||
toolset = dynamic_toolset(ctx)
|
||||
expected_names = {f"{op}_rows_in_table_{table_id}" for op in ROW_OPERATIONS}
|
||||
assert set(toolset.tools) == expected_names, (
|
||||
f"Reloading row tools for table {table_id} left the agent with "
|
||||
f"{sorted(toolset.tools)}; one tool per name is the only usable state."
|
||||
)
|
||||
|
||||
create_tool = toolset.tools[f"create_rows_in_table_{table_id}"]
|
||||
# The row tools embed their schema; that is why the agent skips a schema lookup.
|
||||
assert row_tool_field_names(create_tool) == schema_field_names(created), (
|
||||
f"the generated row tool accepts "
|
||||
f"{sorted(row_tool_field_names(create_tool))} but the schema "
|
||||
f"create_tables returned says {sorted(schema_field_names(created))}. "
|
||||
f"{CONTRACT_CHANGED}"
|
||||
)
|
||||
|
||||
result = call_row_tool(
|
||||
create_tool,
|
||||
rows=[{"Task": "Write the chain test", "Notes": "done"}],
|
||||
thought="chain",
|
||||
)
|
||||
assert len(result["created_row_ids"]) == 1
|
||||
assert Table.objects.get(id=table_id).get_model().objects.count() == 1
|
||||
+592
@@ -0,0 +1,592 @@
|
||||
"""
|
||||
Deterministic tool-contract suite for the Kuma assistant.
|
||||
|
||||
No LLM, no network: every read/list tool is invoked against one richly seeded
|
||||
workspace and its output is checked for shape. This is the guard against
|
||||
backend refactors that silently break an assistant tool — e.g. b70bc968d
|
||||
renamed ``Element.order`` to ``Element.compat_order`` while
|
||||
``ElementItem.from_orm`` kept reading ``element.order``, so ``list_elements``
|
||||
raised ``AttributeError``.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable
|
||||
|
||||
from django.contrib.auth.models import AbstractUser
|
||||
|
||||
import pytest
|
||||
|
||||
from baserow.contrib.automation.models import Automation
|
||||
from baserow.contrib.automation.workflows.models import AutomationWorkflow
|
||||
from baserow.contrib.builder.elements.models import Element
|
||||
from baserow.contrib.builder.models import Builder
|
||||
from baserow.contrib.builder.pages.models import Page
|
||||
from baserow.contrib.database.models import Database
|
||||
from baserow.contrib.database.table.models import Table
|
||||
from baserow.core.graph.types import GraphPointPosition
|
||||
from baserow.core.models import Workspace
|
||||
from baserow_enterprise.assistant.tools.automation.tools import (
|
||||
list_nodes,
|
||||
list_workflows,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.builder.tools import (
|
||||
list_actions,
|
||||
list_data_sources,
|
||||
list_elements,
|
||||
list_pages,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.core.tools import list_builders
|
||||
from baserow_enterprise.assistant.tools.database.tools import (
|
||||
get_tables_schema,
|
||||
list_rows,
|
||||
list_tables,
|
||||
list_views,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.database.types import ListTablesFilterArg
|
||||
from baserow_enterprise.assistant.tools.registries import assistant_tool_registry
|
||||
|
||||
from .utils import make_test_ctx
|
||||
|
||||
# ===========================================================================
|
||||
# Seeded workspace
|
||||
# ===========================================================================
|
||||
|
||||
SEEDED_ELEMENT_TYPES = frozenset(
|
||||
{
|
||||
"heading",
|
||||
"text",
|
||||
"button",
|
||||
"link",
|
||||
"image",
|
||||
"column",
|
||||
"form_container",
|
||||
"input_text",
|
||||
"choice",
|
||||
"checkbox",
|
||||
"table",
|
||||
"menu",
|
||||
}
|
||||
)
|
||||
|
||||
SEEDED_VIEW_TYPES = frozenset(
|
||||
{"grid", "gallery", "form", "kanban", "calendar", "timeline"}
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SeededWorkspace:
|
||||
"""One workspace holding every entity the read tools have to serialize."""
|
||||
|
||||
user: AbstractUser
|
||||
workspace: Workspace
|
||||
database: Database
|
||||
table: Table
|
||||
linked_table: Table
|
||||
builder: Builder
|
||||
page: Page
|
||||
button: Element
|
||||
automation: Automation
|
||||
workflow: AutomationWorkflow
|
||||
|
||||
|
||||
def _seed_database(fx: Any, user: AbstractUser, workspace: Workspace) -> dict[str, Any]:
|
||||
database = fx.create_database_application(
|
||||
user=user, workspace=workspace, name="Contracts DB"
|
||||
)
|
||||
table, fields, _ = fx.build_table(
|
||||
user=user,
|
||||
database=database,
|
||||
name="Orders",
|
||||
columns=[
|
||||
("Name", {"type": "text", "primary": True}),
|
||||
("Notes", "long_text"),
|
||||
("Amount", "number"),
|
||||
("Due", "date"),
|
||||
("Finished", "date"),
|
||||
("Done", "boolean"),
|
||||
],
|
||||
rows=[
|
||||
["First order", "A note", 10, "2026-01-01", "2026-01-05", True],
|
||||
["Second order", "Another note", 20, "2026-02-01", "2026-02-05", False],
|
||||
],
|
||||
)
|
||||
linked_table, _, _ = fx.build_table(
|
||||
user=user,
|
||||
database=database,
|
||||
name="Customers",
|
||||
columns=[("Name", {"type": "text", "primary": True}), ("City", "text")],
|
||||
rows=[["Acme", "Berlin"], ["Globex", "Paris"]],
|
||||
)
|
||||
fx.create_link_row_field(name="Customer", table=table, link_row_table=linked_table)
|
||||
|
||||
status_field = fx.create_single_select_field(table=table, name="Status")
|
||||
fx.create_select_option(field=status_field, value="Open", color="blue")
|
||||
cover_field = fx.create_file_field(table=table, name="Cover")
|
||||
due_field, finished_field = fields[3], fields[4]
|
||||
|
||||
fx.create_grid_view(table=table, name="Grid", order=1)
|
||||
fx.create_gallery_view(
|
||||
table=table, name="Gallery", order=2, card_cover_image_field=cover_field
|
||||
)
|
||||
form_view = fx.create_form_view(table=table, name="Form", order=3)
|
||||
fx.create_form_view_field_options(form_view, enabled=True)
|
||||
fx.create_kanban_view(
|
||||
table=table, name="Kanban", order=4, single_select_field=status_field
|
||||
)
|
||||
fx.create_calendar_view(table=table, name="Calendar", order=5, date_field=due_field)
|
||||
fx.create_timeline_view(
|
||||
table=table,
|
||||
name="Timeline",
|
||||
order=6,
|
||||
start_date_field=due_field,
|
||||
end_date_field=finished_field,
|
||||
)
|
||||
|
||||
return {
|
||||
"database": database,
|
||||
"table": table,
|
||||
"linked_table": linked_table,
|
||||
"name_field": fields[0],
|
||||
}
|
||||
|
||||
|
||||
def _seed_builder(
|
||||
fx: Any, user: AbstractUser, workspace: Workspace, table: Table, name_field: Any
|
||||
) -> dict[str, Any]:
|
||||
builder = fx.create_builder_application(
|
||||
user=user, workspace=workspace, name="Customer Portal"
|
||||
)
|
||||
page = fx.create_builder_page(builder=builder, name="Home", path="/home")
|
||||
integration = fx.create_local_baserow_integration(application=builder, user=user)
|
||||
data_source = fx.create_builder_local_baserow_list_rows_data_source(
|
||||
page=page, name="Orders", table=table, integration=integration
|
||||
)
|
||||
|
||||
fx.create_builder_heading_element(user=user, page=page, value="'Welcome'", level=1)
|
||||
fx.create_builder_text_element(user=user, page=page, value="'Some body copy'")
|
||||
fx.create_builder_image_element(user=user, page=page)
|
||||
fx.create_builder_link_element(user=user, page=page, value="'Go to docs'")
|
||||
fx.create_builder_table_element(user=user, page=page, data_source=data_source)
|
||||
fx.create_builder_menu_element_items(user=user, page=page)
|
||||
|
||||
# Containers with children exercise parent_element_id / place_in_container.
|
||||
column = fx.create_builder_column_element(user=user, page=page, column_amount=2)
|
||||
fx.create_builder_text_element(
|
||||
user=user,
|
||||
page=page,
|
||||
value="'In a column'",
|
||||
position=GraphPointPosition.CHILD,
|
||||
reference_element=column,
|
||||
place_in_container="0",
|
||||
)
|
||||
form_container = fx.create_builder_form_container_element(user=user, page=page)
|
||||
fx.create_builder_input_text_element(
|
||||
user=user,
|
||||
page=page,
|
||||
label="'Your name'",
|
||||
position=GraphPointPosition.CHILD,
|
||||
reference_element=form_container,
|
||||
place_in_container="0",
|
||||
)
|
||||
fx.create_builder_choice_element(
|
||||
user=user,
|
||||
page=page,
|
||||
label="'Pick one'",
|
||||
position=GraphPointPosition.CHILD,
|
||||
reference_element=form_container,
|
||||
place_in_container="0",
|
||||
)
|
||||
fx.create_builder_checkbox_element(
|
||||
user=user,
|
||||
page=page,
|
||||
label="'Agree'",
|
||||
position=GraphPointPosition.CHILD,
|
||||
reference_element=form_container,
|
||||
place_in_container="0",
|
||||
)
|
||||
button = fx.create_builder_button_element(
|
||||
user=user,
|
||||
page=page,
|
||||
value="'Submit'",
|
||||
position=GraphPointPosition.CHILD,
|
||||
reference_element=form_container,
|
||||
place_in_container="0",
|
||||
)
|
||||
|
||||
# Shared-page elements are merged into list_elements as page_name="[shared]".
|
||||
fx.create_builder_heading_element(
|
||||
user=user, page=builder.shared_page, value="'Header'"
|
||||
)
|
||||
|
||||
fx.create_notification_workflow_action(page=page, element=button, event="click")
|
||||
upsert_service = fx.create_local_baserow_upsert_row_service(
|
||||
integration=integration, table=table
|
||||
)
|
||||
upsert_service.field_mappings.create(field=name_field, value="'Ordered'")
|
||||
fx.create_local_baserow_create_row_workflow_action(
|
||||
page=page, element=button, event="click", service=upsert_service
|
||||
)
|
||||
|
||||
return {"builder": builder, "page": page, "button": button}
|
||||
|
||||
|
||||
def _seed_automation(
|
||||
fx: Any, user: AbstractUser, workspace: Workspace
|
||||
) -> dict[str, Any]:
|
||||
automation = fx.create_automation_application(
|
||||
user=user, workspace=workspace, name="Ops"
|
||||
)
|
||||
workflow = fx.create_automation_workflow(
|
||||
user=user, automation=automation, name="Nightly sync"
|
||||
)
|
||||
fx.create_local_baserow_create_row_action_node(user=user, workflow=workflow)
|
||||
fx.create_local_baserow_update_row_action_node(user=user, workflow=workflow)
|
||||
return {"automation": automation, "workflow": workflow}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def seed(premium_data_fixture: Any) -> SeededWorkspace:
|
||||
fx = premium_data_fixture
|
||||
user = fx.create_user()
|
||||
workspace = fx.create_workspace(user=user)
|
||||
|
||||
db_parts = _seed_database(fx, user, workspace)
|
||||
builder_parts = _seed_builder(
|
||||
fx, user, workspace, db_parts["table"], db_parts["name_field"]
|
||||
)
|
||||
automation_parts = _seed_automation(fx, user, workspace)
|
||||
|
||||
return SeededWorkspace(
|
||||
user=user,
|
||||
workspace=workspace,
|
||||
database=db_parts["database"],
|
||||
table=db_parts["table"],
|
||||
linked_table=db_parts["linked_table"],
|
||||
builder=builder_parts["builder"],
|
||||
page=builder_parts["page"],
|
||||
button=builder_parts["button"],
|
||||
automation=automation_parts["automation"],
|
||||
workflow=automation_parts["workflow"],
|
||||
)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# Shape assertions
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
def assert_items(
|
||||
items: Any, required: dict[str, type | tuple[type, ...]], label: str
|
||||
) -> None:
|
||||
"""Assert ``items`` is a non-empty list of dicts carrying typed keys."""
|
||||
|
||||
assert isinstance(items, list), f"{label}: expected a list, got {type(items)}"
|
||||
assert items, f"{label}: empty collection — the seed must populate this tool"
|
||||
for item in items:
|
||||
assert isinstance(item, dict), f"{label}: expected dicts, got {type(item)}"
|
||||
for key, expected in required.items():
|
||||
assert key in item, f"{label}: missing key {key!r} in {item!r}"
|
||||
assert isinstance(item[key], expected), (
|
||||
f"{label}: {key!r} is {type(item[key])}, expected {expected}"
|
||||
)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# Read-tool contract cases
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReadToolCase:
|
||||
"""One read tool, how to call it, and what its output must look like."""
|
||||
|
||||
name: str
|
||||
invoke: Callable[[Any, SeededWorkspace], Any]
|
||||
check: Callable[[Any, SeededWorkspace], None]
|
||||
|
||||
|
||||
def _check_list_builders(result: Any, seed: SeededWorkspace) -> None:
|
||||
assert set(result) >= {"database", "application", "automation"}
|
||||
for builder_type in ("database", "application", "automation"):
|
||||
assert_items(
|
||||
result[builder_type],
|
||||
{"id": int, "name": str, "type": str},
|
||||
f"list_builders[{builder_type}]",
|
||||
)
|
||||
ids = {item["id"] for items in result.values() for item in items}
|
||||
assert {seed.database.id, seed.builder.id, seed.automation.id} <= ids
|
||||
|
||||
|
||||
def _check_list_tables(result: Any, seed: SeededWorkspace) -> None:
|
||||
tables = result["tables"]
|
||||
assert_items(tables, {"id": int, "name": str, "database_id": int}, "list_tables")
|
||||
assert {t["id"] for t in tables} == {seed.table.id, seed.linked_table.id}
|
||||
|
||||
|
||||
def _check_get_tables_schema(result: Any, seed: SeededWorkspace) -> None:
|
||||
schemas = result["tables_schema"]
|
||||
assert_items(
|
||||
schemas,
|
||||
{"id": int, "name": str, "fields": list, "primary_field": dict},
|
||||
"get_tables_schema",
|
||||
)
|
||||
assert {s["id"] for s in schemas} == {seed.table.id, seed.linked_table.id}
|
||||
for schema in schemas:
|
||||
assert_items(
|
||||
schema["fields"],
|
||||
{"id": int, "name": str, "type": str},
|
||||
f"get_tables_schema[{schema['name']}].fields",
|
||||
)
|
||||
orders = next(s for s in schemas if s["id"] == seed.table.id)
|
||||
orders_fields = [orders["primary_field"], *orders["fields"]]
|
||||
assert {f["type"] for f in orders_fields} >= {
|
||||
"text",
|
||||
"long_text",
|
||||
"number",
|
||||
"date",
|
||||
"boolean",
|
||||
"single_select",
|
||||
"link_row",
|
||||
"file",
|
||||
}
|
||||
|
||||
|
||||
def _check_list_rows(result: Any, seed: SeededWorkspace) -> None:
|
||||
assert result["total"] == 2
|
||||
assert_items(result["rows"], {"id": int, "Name": str}, "list_rows")
|
||||
assert {row["Name"] for row in result["rows"]} == {"First order", "Second order"}
|
||||
|
||||
|
||||
def _check_list_views(result: Any, seed: SeededWorkspace) -> None:
|
||||
views = result["views"]
|
||||
assert_items(
|
||||
views, {"id": int, "name": str, "type": str, "public": bool}, "list_views"
|
||||
)
|
||||
assert {v["type"] for v in views} == set(SEEDED_VIEW_TYPES)
|
||||
|
||||
|
||||
def _check_list_workflows(result: Any, seed: SeededWorkspace) -> None:
|
||||
assert_items(
|
||||
result["workflows"], {"id": int, "name": str, "state": str}, "list_workflows"
|
||||
)
|
||||
assert [w["id"] for w in result["workflows"]] == [seed.workflow.id]
|
||||
|
||||
|
||||
def _check_list_nodes(result: Any, seed: SeededWorkspace) -> None:
|
||||
assert_items(result["nodes"], {"id": int, "label": str, "type": str}, "list_nodes")
|
||||
assert len(result["nodes"]) == 3
|
||||
|
||||
|
||||
def _check_list_pages(result: Any, seed: SeededWorkspace) -> None:
|
||||
assert_items(
|
||||
result["pages"],
|
||||
{"id": int, "name": str, "path": str, "visibility": str, "roles": list},
|
||||
"list_pages",
|
||||
)
|
||||
assert [p["id"] for p in result["pages"]] == [seed.page.id]
|
||||
assert isinstance(result["user_sources"], list)
|
||||
assert isinstance(result["available_roles"], list)
|
||||
|
||||
|
||||
def _check_list_data_sources(result: Any, seed: SeededWorkspace) -> None:
|
||||
sources = result["data_sources"]
|
||||
assert_items(sources, {"id": int, "name": str, "type": str}, "list_data_sources")
|
||||
orders = next(ds for ds in sources if ds["name"] == "Orders")
|
||||
assert orders["type"] == "local_baserow_list_rows"
|
||||
assert orders["table_id"] == seed.table.id
|
||||
assert orders["table_name"] == seed.table.name
|
||||
|
||||
|
||||
def _check_list_elements(result: Any, seed: SeededWorkspace) -> None:
|
||||
elements = result["elements"]
|
||||
assert_items(
|
||||
elements,
|
||||
{"id": int, "type": str, "is_container": bool, "page_name": str},
|
||||
"list_elements",
|
||||
)
|
||||
assert set(SEEDED_ELEMENT_TYPES) <= {el["type"] for el in elements}
|
||||
assert any(el["parent_element_id"] is not None for el in elements)
|
||||
assert any(el["page_name"] == "[shared]" for el in elements)
|
||||
menu = next(el for el in elements if el["type"] == "menu")
|
||||
assert_items(menu["menu_items"], {"name": str, "type": str}, "list_elements.menu")
|
||||
|
||||
|
||||
def _check_list_actions(result: Any, seed: SeededWorkspace) -> None:
|
||||
actions = result["workflow_actions"]
|
||||
assert_items(
|
||||
actions,
|
||||
{"id": int, "type": str, "element_id": int, "event": str},
|
||||
"list_actions",
|
||||
)
|
||||
assert {a["type"] for a in actions} == {"notification", "create_row"}
|
||||
create_row = next(a for a in actions if a["type"] == "create_row")
|
||||
assert create_row["table_id"] == seed.table.id
|
||||
assert_items(
|
||||
create_row["field_mappings"],
|
||||
{"field_id": int, "field_name": str, "value": str},
|
||||
"list_actions.field_mappings",
|
||||
)
|
||||
|
||||
|
||||
READ_TOOL_CASES: list[ReadToolCase] = [
|
||||
ReadToolCase(
|
||||
"list_builders",
|
||||
lambda ctx, s: list_builders(ctx, builder_types=None, thought="contract"),
|
||||
_check_list_builders,
|
||||
),
|
||||
ReadToolCase(
|
||||
"list_tables",
|
||||
lambda ctx, s: list_tables(
|
||||
ctx,
|
||||
filters=ListTablesFilterArg(
|
||||
database_id_or_name=s.database.id, table_ids_or_names=None
|
||||
),
|
||||
thought="contract",
|
||||
),
|
||||
_check_list_tables,
|
||||
),
|
||||
ReadToolCase(
|
||||
"get_tables_schema",
|
||||
lambda ctx, s: get_tables_schema(
|
||||
ctx,
|
||||
table_ids=[s.table.id, s.linked_table.id],
|
||||
full_schema=True,
|
||||
thought="contract",
|
||||
),
|
||||
_check_get_tables_schema,
|
||||
),
|
||||
ReadToolCase(
|
||||
"list_rows",
|
||||
lambda ctx, s: list_rows(
|
||||
ctx,
|
||||
table_id=s.table.id,
|
||||
offset=0,
|
||||
limit=20,
|
||||
field_ids=None,
|
||||
thought="contract",
|
||||
),
|
||||
_check_list_rows,
|
||||
),
|
||||
ReadToolCase(
|
||||
"list_views",
|
||||
lambda ctx, s: list_views(ctx, table_id=s.table.id, thought="contract"),
|
||||
_check_list_views,
|
||||
),
|
||||
ReadToolCase(
|
||||
"list_workflows",
|
||||
lambda ctx, s: list_workflows(
|
||||
ctx, automation_id=s.automation.id, thought="contract"
|
||||
),
|
||||
_check_list_workflows,
|
||||
),
|
||||
ReadToolCase(
|
||||
"list_nodes",
|
||||
lambda ctx, s: list_nodes(ctx, workflow_id=s.workflow.id, thought="contract"),
|
||||
_check_list_nodes,
|
||||
),
|
||||
ReadToolCase(
|
||||
"list_pages",
|
||||
lambda ctx, s: list_pages(ctx, application_id=s.builder.id, thought="contract"),
|
||||
_check_list_pages,
|
||||
),
|
||||
ReadToolCase(
|
||||
"list_data_sources",
|
||||
lambda ctx, s: list_data_sources(ctx, page_id=s.page.id, thought="contract"),
|
||||
_check_list_data_sources,
|
||||
),
|
||||
ReadToolCase(
|
||||
"list_elements",
|
||||
lambda ctx, s: list_elements(ctx, page_id=s.page.id, thought="contract"),
|
||||
_check_list_elements,
|
||||
),
|
||||
ReadToolCase(
|
||||
"list_actions",
|
||||
lambda ctx, s: list_actions(ctx, page_id=s.page.id, thought="contract"),
|
||||
_check_list_actions,
|
||||
),
|
||||
]
|
||||
|
||||
COVERED_TOOLS: frozenset[str] = frozenset(case.name for case in READ_TOOL_CASES)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize("case", READ_TOOL_CASES, ids=lambda case: case.name)
|
||||
def test_read_tool_contract(case: ReadToolCase, seed: SeededWorkspace) -> None:
|
||||
ctx = make_test_ctx(seed.user, seed.workspace)
|
||||
case.check(case.invoke(ctx, seed), seed)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# Registry coverage guard
|
||||
# ===========================================================================
|
||||
|
||||
_WRITE = "Mutating tool; its ORM round-trip is covered by the per-domain write tests."
|
||||
_LLM = "Needs a live model call, so it cannot run deterministically here."
|
||||
_CONTROL = "Control-flow only; serializes no ORM entity."
|
||||
|
||||
EXEMPT_TOOLS: dict[str, str] = {
|
||||
"switch_mode": _CONTROL,
|
||||
"navigate": _CONTROL,
|
||||
"ask_user": _CONTROL,
|
||||
"load_row_tools": _CONTROL,
|
||||
"search_user_docs": _LLM,
|
||||
"generate_formula": _LLM,
|
||||
"create_builders": _WRITE,
|
||||
"update_builder": _WRITE,
|
||||
"create_tables": _WRITE,
|
||||
"create_fields": _WRITE,
|
||||
"update_fields": _WRITE,
|
||||
"delete_fields": _WRITE,
|
||||
"create_views": _WRITE,
|
||||
"create_view_filters": _WRITE,
|
||||
"create_workflows": _WRITE,
|
||||
"add_nodes": _WRITE,
|
||||
"update_nodes": _WRITE,
|
||||
"delete_nodes": _WRITE,
|
||||
"create_pages": _WRITE,
|
||||
"update_page": _WRITE,
|
||||
"create_data_sources": _WRITE,
|
||||
"update_data_source": _WRITE,
|
||||
"create_display_elements": _WRITE,
|
||||
"create_layout_elements": _WRITE,
|
||||
"create_form_elements": _WRITE,
|
||||
"create_collection_elements": _WRITE,
|
||||
"update_element": _WRITE,
|
||||
"update_element_style": _WRITE,
|
||||
"move_elements": _WRITE,
|
||||
"create_actions": _WRITE,
|
||||
"add_action_field_mapping": _WRITE,
|
||||
"setup_page": _WRITE,
|
||||
"setup_user_source": _WRITE,
|
||||
"set_theme": _WRITE,
|
||||
}
|
||||
|
||||
|
||||
def registered_tool_names() -> set[str]:
|
||||
"""Every tool function name reachable through the assistant tool registry."""
|
||||
|
||||
return {
|
||||
func.__name__
|
||||
for tool_type in assistant_tool_registry.get_all()
|
||||
for func in tool_type.get_tool_functions()
|
||||
}
|
||||
|
||||
|
||||
def test_every_registered_tool_is_covered_or_exempt() -> None:
|
||||
registered = registered_tool_names()
|
||||
unclassified = registered - COVERED_TOOLS - set(EXEMPT_TOOLS)
|
||||
assert not unclassified, (
|
||||
f"New assistant tools {sorted(unclassified)} have no contract coverage. "
|
||||
"Add a ReadToolCase for read tools, or an EXEMPT_TOOLS entry with a reason."
|
||||
)
|
||||
|
||||
|
||||
def test_coverage_sets_match_the_registry() -> None:
|
||||
registered = registered_tool_names()
|
||||
stale = (COVERED_TOOLS | set(EXEMPT_TOOLS)) - registered
|
||||
assert not stale, f"Tools {sorted(stale)} are no longer registered; drop them."
|
||||
|
||||
|
||||
def test_read_tools_are_not_hidden_in_the_exempt_set() -> None:
|
||||
assert not COVERED_TOOLS & set(EXEMPT_TOOLS)
|
||||
assert not {name for name in EXEMPT_TOOLS if name.startswith("list_")}
|
||||
+619
@@ -0,0 +1,619 @@
|
||||
"""
|
||||
Deterministic assembly guard for the Kuma assistant toolset.
|
||||
|
||||
No LLM, no network: the real production toolset is built via
|
||||
``assistant_tool_registry.build_toolset()`` for a real user + workspace, and
|
||||
every tool it exposes is forced to produce the JSON schema and description the
|
||||
model actually reads. This is the guard against a pydantic model, annotation or
|
||||
docstring change that leaves the assistant unable to start — a class of failure
|
||||
that only the (paid, CI-skipped) eval suite would otherwise notice.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Callable, Iterator
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from django.contrib.auth.models import AbstractUser
|
||||
|
||||
import pytest
|
||||
from pydantic import BaseModel, ConfigDict, ValidationError
|
||||
from pydantic_ai import Agent, RunContext
|
||||
from pydantic_ai.exceptions import ModelRetry
|
||||
from pydantic_ai.messages import ModelResponse, TextPart, ToolCallPart, ToolReturnPart
|
||||
from pydantic_ai.models.function import AgentInfo, FunctionModel
|
||||
from pydantic_ai.models.groq import GroqModel
|
||||
from pydantic_ai.models.test import TestModel
|
||||
from pydantic_ai.providers.groq import GroqProvider
|
||||
from pydantic_ai.toolsets import AbstractToolset
|
||||
from pydantic_ai.toolsets.abstract import ToolsetTool
|
||||
from pydantic_ai.usage import RunUsage
|
||||
|
||||
from baserow.core.exceptions import PermissionDenied
|
||||
from baserow.core.models import Workspace
|
||||
from baserow_enterprise.assistant.deps import AgentMode, AssistantDeps
|
||||
from baserow_enterprise.assistant.model_profiles import (
|
||||
ResolvedAssistantModelProfile,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.registries import assistant_tool_registry
|
||||
from baserow_enterprise.assistant.tools.routing import (
|
||||
ModeAwareToolset,
|
||||
is_tool_active,
|
||||
routed_tool_names,
|
||||
tool_home,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.search_user_docs.tool_types import (
|
||||
SearchDocsToolType,
|
||||
)
|
||||
from baserow_enterprise.assistant.tools.toolset import (
|
||||
InlineRefsToolset,
|
||||
_find_placeholder_ids,
|
||||
format_tool_arg_errors,
|
||||
inline_refs,
|
||||
)
|
||||
|
||||
from .utils import create_fake_tool_helpers
|
||||
|
||||
# Profile lookups take the model string; no live model is ever constructed.
|
||||
MODEL_STRING = "groq:test-model"
|
||||
|
||||
ALL_MODES: list[AgentMode] = list(AgentMode)
|
||||
|
||||
|
||||
def registered_tool_functions() -> list[Callable]:
|
||||
"""Every tool function reachable through the assistant tool registry."""
|
||||
|
||||
return [
|
||||
func
|
||||
for tool_type in assistant_tool_registry.get_all()
|
||||
for func in tool_type.get_tool_functions()
|
||||
]
|
||||
|
||||
|
||||
REGISTERED_TOOLS: dict[str, Callable] = {
|
||||
func.__name__: func for func in registered_tool_functions()
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BuiltToolset:
|
||||
"""The production toolset, its dependencies, and tool catalog."""
|
||||
|
||||
toolset: AbstractToolset
|
||||
deps: AssistantDeps
|
||||
catalog: str
|
||||
|
||||
def tools_in(self, mode: AgentMode) -> dict[str, ToolsetTool]:
|
||||
"""Tools the assembled toolset exposes while the agent is in *mode*."""
|
||||
|
||||
return {
|
||||
name: tool
|
||||
for name, tool in self.managed_tools_in(mode).items()
|
||||
if not tool.tool_def.defer_loading
|
||||
}
|
||||
|
||||
def managed_tools_in(self, mode: AgentMode) -> dict[str, ToolsetTool]:
|
||||
"""All resolvable tools, including deferred tools owned by another mode."""
|
||||
|
||||
self.deps.mode = mode
|
||||
ctx: RunContext[AssistantDeps] = RunContext(
|
||||
deps=self.deps, model=TestModel(), usage=RunUsage()
|
||||
)
|
||||
return asyncio.run(self.toolset.get_tools(ctx))
|
||||
|
||||
def all_exposed_tools(self) -> dict[str, ToolsetTool]:
|
||||
"""Union of the tools exposed across every mode."""
|
||||
|
||||
return {
|
||||
name: tool
|
||||
for mode in ALL_MODES
|
||||
for name, tool in self.tools_in(mode).items()
|
||||
}
|
||||
|
||||
|
||||
def build_production_toolset(user: AbstractUser, workspace: Workspace) -> BuiltToolset:
|
||||
deps = AssistantDeps(
|
||||
user=user, workspace=workspace, tool_helpers=create_fake_tool_helpers()
|
||||
)
|
||||
toolset, catalog = assistant_tool_registry.build_toolset(
|
||||
user=user,
|
||||
workspace=workspace,
|
||||
model=MODEL_STRING,
|
||||
model_profile=deps.tool_helpers.model_profile,
|
||||
deps=deps,
|
||||
)
|
||||
deps.tool_catalog = catalog
|
||||
return BuiltToolset(toolset=toolset, deps=deps, catalog=catalog)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def searchable_knowledge_base() -> Iterator[None]:
|
||||
"""Open the ``search_user_docs`` gate, which needs pgvector plus indexed docs."""
|
||||
|
||||
with patch.object(SearchDocsToolType, "can_use", return_value=True):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def built(data_fixture: Any, searchable_knowledge_base: None) -> BuiltToolset:
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
return build_production_toolset(user, workspace)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# Assembly
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize("mode", ALL_MODES, ids=lambda mode: mode.value)
|
||||
def test_toolset_assembles_in_every_mode(mode: AgentMode, built: BuiltToolset) -> None:
|
||||
tools = built.tools_in(mode)
|
||||
assert tools, f"{mode.value} mode exposes no tools at all"
|
||||
unknown = set(tools) - set(REGISTERED_TOOLS)
|
||||
assert not unknown, (
|
||||
f"{mode.value} mode exposes unregistered tools {sorted(unknown)}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_every_registered_tool_is_exposed_in_some_mode(built: BuiltToolset) -> None:
|
||||
exposed = set(built.all_exposed_tools())
|
||||
dropped = set(REGISTERED_TOOLS) - exposed
|
||||
assert not dropped, (
|
||||
f"Registered tools {sorted(dropped)} are unreachable in every mode: the "
|
||||
"assistant can never call them. Add a route for them in "
|
||||
"baserow_enterprise.assistant.tools.routing._tool_routes."
|
||||
)
|
||||
assert exposed == set(REGISTERED_TOOLS)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_wrong_mode_tools_are_deferred_but_resolvable(built: BuiltToolset) -> None:
|
||||
managed = built.managed_tools_in(AgentMode.DATABASE)
|
||||
|
||||
assert not managed["create_tables"].tool_def.defer_loading
|
||||
routed = managed["create_workflows"]
|
||||
assert routed.tool_def.defer_loading
|
||||
assert routed.tool_def.metadata["assistant_mode"] == "automation"
|
||||
assert managed["list_workflows"].tool_def.metadata["assistant_mode"] == (
|
||||
"automation"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
def test_gpt_oss_model_can_discover_route_and_execute_a_wrong_mode_tool(
|
||||
built: BuiltToolset, data_fixture: Any
|
||||
) -> None:
|
||||
automation = data_fixture.create_automation_application(
|
||||
user=built.deps.user,
|
||||
workspace=built.deps.workspace,
|
||||
name="Restaurant Automation",
|
||||
)
|
||||
workflow = data_fixture.create_automation_workflow(
|
||||
automation=automation, name="Process Orders"
|
||||
)
|
||||
built.deps.mode = AgentMode.DATABASE
|
||||
expected = {
|
||||
"workflows": [{"id": workflow.id, "name": "Process Orders", "state": "draft"}]
|
||||
}
|
||||
visible_by_request: list[dict[str, Any]] = []
|
||||
|
||||
def model_function(messages, info: AgentInfo) -> ModelResponse:
|
||||
visible = {tool.name: tool for tool in info.function_tools}
|
||||
visible_by_request.append(visible)
|
||||
request_number = len(visible_by_request)
|
||||
|
||||
if request_number == 1:
|
||||
# Groq has no native ToolSearch, so Pydantic AI must expose its local
|
||||
# fallback while withholding the deferred production-tool schema.
|
||||
assert "search_tools" in visible
|
||||
assert "list_workflows" not in visible
|
||||
return ModelResponse(
|
||||
parts=[
|
||||
ToolCallPart(
|
||||
tool_name="search_tools",
|
||||
args={"queries": ["list_workflows"]},
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
call = ToolCallPart(
|
||||
tool_name="list_workflows",
|
||||
args={
|
||||
"automation_id": automation.id,
|
||||
"thought": "Checking the existing workflows",
|
||||
},
|
||||
)
|
||||
if request_number == 2:
|
||||
# Discovery makes the real schema model-visible, but it remains
|
||||
# deferred until the mode-aware wrapper receives the first call.
|
||||
assert visible["list_workflows"].defer_loading
|
||||
assert set(
|
||||
visible["list_workflows"].parameters_json_schema["required"]
|
||||
) == {"automation_id", "thought"}
|
||||
return ModelResponse(parts=[call])
|
||||
|
||||
if request_number == 3:
|
||||
# The retry triggered by the discovered call switched modes. The
|
||||
# next request now contains the active, non-deferred schema.
|
||||
assert built.deps.mode == AgentMode.AUTOMATION
|
||||
assert not visible["list_workflows"].defer_loading
|
||||
return ModelResponse(parts=[call])
|
||||
|
||||
tool_return = messages[-1].parts[-1]
|
||||
assert isinstance(tool_return, ToolReturnPart)
|
||||
assert tool_return.tool_name == "list_workflows"
|
||||
assert tool_return.content == expected
|
||||
return ModelResponse(parts=[TextPart(content="done")])
|
||||
|
||||
gpt_oss = GroqModel(
|
||||
"openai/gpt-oss-120b", provider=GroqProvider(api_key="not-used")
|
||||
)
|
||||
agent: Agent[AssistantDeps, str] = Agent(
|
||||
model=FunctionModel(model_function, profile=gpt_oss.profile),
|
||||
deps_type=AssistantDeps,
|
||||
output_type=str,
|
||||
toolsets=[built.toolset],
|
||||
)
|
||||
|
||||
result = agent.run_sync("List the workflows", deps=built.deps)
|
||||
|
||||
assert result.output == "done"
|
||||
assert len(visible_by_request) == 4
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_toolset_still_assembles_when_a_tool_group_is_gated_off(
|
||||
data_fixture: Any,
|
||||
) -> None:
|
||||
"""``can_use()`` returning False must drop tools, not break assembly."""
|
||||
|
||||
user = data_fixture.create_user()
|
||||
workspace = data_fixture.create_workspace(user=user)
|
||||
with patch.object(SearchDocsToolType, "can_use", return_value=False):
|
||||
built = build_production_toolset(user, workspace)
|
||||
exposed = set(built.all_exposed_tools())
|
||||
assert "search_user_docs" not in exposed
|
||||
assert "list_tables" in exposed
|
||||
assert built.catalog
|
||||
assert "search_user_docs" not in built.catalog
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_permission_errors_become_actionable_tool_results(built: BuiltToolset) -> None:
|
||||
inner = MagicMock()
|
||||
inner.call_tool = AsyncMock(side_effect=PermissionDenied())
|
||||
routed = ModeAwareToolset(inner, built.deps)
|
||||
tool = built.managed_tools_in(AgentMode.DATABASE)["create_tables"]
|
||||
|
||||
result = asyncio.run(routed.call_tool("create_tables", {}, None, tool))
|
||||
|
||||
assert result["error"] == "create_tables stopped because permission was denied."
|
||||
assert "Do not retry or claim" in result["next_steps"]
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# Per-tool schema contract
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
def _refs_in(node: Any) -> list[str]:
|
||||
"""Every ``$ref``/``$defs`` key left in a schema after ref inlining."""
|
||||
|
||||
found: list[str] = []
|
||||
if isinstance(node, dict):
|
||||
for key, value in node.items():
|
||||
if key in ("$ref", "$defs"):
|
||||
found.append(key)
|
||||
found.extend(_refs_in(value))
|
||||
elif isinstance(node, list):
|
||||
for item in node:
|
||||
found.extend(_refs_in(item))
|
||||
return found
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize("tool_name", sorted(REGISTERED_TOOLS))
|
||||
def test_tool_exposes_a_schema_the_model_can_read(
|
||||
tool_name: str, built: BuiltToolset
|
||||
) -> None:
|
||||
tool = built.all_exposed_tools().get(tool_name)
|
||||
assert tool is not None, f"{tool_name} is registered but exposed in no mode"
|
||||
|
||||
description = (tool.tool_def.description or "").strip()
|
||||
assert description, (
|
||||
f"{tool_name} has no description: the model gets a nameless tool. Give "
|
||||
"the tool function a docstring."
|
||||
)
|
||||
|
||||
schema = tool.tool_def.parameters_json_schema
|
||||
assert isinstance(schema, dict), f"{tool_name}: parameter schema is not an object"
|
||||
assert schema.get("type") == "object", (
|
||||
f"{tool_name}: parameter schema type is {schema.get('type')!r}, expected "
|
||||
"'object'"
|
||||
)
|
||||
properties = schema.get("properties")
|
||||
assert isinstance(properties, dict) and properties, (
|
||||
f"{tool_name}: parameter schema has no properties"
|
||||
)
|
||||
leftover = _refs_in(schema)
|
||||
assert not leftover, (
|
||||
f"{tool_name}: schema still contains {sorted(set(leftover))} after "
|
||||
"inline_refs; open-weight models cannot follow the indirection."
|
||||
)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# Catalog
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize("mode", ALL_MODES, ids=lambda mode: mode.value)
|
||||
def test_catalog_lists_every_tool_callable_in_that_mode(
|
||||
mode: AgentMode, built: BuiltToolset
|
||||
) -> None:
|
||||
listed = {
|
||||
name
|
||||
for line in built.catalog.splitlines()
|
||||
if line.startswith("- ") and ": " in line
|
||||
for name in line.split(": ", 1)[1].split(", ")
|
||||
}
|
||||
missing = set(built.tools_in(mode)) - listed
|
||||
assert not missing, (
|
||||
f"The catalog omits {mode.value} tools {sorted(missing)}; the model "
|
||||
"will never know they exist."
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_deps_expose_one_catalog(built: BuiltToolset) -> None:
|
||||
assert built.deps.tool_catalog == built.catalog
|
||||
|
||||
|
||||
def test_canonical_home_is_independent_from_shared_visibility() -> None:
|
||||
assert tool_home("list_workflows") == AgentMode.AUTOMATION
|
||||
assert is_tool_active("list_workflows", AgentMode.EXPLAIN)
|
||||
|
||||
|
||||
DATABASE = AgentMode.DATABASE
|
||||
APPLICATION = AgentMode.APPLICATION
|
||||
AUTOMATION = AgentMode.AUTOMATION
|
||||
EXPLAIN = AgentMode.EXPLAIN
|
||||
EVERYWHERE = frozenset(AgentMode)
|
||||
|
||||
# Adding a tool must fail here, so its reach is a decision and not a default.
|
||||
TOOL_VISIBILITY: dict[str, frozenset[AgentMode]] = {
|
||||
"add_action_field_mapping": frozenset({APPLICATION}),
|
||||
"add_nodes": frozenset({AUTOMATION}),
|
||||
"ask_user": EVERYWHERE,
|
||||
"create_actions": frozenset({APPLICATION}),
|
||||
"create_builders": EVERYWHERE - {EXPLAIN},
|
||||
"create_collection_elements": frozenset({APPLICATION}),
|
||||
"create_data_sources": frozenset({APPLICATION}),
|
||||
"create_display_elements": frozenset({APPLICATION}),
|
||||
"create_fields": frozenset({DATABASE}),
|
||||
"create_form_elements": frozenset({APPLICATION}),
|
||||
"create_layout_elements": frozenset({APPLICATION}),
|
||||
"create_pages": frozenset({APPLICATION}),
|
||||
"create_tables": frozenset({DATABASE}),
|
||||
"create_view_filters": frozenset({DATABASE}),
|
||||
"create_views": frozenset({DATABASE}),
|
||||
"create_workflows": frozenset({AUTOMATION}),
|
||||
"delete_fields": frozenset({DATABASE}),
|
||||
"delete_nodes": frozenset({AUTOMATION}),
|
||||
"generate_formula": frozenset({DATABASE}),
|
||||
"get_tables_schema": EVERYWHERE,
|
||||
"list_actions": frozenset({APPLICATION, EXPLAIN}),
|
||||
"list_builders": EVERYWHERE,
|
||||
"list_data_sources": frozenset({APPLICATION, EXPLAIN}),
|
||||
"list_elements": frozenset({APPLICATION, EXPLAIN}),
|
||||
"list_nodes": frozenset({AUTOMATION, EXPLAIN}),
|
||||
"list_pages": frozenset({APPLICATION, EXPLAIN}),
|
||||
"list_rows": EVERYWHERE,
|
||||
"list_tables": EVERYWHERE,
|
||||
"list_views": EVERYWHERE,
|
||||
"list_workflows": frozenset({AUTOMATION, EXPLAIN}),
|
||||
"load_row_tools": frozenset({DATABASE}),
|
||||
"move_elements": frozenset({APPLICATION}),
|
||||
"navigate": EVERYWHERE,
|
||||
"search_user_docs": EVERYWHERE,
|
||||
"set_theme": frozenset({APPLICATION}),
|
||||
"setup_page": frozenset({APPLICATION}),
|
||||
"setup_user_source": frozenset({APPLICATION}),
|
||||
"switch_mode": EVERYWHERE,
|
||||
"update_builder": EVERYWHERE - {EXPLAIN},
|
||||
"update_data_source": frozenset({APPLICATION}),
|
||||
"update_element": frozenset({APPLICATION}),
|
||||
"update_element_style": frozenset({APPLICATION}),
|
||||
"update_fields": frozenset({DATABASE}),
|
||||
"update_nodes": frozenset({AUTOMATION}),
|
||||
"update_page": frozenset({APPLICATION}),
|
||||
}
|
||||
|
||||
|
||||
def test_every_routed_tool_has_the_expected_reach() -> None:
|
||||
actual = {
|
||||
name: frozenset(mode for mode in AgentMode if is_tool_active(name, mode))
|
||||
for name in routed_tool_names()
|
||||
}
|
||||
|
||||
assert actual == TOOL_VISIBILITY
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_tool_catalog_stays_compact_and_does_not_repeat_tool_docs(
|
||||
built: BuiltToolset,
|
||||
) -> None:
|
||||
assert len(built.catalog) < 4000
|
||||
assert "WHEN to use" not in built.catalog
|
||||
assert built.catalog.startswith("- database:")
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# Failure-path machinery (tools.toolset)
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
class _FieldArg(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: str
|
||||
field_type: str
|
||||
|
||||
|
||||
class _CreateFieldsArgs(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
table_id: int
|
||||
fields: list[_FieldArg]
|
||||
|
||||
|
||||
_ARGS_SCHEMA: dict = inline_refs(_CreateFieldsArgs.model_json_schema())
|
||||
|
||||
|
||||
class _ModelValidator:
|
||||
"""Stand-in for the pydantic-core validator pydantic-ai attaches to a tool."""
|
||||
|
||||
def validate_python(self, value: Any) -> dict[str, Any]:
|
||||
return _CreateFieldsArgs.model_validate(value).model_dump()
|
||||
|
||||
|
||||
def _validation_errors(wrong_args: dict) -> list[dict]:
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
_CreateFieldsArgs.model_validate(wrong_args)
|
||||
return exc_info.value.errors(include_url=False, include_context=False)
|
||||
|
||||
|
||||
def test_arg_error_report_names_paths_shapes_and_id_producers() -> None:
|
||||
wrong_args = {"table_id": "nope", "fields": [{"name": "Amount", "kind": "number"}]}
|
||||
|
||||
report = format_tool_arg_errors(
|
||||
"create_fields", _ARGS_SCHEMA, wrong_args, _validation_errors(wrong_args)
|
||||
)
|
||||
|
||||
assert "create_fields did NOT run" in report
|
||||
assert "Call list_tables to get a real id" in report
|
||||
assert "fields.0.field_type: required" in report
|
||||
assert "name*, field_type*" in report
|
||||
assert "Never invent an id" in report
|
||||
|
||||
|
||||
def test_arg_error_report_never_raises_on_malformed_error_payloads() -> None:
|
||||
report = format_tool_arg_errors("list_rows", {}, {"table_id": 1}, None)
|
||||
|
||||
assert "list_rows did NOT run" in report
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"args,expected",
|
||||
[
|
||||
({"table_id": 0}, [("table_id", "list_tables", 0)]),
|
||||
({"navigate_to_page_id": 0}, [("navigate_to_page_id", "list_pages", 0)]),
|
||||
(
|
||||
{"view": {"cover_field_id": -1}},
|
||||
[("view.cover_field_id", "get_tables_schema", -1)],
|
||||
),
|
||||
({"field_ids": [3, 0]}, [("field_ids[1]", "get_tables_schema", 0)]),
|
||||
(
|
||||
{"filters": [{"field_id": "0"}]},
|
||||
[("filters[0].field_id", "get_tables_schema", "0")],
|
||||
),
|
||||
({"table_id": 5, "row_id": 0, "amount": 0}, []),
|
||||
],
|
||||
)
|
||||
def test_placeholder_id_detection(
|
||||
args: dict[str, Any], expected: list[tuple[str, str, Any]]
|
||||
) -> None:
|
||||
assert _find_placeholder_ids(args) == expected
|
||||
|
||||
|
||||
def _wrapped_toolset() -> tuple[InlineRefsToolset, AsyncMock]:
|
||||
inner = MagicMock()
|
||||
inner.call_tool = AsyncMock(return_value={"ok": True})
|
||||
profile = MagicMock(spec=ResolvedAssistantModelProfile)
|
||||
return (
|
||||
InlineRefsToolset(inner, model=TestModel(), model_profile=profile),
|
||||
inner.call_tool,
|
||||
)
|
||||
|
||||
|
||||
def test_call_tool_blocks_invented_ids_before_execution() -> None:
|
||||
toolset, inner_call = _wrapped_toolset()
|
||||
|
||||
result = asyncio.run(
|
||||
toolset.call_tool("create_fields", {"table_id": 0, "fields": []}, None, None)
|
||||
)
|
||||
|
||||
assert "Invented IDs: table_id=0" in result["error"]
|
||||
assert "list_tables" in result["next_steps"]
|
||||
inner_call.assert_not_awaited()
|
||||
|
||||
|
||||
def test_call_tool_executes_with_real_ids() -> None:
|
||||
toolset, inner_call = _wrapped_toolset()
|
||||
|
||||
result = asyncio.run(toolset.call_tool("list_rows", {"table_id": 7}, None, None))
|
||||
|
||||
assert result == {"ok": True}
|
||||
inner_call.assert_awaited_once_with("list_rows", {"table_id": 7}, None, None)
|
||||
|
||||
|
||||
def _fixer_toolset() -> tuple[InlineRefsToolset, AsyncMock]:
|
||||
toolset, inner_call = _wrapped_toolset()
|
||||
toolset._original_validators["create_fields"] = _ModelValidator()
|
||||
toolset._schemas["create_fields"] = _ARGS_SCHEMA
|
||||
return toolset, inner_call
|
||||
|
||||
|
||||
def _call_with_fixer_reply(toolset: InlineRefsToolset, reply: str) -> Any:
|
||||
with patch("baserow_enterprise.assistant.tools.toolset.Agent") as agent_cls:
|
||||
agent_cls.return_value.run = AsyncMock(
|
||||
return_value=SimpleNamespace(output=reply)
|
||||
)
|
||||
return asyncio.run(
|
||||
toolset.call_tool("create_fields", {"fields": []}, None, None)
|
||||
)
|
||||
|
||||
|
||||
def test_fixed_args_are_revalidated_and_executed() -> None:
|
||||
toolset, inner_call = _fixer_toolset()
|
||||
fixed = {"table_id": 7, "fields": [{"name": "Amount", "field_type": "number"}]}
|
||||
|
||||
result = _call_with_fixer_reply(toolset, json.dumps(fixed))
|
||||
|
||||
assert result == {"ok": True}
|
||||
inner_call.assert_awaited_once_with("create_fields", fixed, None, None)
|
||||
|
||||
|
||||
def test_cannot_fix_reply_raises_model_retry_instead_of_executing() -> None:
|
||||
toolset, inner_call = _fixer_toolset()
|
||||
reply = json.dumps({"__cannot_fix__": "the real table id"})
|
||||
|
||||
with pytest.raises(ModelRetry, match="the real table id"):
|
||||
_call_with_fixer_reply(toolset, reply)
|
||||
inner_call.assert_not_awaited()
|
||||
|
||||
|
||||
def test_still_invalid_fix_raises_the_rendered_report() -> None:
|
||||
toolset, inner_call = _fixer_toolset()
|
||||
|
||||
with pytest.raises(ModelRetry, match="did NOT run") as exc_info:
|
||||
_call_with_fixer_reply(toolset, json.dumps({"fields": []}))
|
||||
|
||||
assert "table_id" in str(exc_info.value)
|
||||
inner_call.assert_not_awaited()
|
||||
|
||||
|
||||
def test_fixer_crash_degrades_to_model_retry_with_the_report() -> None:
|
||||
toolset, inner_call = _fixer_toolset()
|
||||
|
||||
with patch("baserow_enterprise.assistant.tools.toolset.Agent") as agent_cls:
|
||||
agent_cls.return_value.run = AsyncMock(side_effect=RuntimeError("boom"))
|
||||
with pytest.raises(ModelRetry, match="did NOT run"):
|
||||
asyncio.run(toolset.call_tool("create_fields", {"fields": []}, None, None))
|
||||
inner_call.assert_not_awaited()
|
||||
Reference in new issue
Block a user