feat(analyst): harness robustness for data-question runs

Merged
AN
2mo ago
+36885-1587

Issue for this PR

No GitHub issue; tracked internally (analyst harness robustness, Oct 2026).

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

These 25 commits make analyst runs produce usable answers despite slow providers, large transfers and tool-contract failures, and close SQL read-permission bypasses and scratch/search isolation holes. There is no workload-specific logic anywhere in the branch. This description covers HEAD 07249b8d47.

Problems described below were observed in evaluation traces of long-running analyst sessions; the internal trace analysis is available on request.

1. Provider and request robustness

Observed: a header timeout became a terminal UnknownError, a stalled Bedrock request consumed a trial, and a BigInt tool result broke the next request (commit b27419790c). Some sessions also went silent early in an 860 s budget and stayed silent until the time-budget abort.
Retry header timeouts as API errors; keep the header timeout opt-in for non-OpenAI providers. Extend the Bedrock-eventstream idle watchdog to streaming bodies from every provider: silence raises MODEL_STOPPED_RESPONDING, with bounded retries only before that attempt emits any output. Retrying after text or tool calls could execute a tool twice; f5ea25b9aa closes that hole. Preserve the 300-second chunkTimeout default from PR #844; ALTIMATE_STREAM_IDLE_TIMEOUT_MS overrides it, and 0 disables it (1679f90d6a). Normalize BigInts at request/trace boundaries, surface empty decode failures, and retry startup provider-list failures instead of reporting a missing model.
Cap traced user/synthetic attachment text at 4,000 characters and serialize API errors without response headers or unbounded bodies (f5ea25b9aa).

2. SQL tools and scratch storage

Observed: 49/56 sql_check calls were rejected, 21/44 schema inspections returned empty success, scratch writes were denied, and 52/52 Mongo reads were classified as writes; large transfers exhausted memory or lost scratch tables after a timeout.

  • Add 120-second query deadlines, supervised local-engine helpers, explicit result previews and typed JSONL spills. Load DuckDB outside the parent argv to fix run --dir; classify metadata statements as reads.
  • An independent review found a critical bypass: E'\'--'; DELETE could run as a read. Add the string-literal-aware sql-tokenize.ts, strip comments per parsed statement, and reject parser failures as reads. sql_check, sql_materialize and result lint require a single parser-reported query; sql_execute accepts classifier-proven reads, including read metadata statements, but refuses multi-statement reads. Writing PRAGMAs require write permission (fec392c583).
  • Add sql_check invariants for fan-out, key matching, grain, nulls and coverage; accept unused empty fields while preserving meaningful empty patterns. Resolve engine-default schemas, bound fallback probing, report missing tables, and include value samples.
  • After 14 failed schema_inspect(schema_name="scratch") calls in one session, resolve schema_name or the leading qualifier of table to a configured warehouse's default schema when it names that warehouse and no such schema exists. Return a note, let explicit warehouse win, and show the addressing form in not-found errors (4787af68e9).
  • Pre-flight SQL and Mongo materializations with bounded counts and samples; add max_bytes (256 MiB default, 2 GiB hard cap). Accept native Mongo command documents and classify reads by command.
  • Allow only scratch-safe table/view and row writes without source-write permission. Use a private temporary DuckDB file so committed scratch tables survive helper restarts; bulk-load typed JSONL instead of 500-row insert batches. Key stores by the root session so subagents share their parent's tables while independent sessions remain isolated; close stores on session removal (c95ddd2633). Restore real DuckDB exports after test mocks to prevent suite-order failures.
  • Run the local-engine helper in the caller's cwd so relative SQL paths resolve correctly. Keep the private temp directory for HOME/XDG/TMP and DuckDB spill; pass TZ, proxy and documented credential variables, and use the real extension directory. close() bypasses the query queue with a 2 s polite grace or 500 ms for an in-flight query. Decode rows as plain objects and BLOBs as Buffers; forward Mongo count/distinct command query filters (32053eb019).

3. Lint on execute

Observed: traces contained incorrect calculations and reserved aliases, while the analyst never called the separate check/lint tools (commit 7bd8be1c46).
sql-result-lint.ts appends up to three advisory correctness findings to sql_execute/sql_materialize results and records lint_rules. It uses an allowlist, limits schema construction to referenced tables, and disables later session lints after a 250 ms overrun; synchronous core lint is not interruptible. ALTIMATE_SQL_EXECUTE_LINT=0 disables it.
The four rules integer_division, limit_without_order_by, avg_of_avg, and reserved_word_alias are allowlisted here but implemented in altimate-core-internal #773; TVF resolution is in #774. Those additions activate only when the corresponding core version ships.

4. run output and deadlines

Observed: nine answers contained intermediate commentary, a killed child exited successfully, and exploration continued until an external timeout with no answer. A later session stayed at reasoning effort high from its last visible reasoning to the 840 s abort, without an answer.
Save only the final model step to --output, preserve the answer through a bare DONE, and write a harness note when no reply exists. Support JSON-mode answer files and one bounded finalization after budget exhaustion. --time-budget / ALTIMATE_RUN_TIME_BUDGET_S sets a soft deadline at 80% and a hard abort at 100%, then allows one finalization generation bounded to 30 seconds; subagent time counts.
At the soft deadline, abort the in-flight model request after any executing tool persists its result, retain emitted text/reasoning, and make the answer-now nudge the next turn without a provider-error retry. Request the provider's lowest reasoning effort for the rest of the run, including subagents and finalization, without changing the configured variant. ALTIMATE_RUN_BUDGET_EFFORT_DOWNGRADE=0 disables the downgrade, but keeps the interrupt (2fe68a47f6); the remaining none vs low question is recorded below. The lowest effort is provider-specific: always-thinking Claude models (Opus 4.7 and later, Fable 5) reject thinking.type: "disabled" with HTTP 400 ("use thinking.type.adaptive and output_config.effort"), which made every budget-exhausted final request fail and lose the best-effort reply; those models now keep adaptive thinking at effort low (direct Anthropic, Vertex and Gateway: thinking: adaptive + effort: low; Bedrock: reasoningConfig adaptive/low with matching raw thinking and output_config.effort fields, stale token budgets dropped), while Claude 4.6 and older keep disabled thinking (5641c87dc9). Live check on Bedrock Opus 5.5 with an 8 second budget: before, the finalizer request failed with the 400 and the run ended in error; after, the lowered-effort request succeeded and the run ended with a final reply.
Exit 0 when finalization writes an answer, with the budget abort reported as a warning; silent finalization, hard failures and Ctrl-C remain non-zero. Signal exits become 128 + signal. Add Unix-ms trace fields generation_interrupted_at / effort_downgraded_at; runs without a time budget are unaffected. Update the help snapshot for --time-budget (f5ea25b9aa).

5. Analyst method and inspectable runs

Observed: prompts conflicted with answer-only requests, and review of full traces exposed population, weighting and interpretation errors.
Require the requested final format, N concrete top-N rows, explicit population/grain/denominator, both readings of ambiguous clauses, and smaller-side cross-engine transfers. Add the built-in data-question skill and read-only data-explorer, expose embedded skills missing from partial installs, and reject reuse of foreign-session permissions. Trace descendant sessions, reasoning, effective prompts and tool schemas, retaining earlier evidence on resume.

6. Search-result permissions

Observed: one session's grep(path=/opt) surfaced another session's traces although read of that directory was denied. This exposed a general isolation hole.
Filter grep/glob/ls results through the read-permission rules: drop denied rows and issue one batched ask prompt for returned rows only. Apply the result cap after filtering; grep stops at 101 permitted results or 10,000 scanned. Tool contexts carry the ruleset and batch forwards it (e987fe76dc). Evaluate worktree-relative paths exactly like read; absolute rules may only tighten the result to deny or ask, never grant access (c95ddd2633).

7. Review follow-ups

Commit 07249b8d47 fixes review-bot findings in the two highest severity tiers, with regression coverage:

  • Keep the data-explorer read-only permission ceiling after agent or global overrides, and bind resumed tasks to the agent that created them.
  • Run PostgreSQL extraction in a pinned READ ONLY transaction and roll back; refuse Mongo $out/$merge anywhere in a pipeline, including nested pipelines. Require approval for attached-catalog writes and refuse unbounded distinct.
  • Send request snapshots on a private bus channel exposed only through a guarded trace subscription, keeping the live trace viewer updating. Redact exported errors before truncation.
  • Abort queued requests at the hard deadline, race fetch hooks against the abort signal, and track idle-stream replay safety at decoded output. Make dash-comment lexing dialect-aware.
  • Keep scratch stores restricted after helper reopen and close them on registry shutdown. Preserve default AWS profile paths and scan stdio chunks once for linear scanning.
  • Use the configured default schema for schema inspection and route warehouse aliases before probing. Make value profiling honour execute permission and workspace routing.

Commits a0d8f29962 and 3c168187fd fix the later review-bot findings in the same tiers:

  • sql_materialize validates the source statement as read-only before the sql_execute ask and before the workspace redirect, so a write statement or Mongo write pipeline against a shadowed warehouse is rejected rather than redirected to the integration tool.
  • The Mongo driver normalises BSON Binary losslessly (base64:<bytes>, subtype 4 as its canonical UUID string) instead of the Binary(<length>) label, so distinct same-length binaries no longer collide in scratch tables; schema inference reports uuid/binary.
  • The final read approval from grep/glob/ls re-applies absolute read rules after the relative and wildcard fallbacks, so an absolute ask rule prompts even with a trailing "*": "allow"; Tool.Context.ask accepts an optional ruleset, honoured by the prompt, session-tools and legacy adapters (only ever built from the caller's own merged ruleset).
  • grep builds candidates from the lexical requested path, so a relative read deny on a symlink alias applies while absolute rules still apply to the canonical target.
  • The time-budget effort downgrade keeps adaptive thinking for always-thinking Claude models on the SAP provider as well (the modelParams branch had still forced disabled).

Commit 41773ae02b fixes the next review-bot round in the same tiers:

  • grep lists candidates first and requests read approval for ask-scoped files before any content is read; a candidate is denied when either its requested alias path or its resolved target is denied. With nothing restricted the search is still one ripgrep run; with denied or unapproved candidates ripgrep is restricted to the approved files in bounded argument batches, so a denied file is neither read nor allowed to consume the scan ceiling.
  • The Mongo driver encodes BSON Binary from raw bytes (value(true)), so bytes at or above 0x80 round-trip through base64 unchanged.
  • sql_check executes PostgreSQL checks with readOnly: true, matching materialization, so a SELECT over a DML user-defined function cannot mutate data.
  • The DuckDB driver tracks a shared-engine generation: after one connector's timeout restarts the helper, every other connector on that engine is rejected once with SESSION_STATE_LOST before executing more SQL (including a peer already queued), then continues.
  • A text part forcibly closed by the soft-budget interruption no longer counts as an answer, and hard-budget exhaustion always enters the bounded finalization once.

Commits c0978ef61f and 7eb075ae92 fix the following round:

  • The analyst and its data-explorer subagent no longer get bash. The bash tool evaluates individual parsed command nodes, so pipes, chaining and redirects (cat /dev/null > model.sql, (cat x)>y, find . -delete) never reached the read-only allow-list; the shell is now denied for both agents, also after global or per-agent configuration grants. Was: ls/cat/head/tail/find/wc/grep/dbt list|ls|debug allowed through bash → now: no shell; structured read, grep, glob and SQL tools remain.
  • Ordinary DuckDB helpers inherit the caller's HOME, USERPROFILE and XDG_* and receive AZURE_CONFIG_DIR and CLOUDSDK_CONFIG (explicit values or the ~/.azure and ~/.config/gcloud defaults), so Azure CLI logins, AWS IAM Identity Center token caches (~/.aws/sso/cache) and gcloud Application Default Credentials work as they did in-process; the private directory stays for TMP and for scratch helpers. The earlier HOME redirect protected nothing for ordinary helpers because Bun script execution does not load the global bunfig and the helper already runs with an explicit --config and --no-env-file (verified on the installed Bun).
  • grep normalises an explicit include: "*" for both the listing and the content pass so they see identical files.
  • DuckDB: every statement a peer queued before a shared-session restart is rejected (not only the first), while the connector whose own timeout caused the restart keeps its queued statements.

Commit 017721b5b1 closes the PostgreSQL read-only class and the pool-acquisition race:

  • Every read path that executes against a PostgreSQL connector passes readOnly: true (value profiling in schema_inspect, parsed sql_execute reads, sql.execute/sql.explain dispatch including EXPLAIN ANALYZE, the connection-test probe, data-diff discovery and diff queries, FinOps query history), matching sql_check and materialization, so a view whose SELECT calls a data-modifying function cannot mutate data under read permission.
  • The outer query_timeout_ms deadline aborts a PostgreSQL acquisition still waiting on the pool; a client admitted after the deadline is released without issuing SQL and cancellation is re-checked before the user SQL, so a statement cannot execute after the caller received a timeout.
  • DuckDB helpers default CLOUDSDK_CONFIG to %APPDATA%\gcloud on Windows.

Lower-severity findings are triaged in the PR for follow-up.

Known limitation. sql_explain with analyze: true now refuses anything the shared read classifier does not mark as a single read-only statement. That classifier still accepts a SELECT that calls a sequence-advancing function such as nextval(...), exactly as sql_execute does for plain reads. On PostgreSQL the read-only transaction rejects it. On engines without one, such as DuckDB, the sequence advances. Closing this belongs in the shared classifier so both tools gain it together.

How did you verify your code works?

Recorded verification by the Engineer runner outside the Codex sandbox; no tests or builds were run for this draft refresh:

  • At 32053eb019, opencode bun test test/cli/help test/altimate test/tool test/session test/provider test/release-validation test/cli/run: 11,471 pass, 669 skip, 1 fail. The sole failure was PostgreSQL Driver E2E, which needs a live Postgres. Drivers: 444 pass, 0 fail. Typecheck clean. This broad run predates the final budget commit.
  • At 2fe68a47f6, bun test test/cli/run test/session test/provider test/altimate/tools: 2,762 pass, 26 skip, 0 fail. Typecheck and git diff --check clean; markers balanced.
  • At HEAD 07249b8d47, opencode bun test test/cli test/altimate test/tool test/session test/provider test/release-validation test/bus test/server test/agent test/e2e-smoke ran outside the sandbox: 12,727 pass, 682 skip, 4 fail. The four failures also fail on main or need a live PostgreSQL (experimental HttpApi, mcp HttpApi, PostgreSQL Driver E2E). The trace-viewer regression was fixed before commit; re-run: 1,993 pass, 0 new failures.
  • At 07249b8d47, drivers: 463 pass, 0 fail. Typecheck and git diff --check clean; markers balanced.
  • Two adversarial reviews, independent engineer review and Sonnet, preceded each commit batch. Residuals: an E2E trace assertion for the new budget fields, an OpenAI-native low-effort request assertion, and resolving none vs low as the lowest effort.

Earlier file-by-file runs of bun test <file> from each package directory: new opencode altimate tests 323 pass, 0 fail across 22 files; new driver tests 57 pass, 3 sandbox-only failures across four files. The table preserves those earlier results; local-engine.test.ts subsequently passed 34/34 outside the sandbox. Neither run is a claim about the entire repository suite.

New test files covered by that earlier run; paths below are relative to packages/<package>/test/:

Package / test filePassFail
opencode / altimate/json-bigint.test.ts20
opencode / altimate/llm-request-tracing.test.ts30
opencode / altimate/schema-inspect-default-schema.test.ts90
opencode / altimate/scratch.test.ts90
opencode / altimate/sql-classify-metadata.test.ts240
opencode / altimate/sql-classify-mongo.test.ts60
opencode / altimate/sql-materialize-bulk.test.ts60
opencode / altimate/sql-materialize-mongo.test.ts140
opencode / altimate/sql-materialize.test.ts450
opencode / altimate/sql-query-deadline.test.ts70
opencode / altimate/tools/schema-inspect-not-found.test.ts20
opencode / altimate/tools/schema-inspect-values.test.ts110
opencode / altimate/tools/sql-check.test.ts580
opencode / altimate/tools/sql-execute-bigint-metadata.test.ts30
opencode / altimate/tools/sql-execute-lint.test.ts110
opencode / altimate/tools/sql-execute-scratch-write.test.ts40
opencode / altimate/tools/sql-execute.test.ts180
opencode / altimate/tools/sql-result-format.test.ts310
opencode / altimate/tools/sql-result-lint.test.ts420
opencode / altimate/tracing-bigint.test.ts70
opencode / altimate/tracing-run-budget.test.ts20
opencode / altimate/tracing-run-content.test.ts90
drivers / duckdb-argv-dir.test.ts10
drivers / local-engine.test.ts313
drivers / mongodb-unit.test.ts60
drivers / query-timeout.test.ts190

Also added under packages/opencode/test/, outside that earlier file-by-file run: agent/analyst-data-explorer.test.ts, cli/cmd/run-output.test.ts, cli/run/budget-finalization.test.ts, cli/run/json-output.test.ts, cli/run/run-tracing.test.ts, cli/run/time-budget.test.ts, e2e-smoke/analyst-smoke.test.ts, skill/builtin-discovery.test.ts.

  • All three earlier driver failures required process enumeration: helper counts/child PID were zero; pgrep reported "Cannot get process list" and ps was denied by the sandbox. The subsequent 34/34 pass outside the sandbox confirms the sandbox-only cause.
  • Earlier existing bun test test/altimate/tools/datamate-list-integrations.test.ts: 1 pass, 2 fail, 2 errors, exit 1. Recorded as a pre-existing failure on main; main was not rerun here.
  • Marker coverage: 9aa62046a2 adds comment-only altimate_change wrappers to run.ts, run-accounting.ts, and termination.ts. The local check falsely passed when upstream/dev was the v2 tree; verification used tag v1.18.34 and a clone without the upstream remote, exercising CI's fallback. The prior v8 count was 324 starts / 324 ends across 19 touched files; current HEAD is confirmed balanced above.
  • Earlier independent adversarial reviews of the v8 diff addressed grep starvation before the cap, a 120-second default regression, and scope creep; their findings were applied before commit.

Screenshots / recordings

N/A.

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

šŸ¤– Generated with Claude Code


[!NOTE]
High Risk
Changes core SQL/Mongo execution paths (process kills, session state loss, PostgreSQL read-only transactions, and result-size limits), which can alter timeout behavior, scratch isolation, and cross-session grep filtering.

Overview
Adds a built-in data-question skill that defines inspect → plan → compute → verify → answer workflows for cross-warehouse SQL, join fan-out checks, metadata-driven unions, batch labeling, and reading sql_execute JSONL spills.

Local database execution moves DuckDB and SQLite into a supervised helper process (LocalEngine) so runaway queries can be killed, query deadlines (shared query-timeout.ts, default 120s) and maxResultBytes caps apply while rows stream, and DuckDB is resolved without loading the native addon in the host (fixing --dir argv collisions). DuckDB gains shared-engine pooling, sandbox replay on reopen, and scratch vs ordinary secret/temp isolation; PostgreSQL adds BEGIN READ ONLY extraction, tighter statement_timeout handling, and streaming byte budgets; MongoDB adds native command normalization, nested $out/$merge blocking, maxTimeMS, and bounded cursor reads.

Ripgrep can filter matches by path and enforce a scan ceiling separate from the result limit. sql_execute docs document optional query_from (generated SQL from a one-row SELECT). Lockfile adds ajv and pins @smithy buffer packages; assistant messages may carry optional metadata for diagnostics.

Reviewed by Cursor Bugbot for commit 5f304e76e24f6a3db97e628e53387d6feb6865ab. Bugbot is set up for automated code reviews on this repo. Configure here.