Skip to content

grafana: one-command local run — from checkout to a rendering dashboard (fixes #421) - #422

Merged
haiyuan-eng-google merged 11 commits into
mainfrom
grafana/one-command-local
Aug 13, 2026
Merged

haiyuan-eng-google merged 11 commits into
mainfrom
grafana/one-command-local

Conversation

@caohy1988

@caohy1988 caohy1988 commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes #421. The Grafana e2e path collapses from seven manual steps (plus two undocumented failure modes) to:

python3 grafana/run_local.py --project MY_PROJECT --dataset MY_DATASET

The script (stdlib-only, macOS/Linux, amd64/arm64) downloads, checksum-verifies, and caches a pinned Grafana, installs the pinned BigQuery datasource plugin (3.3.1, manifest-verified on every rerun), provisions auth, patches a copy of bqaa-dashboard.json with all six constants, creates the prefixed views when bq-agent-sdk is on PATH, launches bound to 127.0.0.1, health-polls, and prints the dashboard URL. --stop tears it down with strong process-identity verification. Everything generated lives in gitignored grafana/.local/; committed sources are never mutated.

Hardening (both review rounds)

  • Loopback-only (GF_SERVER_HTTP_ADDR=127.0.0.1, env pinned by test) — never a wildcard listener with admin/admin.
  • Credential files: datasource YAML written atomically at 0600 in a 0700 dir (JWT path carries a private key).
  • No hard-coded location: processingLocation omitted (plugin auto-selects); validated --processing-location override.
  • Cost guard preserved: MaxBytesBilled: 100000000 default from datasource.example.yaml, validated override, both auth shapes.
  • Safe extraction on every interpreter: stdlib data filter where available; on pre-3.10.12/3.11.4 the fallback validates every member (no traversal, no absolute paths, no links/special files) and fails loudly — regression-tested with malicious archives.
  • --stop cannot kill an unrelated process: exact-executable + --homepath argument + recorded process start time (defeats PID reuse); a live test proves a lookalike process whose argv mentions the home path is never signalled.
  • Atomic launch ownership: an exclusive flock on the workdir is taken before the liveness check and held through pidfile publication — concurrent launches yield exactly one owner (two-contender regression), a second launch is refused with the pid/port/stop command while an instance lives, and --stop takes the same lock so it cannot race a launch in flight.
  • Cache integrity: cached plugin manifests are checked against the pin (mismatch/corrupt → reinstall); extractions record archive-hash provenance, and an explicit --grafana-sha256 is always honored — mismatched caches are discarded and fail closed.
  • Downloads verified against the published .sha256; one-sided --time-from/--time-to rejected; identifiers/prices validated before any write; the patcher refuses non-constant variables (the dashboard's injection-safety contract, enforced in code).

Verification

  • Live e2e of the script against a 100,023-event table: checksum-verified extract → loopback-only listener (netstat) → datasource health OK → jsonData carries the cost cap and no pinned location → live query under the cap returned 100,023 → --stop clean.
  • Tests: 69 in the runner suite, 95 combined with the dashboard suite — no network, including malicious-archive, lookalike-process, recycled-pid, cached-manifest, and cached-extraction-vs-explicit-hash regressions.

Files

  • grafana/run_local.py — the launcher
  • tests/test_grafana_local_runner.py — 69 tests
  • grafana/README.md — Quick-start + known pitfalls
  • .gitignore — grafana/.local/
python3 grafana/run_local.py --project P --dataset D replaces the
seven-step manual chain: downloads a pinned Grafana (12.3.0, satisfying
the plugin's >=12.2.5 floor), installs the BigQuery datasource plugin,
provisions auth (ADC by default, --sa-key for the documented JWT path
with a real block-scalar private key), writes a patched copy of
bqaa-dashboard.json with all six constants filled, creates adk_* views
when bq-agent-sdk is on PATH, and launches with the plugin preinstaller
disabled (a failed preinstall breaks all plugin loading with an opaque
react/jsx-runtime 404). --stop tears it down; grafana/.local/ is
disposable and gitignored; committed sources are never mutated.

Safety: identifiers validated with the repository's identifier rules,
prices restricted to plain decimals (they are interpolated into panel
arithmetic), and the patcher refuses non-constant variables so the
dashboard's constants-stay-constants contract is enforced in code.

Verified end to end against a live 100,023-event table: provisioning,
views, plugin install, health, and a datasource query all green; --stop
kills cleanly. Tests cover validation, patching, provisioning shapes,
the platform matrix, the version-floor pin, and a no-network
--provision-only run: 40 passed.
@caohy1988

Copy link
Copy Markdown
Collaborator Author

Independent review at 34b8513 — one real finding, two suggestions

Verified locally in a detached worktree: 40/40 new tests pass, bq-agent-sdk is a real entry point with views create-all and the exact flags used (cli.py:1816), the identifier rules match the repo's source of truth, the README's version-floor note matches the plugin's published grafanaDependency (checked against the Grafana catalog API), the pinned Grafana 12.3.0 tarball exists on dl.grafana.com, sources are never mutated, and all required CI checks are green. The patcher's constants-only enforcement and the strict price regex are exactly right.

Finding: --view-prefix is accepted and patched, but never forwarded to view creation

main() collects and validates --view-prefix and writes it into the dashboard constants, but maybe_create_views(project, dataset, table) (run_local.py:278) doesn't take it, and the bq-agent-sdk views create-all invocation omits --prefix — even though the CLI supports it (cli.py:1825, default adk_). So with a non-default prefix the dashboard constants point at foo_* views while the CLI creates adk_* views, and every panel shows "No data" — the exact confusion this script exists to eliminate. The default path is unaffected (which is why the live e2e passed), and no test covers the non-default path. Fix is small: pass the prefix into maybe_create_views and add --prefix to the command, plus one test asserting the rendered command includes it.

Suggestion (non-blocking): verify the pinned tarball's checksum

The download at run_local.py:239 trusts HTTPS alone. Grafana publishes SHA256 sidecars at the same path pattern — I confirmed grafana-12.3.0.darwin-arm64.tar.gz.sha256 returns a live checksum. Verifying it (pinned per dist, or fetched and checked at download time) would make the "pinned" claim end-to-end and matches the supply-chain posture of #411/#413. The filter="data" extraction and .partial-rename pattern are already the right shape.

Nits

  • stop() SIGTERMs whatever PID is in the pidfile; if Grafana died and the PID was recycled, --stop could hit an unrelated process. A /proc-style or ps check that the command line contains the grafana homepath would close it.
  • tarfile.extractall(filter=...) requires Python ≥3.12 or the backported patches (3.10.12+/3.11.4+); CI runners are fine, but a stock older 3.10/3.11 patch release would TypeError. One line in the docstring would do.

None of this blocks the default-path value, which is real: seven steps to one command, with the two #421 failure modes handled in code rather than prose.

@caohy1988

Copy link
Copy Markdown
Collaborator Author

Fresh review at 34b8513 — changes requested

The default US/ADC path is real and healthy, but this is not ready to merge. I found five merge blockers beyond the green happy path.

P1 — local Grafana is exposed on every network interface

run_local.py:425-445 sets the port but not GF_SERVER_HTTP_ADDR. Grafana documents that an empty http_addr is equivalent to 0.0.0.0. The live validation instance confirmed the result: it listens on *:3005, and the documented admin/admin credentials currently have administrator access to the ADC-backed datasource.

Fix: set GF_SERVER_HTTP_ADDR=127.0.0.1, use 127.0.0.1 for health/dashboard URLs, and pin that environment value in a test.

Reference: https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/#http_addr

P1 — --sa-key copies the private key into a world-readable file

run_local.py:381-390 creates ordinary directories and writes the credential-bearing YAML with Path.write_text(). Under the normal 022 umask, I reproduced bigquery.yaml as mode 0644 inside a 0755 work directory. Any other local account can read the copied service-account private key.

Fix: create the credential directory as 0700 and write/replace the datasource file atomically as 0600; add a permissions assertion for the JWT provisioning test.

P1 — custom view prefixes create the wrong views

The earlier review finding is correct. maybe_create_views() never accepts or forwards the validated prefix, while main() calls it with only project/dataset/table. I captured the generated command: it contains no --prefix. --view-prefix custom_ therefore makes the dashboard query custom_* while the CLI creates adk_*.

Fix: pass the prefix through to bq-agent-sdk views create-all --prefix <value> and test the exact command.

P1 — non-US datasets fail

Both datasource render paths hard-code processingLocation: US. The live fixture is itself in US, so the successful E2E run cannot detect this. BigQuery rejects an explicitly mismatched job location; the Grafana plugin supports leaving the field empty for automatic selection.

Fix: omit the setting by default, or add a validated --processing-location override. Cover default automatic selection plus an explicit EU/regional value.

References: https://grafana.com/docs/plugins/grafana-bigquery-datasource/latest/configure/ and https://docs.cloud.google.com/bigquery/docs/locations

P1 — the generated datasource drops the repository cost guard

grafana/datasource.example.yaml sets MaxBytesBilled: 100000000; render_datasource_yaml() omits it. The live API confirms that the generated datasource has no cap. That is especially risky with broad developer ADC credentials: a panel or edited query can incur an unexpectedly large scan.

Fix: preserve the existing 100 MB default, allow an explicit numeric override, and test both ADC and JWT shapes. Grafana documents MaxBytesBilled specifically as the per-query cost guard.

Reference: https://grafana.com/docs/plugins/grafana-bigquery-datasource/latest/configure/

P2 — close these small lifecycle and reproducibility gaps in the same PR

  • Pin plugin version 3.3.1. install_plugin() installs latest while the Grafana compatibility test assumes the current 3.3.1 dependency floor. The catalog currently returns 3.3.1, so this works today but can silently reintroduce the exact version-floor failure [Grafana] One-command local run: seven manual steps and two undocumented failure modes between a user and their first dashboard #421 is meant to eliminate. Grafana CLI supports plugins install <id> <version>.
  • Reject one-sided --time-from / --time-to. Passing only one currently exits successfully and silently retains the original dashboard range.
  • Verify the downloaded Grafana archive against SHA256 before extraction/execution.
  • Make --stop verify that the PID belongs to this Grafana homepath, wait for termination, and print the correct stop command when a custom work directory is used.
  • Document or handle the minimum Python patch release required for tarfile.extractall(filter="data") under the repository-wide Python >=3.10 claim.

What passed

  • 66/66 claimed local tests passed in an isolated detached worktree.
  • All required GitHub checks are green across Python 3.10–3.14.
  • Live Grafana 12.3.0, plugin 3.3.1, datasource health, and dashboard provisioning passed.
  • git diff --check and py_compile passed.
  • Identifier/price validation, constants-only dashboard patching, shell argument handling, and committed-source immutability are sound.

Scope verdict: requirements missing. Keep #421 open until the five P1s are fixed and reverified; green CI currently proves only the US/default-prefix happy path.

@caohy1988

Copy link
Copy Markdown
Collaborator Author

Independent spot-check of the changes-requested review — all five P1s reproduce from code

I re-verified each blocker against the worktree rather than taking the review at face value:

  1. Bind address — confirmed: the launch env (run_local.py:425-435) sets no GF_SERVER_HTTP_ADDR, and Grafana's documented default binds all interfaces. With admin/admin on a fresh instance this is a genuine exposure for a tool whose whole point is running casually on a laptop.
  2. Credential file permissions — confirmed: write_text into mkdir-default directories yields 0644/0755 under a normal umask; the JWT path copies a private key into that file.
  3. View prefix — this was my earlier finding; the command capture matches what I traced (maybe_create_views never receives the prefix; views create-all supports --prefix at cli.py:1825).
  4. processingLocation: US hard-coded — confirmed in both render paths; the live fixture being in US means the green e2e cannot see this.
  5. MaxBytesBilled dropped — confirmed, and it's worse than a simple omission: grafana/datasource.example.yaml:35-37 sets MaxBytesBilled: 100000000 and explicitly warns that a wrong spelling silently drops the cap — so the repo already treats silent cap loss as a known hazard, and the generated datasource ships without the cap at all.

The P2 list is also accurate from code: install_plugin passes no version (verified at run_local.py:258-275), one-sided --time-from/--time-to is silently ignored by the if time_from and time_to guard, and the pidfile/tarfile points match my earlier nits.

For the record: my earlier review caught the prefix bug and the checksum gap but missed the bind-address and file-permission exposures — this round's review is the more complete one, and I concur with "not ready to merge" until the five P1s land and are reverified.

haiyuan-eng-google and others added 3 commits August 12, 2026 22:42
…in, keep cost cap

All five P1s from review, each verified live after fixing:

- GF_SERVER_HTTP_ADDR=127.0.0.1 (empty http_addr binds every interface);
  netstat now shows 127.0.0.1-only LISTEN; env pinned by a test.
- Credential-bearing datasource YAML written atomically as 0600 inside a
  0700 directory (JWT path copies a private key); permissions asserted.
- --view-prefix forwarded to bq-agent-sdk views create-all --prefix; the
  exact command is built by a pure function and tested.
- processingLocation omitted by default (plugin auto-selects the job
  location; hard-coded US broke every non-US dataset), with a validated
  --processing-location override.
- MaxBytesBilled preserved from datasource.example.yaml (100 MB default,
  validated --max-bytes-billed override) in both ADC and JWT shapes,
  placed under jsonData before the secure block.

P2s: plugin pinned to 3.3.1 (installing latest could silently raise the
floor #421 exists to eliminate); one-sided --time-from/--time-to rejected;
downloads verified against the published .sha256 (plus --grafana-sha256
for independently pinned hashes on local archives); --stop verifies the
pid still belongs to this homepath, waits for exit, and the printed stop
hint includes a custom --workdir; tarfile data filter feature-detected
for pre-3.10.12 interpreters.

Live reverification: launch on :3007 with checksum verification, netstat
loopback-only, datasource health OK, jsonData carries the 100 MB cap and
no location, live query under the cap returned 100023, --stop clean.
Tests: 57 in the runner suite, 83 with the dashboard suite.
@caohy1988

Copy link
Copy Markdown
Collaborator Author

All five P1s and every P2 are fixed at the new head (541b77b, merged with the branch's main sync) — and each P1 was re-verified live after fixing, not just unit-tested:

P1s

  1. Loopback bind — launch_env() (now a pure, test-pinned function) sets GF_SERVER_HTTP_ADDR=127.0.0.1; health/dashboard URLs use 127.0.0.1. Live: netstat shows 127.0.0.1.3007 LISTEN only — no wildcard listener.
  2. Key-file permissions — write_private() writes the datasource YAML atomically at 0600 inside a 0700 directory (both asserted in test_jwt_provisioning_file_is_private, including no leftover temp file).
  3. View prefix forwarded — build_views_command() includes --prefix <validated value> (flag name verified against bq-agent-sdk views create-all --help); the exact argv is tested.
  4. No hard-coded US — processingLocation omitted by default (plugin auto-selects), validated --processing-location override; tested for omit/EU/invalid. Live datasource jsonData confirms no location field.
  5. Cost guard preserved — MaxBytesBilled: 100000000 default (matching datasource.example.yaml, spelling and all), validated --max-bytes-billed override, present in both ADC and JWT shapes and placed under jsonData before the secure block. Live datasource jsonData shows the cap; a query ran under it and returned 100023.

P2s

Plugin pinned to 3.3.1 (install argv tested — latest-install could silently raise the floor #421 eliminates); one-sided --time-from/--time-to now a parser error (tested via subprocess); downloads verified against the published .sha256 with --grafana-sha256 for independently pinned hashes on local archives (verify helper unit-tested, and the live rerun verified the cached tarball against the published hash); --stop verifies the pid's command line still contains this launcher's homepath before signaling, waits up to 15 s, and the printed stop hint includes a custom --workdir; the tarfile data filter is feature-detected for pre-3.10.12/3.11.4 interpreters.

Reverification

Full live rerun on :3007: checksum-verified extract → loopback-only listener → datasource health OK → capped, auto-location query returned 100,023 → --stop exited clean (and refuses stale pids). README quick-start updated for the loopback bind, cost cap, location behavior, and key-file permissions. Tests: 57 in the runner suite (17 new this round), 83 with the dashboard suite.

@caohy1988

Copy link
Copy Markdown
Collaborator Author

Re-review at f22b84a — all five P1s and the P2 list verified fixed; LGTM

I verified each fix in the code, not from the commit message, and ran the suite locally:

P1s:

  1. Bind address — GF_SERVER_HTTP_ADDR="127.0.0.1" is in the launch env (line 273). Loopback only.
  2. Credential permissions — write_private (240-256) tightens the parent to 0700 before creating the file, opens with 0600, and uses os.replace for the atomic rename with tmp cleanup on failure. The ordering closes the list/read window correctly.
  3. View prefix — forwarded as --prefix to views create-all (line 293), so non-default prefixes now create the views the dashboard actually queries.
  4. Processing location — omitted by default so the plugin auto-selects (185-204); both ADC and JWT render paths handle it identically. Non-US datasets work now.
  5. Cost guard — MaxBytesBilled is rendered in both auth paths from DEFAULT_MAX_BYTES_BILLED = "100000000" (matching datasource.example.yaml), validated through require_max_bytes, with a flag override.

P2s: plugin pinned to 3.3.1 (line 63) so the version-floor test can't drift; downloads verify against the published .sha256 sidecar with --grafana-sha256 for an independently pinned hash; one-sided --time-from/--time-to now fails argument validation (537-538).

Tests: 57/57 pass locally (17 new covering the fixes, including the permissions and prefix paths). CI: all required checks green at this head.

The respin addresses everything from the changes-requested round. Ready to merge from this side.

…che-pin integrity

Both P1 reproductions from review closed, plus the two cache paths:

- Pre-3.10.12 fallback extraction validates every member (regular
  files/dirs only, no absolute paths, no traversal, no links) and fails
  loudly instead of falling back to unrestricted extractall; regression
  tests cover ../ traversal, absolute paths, symlinks, and a benign
  archive through the fallback path itself.
- --stop verifies a strong launch identity: the command must start with
  the exact recorded grafana executable AND carry the --homepath
  argument AND the process start time must equal the one recorded at
  launch (defeats pid reuse). A live end-to-end test proves an
  unrelated process whose argv merely mentions the home path is never
  signalled; identity matching is pure and covered for lookalike,
  recycled-pid, and prefix-spoofed cases.
- Cached plugin manifests are checked against the 3.3.1 pin; mismatched
  or corrupt manifests reinstall instead of silently bypassing the pin.
- Extractions record archive-hash provenance; an explicitly supplied
  --grafana-sha256 is always honored — a cached home with different
  provenance is discarded and the archive re-verified (fails closed on
  mismatch), covered end to end with tiny synthetic archives.
@caohy1988

Copy link
Copy Markdown
Collaborator Author

Round-3 review at 4542f4b — all four round-2 findings verified fixed, adversarial repros re-run

This time I re-ran the attacks, not just the reading:

  1. Tar traversal — closed and probed. _validated_members rejects non-file/dir members, absolute paths (including drive-letter), and resolved-path escapes; I built the round-2 malicious archive (../escaped.txt) and ran it through _extract_without_filter — it dies with refusing to extract '../escaped.txt': it escapes the destination. Modern interpreters additionally get filter="data" with the pre-validated member list. No unrestricted extractall remains on any supported interpreter.
  2. Stop-guard — closed and probed. The pidfile now records {pid, home, exe, start} and _identity_matches requires the exact executable, the --homepath <home> argument, and the process start time. My probes: an unrelated process merely carrying the home path in argv → no match (the round-2 attack); the real launch command → match; the same command under a recycled PID with a different start time → no match. Fails safe when the launch-time probe yields no start marker.
  3. Plugin pin — enforced across reruns. plugin_needs_install parses the cached manifest and reinstalls on version mismatch or corruption before trusting the cache.
  4. Checksum provenance — honored. A cached extraction is reused only when no explicit hash is supplied or the recorded .provenance.json matches it; disagreement triggers a rebuild. Explicit --grafana-sha256 can no longer be silently ignored.

Suite: 65/65 locally (8 new over the respin, covering exactly these paths); CI all green at this head.

From my side this closes the review loop — merge-ready.

@caohy1988

Copy link
Copy Markdown
Collaborator Author

Full fresh review at 4542f4b — one P1 remains

I reviewed the complete PR again from a clean clone, verified all four findings from the prior round, ran the full suite, inspected the official pinned archives, and exercised the launcher with a real Grafana 12.3.0 process. The prior four findings are closed, but one untested lifecycle blocker remains.

P1 — a second launch in the same workdir orphans the first Grafana process

run_local.py:735-743 writes the workdir's single grafana.pid unconditionally after every launch. It does not check whether the existing pidfile still identifies a live Grafana instance.

I reproduced this end to end with the actual pinned Grafana and the installed BigQuery plugin:

  1. Launch port 39987 with one workdir.
  2. Launch port 39988 with the same workdir.
  3. Both dashboard processes remain healthy.
  4. The second launch overwrites grafana.pid with its own identity.
  5. --stop stops only port 39988 and deletes the pidfile.
  6. Port 39987 remains healthy and running, but there is no launcher record left to stop it.

That leaves an admin/admin local instance backed by the operator's credentials alive after the documented teardown command reports success.

Fix: before provisioning or launching, read any existing pidfile and apply the strong identity matcher. If it points to a live launcher-owned Grafana, refuse the second launch and print the existing PID plus the --stop instruction. If it is stale, remove it and continue. Add an end-to-end regression proving a second launch cannot overwrite a live record.

Confidence: 10/10 — reproduced with real Grafana 12.3.0 and both health endpoints.

Prior findings verified fixed

  • Legacy-Python tar extraction validates the complete member list before writing; traversal, absolute paths, links, and special files fail closed.
  • The lookalike-process repro survives --stop; a real Grafana identity matches and stops cleanly.
  • Cached plugin manifests must match version 3.3.1; mismatch/corruption triggers reinstall.
  • Explicit archive hashes are honored through extraction provenance and mismatches fail closed.

Fresh verification

  • Runner suite: 65 passed.
  • Combined dashboard suite: 91 passed, zero warnings.
  • Official Grafana 12.3.0 Linux amd64 and macOS arm64 archives are compatible with the stricter extractor; checksums match their published sidecars.
  • Full macOS run: verified extraction, plugin 3.3.1 installation, loopback-only listener, health check, and clean teardown.
  • All required CI checks are green.
  • Branch is current with main; head remained 4542f4b throughout review.
  • No Greptile comments and no committed dashboard/query-source mutation.
  • PR body correctly reports 65/91 tests.

Verdict: changes requested. Close the duplicate-launch lifecycle hole and pin the regression; everything else from both previous review rounds is settled.

The workdir holds one grafana.pid; a second launch overwrote it and
orphaned the first instance - --stop then tore down only the newer
process and reported success while an admin/admin Grafana kept running
with no record left to stop it (review repro at 4542f4b).

live_instance() now runs before any provisioning or launch: the pidfile
is checked with the same strong identity matcher --stop uses; a live
launcher-owned instance refuses the run with its pid, port, and the
exact stop command; a stale record is removed and the run proceeds.
The pidfile also records the port for that message.

Regressions: a live identity-matching fake (bash exec'd by literal
path, compound command so it cannot exec-optimize away) proves a second
run exits 1, leaves the record and process untouched, and writes
nothing; a stale record is cleared and the run proceeds. Verified live
with real Grafana 12.3.0: second launch refused with the first instance
healthy, then --stop clean.
@caohy1988

Copy link
Copy Markdown
Collaborator Author

The duplicate-launch P1 is closed at fea1726, and your exact repro was re-run against real Grafana 12.3.0 after the fix:

  • Guard before any work: live_instance() runs before provisioning or launch and applies the same strong identity matcher --stop uses. A live launcher-owned instance refuses the run with exit 1, printing the pid, the port (now recorded in the pidfile), and the exact --stop command — including --workdir when custom. A stale record is removed and the run proceeds.
  • Live reverification (your steps 1–6, post-fix): first launch on :3007 healthy → second launch same workdir on :3008 refused (a launcher-owned grafana is already running from this workdir (pid 99130, port 3007); stop it first with: python3 run_local.py --stop) → first instance still healthy → --stop stops it cleanly and removes the pidfile. No orphan possible: the record can no longer be overwritten while its process lives.
  • Regressions pinned without real Grafana: a live identity-matching fake (bash exec'd by its literal path with a compound command so it can't exec-optimize itself away — a fun rabbit hole: bash -c "sleep 30" replaces itself with sleep and breaks the exact-exe identity) proves a second run exits 1, leaves the pidfile and process untouched, and writes nothing; a stale record is cleared and the run proceeds with the pidfile removed.

Tests: 67 runner / 93 combined, all passing. Everything from all three review rounds is now closed; awaiting maintainer review.

@caohy1988

Copy link
Copy Markdown
Collaborator Author

Heads-up: CI is red at fea1726 on all five Linux jobs (macOS-green)

The new test_second_launch_refused_while_instance_lives fails identically on every Test matrix job (3.10–3.14):

assert result.returncode == 1   # got 0 — the second launch proceeded to
                                # "provisioning written under …" instead of refusing

So on Linux, live_instance() declined to match the fake live instance and removed the pidfile. The same suite passes 67/67 on macOS locally, so this is a platform split in the identity path, almost certainly inside _probe_process / _identity_matches rather than the guard's placement. Prime suspects, in order:

  1. The fixed 24-char slice of ps -p <pid> -o lstart= -o command= output. The parsing assumes lstart is exactly 24 columns; that's true for both macOS ps and procps-ng most of the time, but procps-ng column-padding behavior when headers are suppressed has version quirks — if lstart comes out narrower/wider on the runner's procps version, both start and command are garbage and every identity check fails. Splitting on the year or matching the ctime shape with a regex would be robust.
  2. ps -o command= content for the /bin/bash -c … victim on Linux — if procps renders the argv differently than expected (e.g., without the leading /bin/bash prefix form the matcher requires), command.startswith(expected_exe + " ") fails.

I can't reproduce locally (no Linux box here; Docker daemon is down), but a docker run --rm -v $PWD:/src -w /src python:3.12 pytest tests/test_grafana_local_runner.py -k second_launch -x on any machine with a live daemon should show it in seconds, and printing the probe tuple on mismatch in the test would make the diff obvious.

Everything else from the round-3 review stands — the failure is confined to the new duplicate-launch test on Linux.

@caohy1988

Copy link
Copy Markdown
Collaborator Author

Full fresh review at fea1726 — changes requested

I reviewed the complete PR again from a clean clone, rechecked the earlier fixes, ran the full local suite, inspected the required GitHub checks, and exercised both sequential and concurrent launch behavior. The sequential duplicate-launch guard works on macOS, but two merge blockers remain.

P1 — concurrent launches can still orphan the first Grafana process

main() checks live_instance() once, then performs provisioning, view creation, download/plugin work, and launch before writing grafana.pid. That is a check-then-act race: two launchers can both observe no pidfile before either owns the workdir.

I reproduced the actual lifecycle failure with two launcher processes, two real child processes, and live HTTP health endpoints:

  • launcher exits: [0, 0]
  • ports 39987 and 39988: both healthy
  • listener PIDs: two distinct live processes
  • grafana.pid: records only port 39988
  • port 39987 process: live but orphaned from the launcher record

So the sequential six-step repro is closed, but the same admin/admin credential-backed orphan is still possible when starts overlap.

Fix: claim launch ownership atomically for the workdir (for example, an exclusive lock compatible with supported macOS/Linux), recheck live_instance() while holding it, and retain ownership through process launch plus pidfile publication. Add a regression that starts two independent contenders together and proves exactly one may launch.

Confidence: 10/10 — reproduced end to end with two OS processes and both health endpoints.

P1 — every required Python CI job is red

Python 3.10–3.14 all fail test_second_launch_refused_while_instance_lives: expected exit 1, received 0. The fake records /bin/bash as its executable, but Ubuntu reports a different canonical command prefix, so the child invocation treats the record as stale, deletes it, provisions files, and exits successfully.

Fix the helper to derive the recorded executable from the command prefix returned by _probe_process (or use a platform-stable fake), then restore all required checks. The application code's real-Grafana identity path is not disproved by this test failure, but the claimed portable regression currently does not test it on Linux.

Failing CI run

Confidence: 10/10 — the identical failure is present in every supported Python matrix job.

P2 — verification text is stale

The PR body still reports 65 runner / 91 combined and names tests/test_grafana_local_runner.py as 65 tests. The current claimed and locally verified totals are 67 runner / 93 combined. Refresh the body after the blockers are fixed and the final suite passes.

What passed

Verdict: do not merge #422 yet; keep #421 open. Make workdir launch ownership atomic, pin the concurrent regression, repair the Linux test, restore green required CI, and refresh the test counts.

@caohy1988

Copy link
Copy Markdown
Collaborator Author

Independent confirmation of the round-4 findings

The concurrent-launch race is real by construction — verified from the code layout: live_instance() is consulted once at line 667, and the pidfile is not published until line 772, with view creation (751), the Grafana download/extract (758), plugin install, and the actual Popen (764) all inside the window. Two launchers starting within a few seconds of each other both observe "no pidfile." No lock exists anywhere in the launch path. Your two-process repro matches exactly what the code permits. An atomic workdir claim (lockfile held from before the check through pidfile publication) is the right shape for the fix.

The Linux CI failure diagnosis converges with mine. I reported the same red matrix last cycle and pointed at the ps-rendering side; your narrowing to the recorded-exe prefix mismatch on Ubuntu is consistent — the helper records /bin/bash while the platform's canonical command prefix differs, so the child treats the record as stale, deletes it, and proceeds (exit 0, "provisioning written"). Deriving the fake's recorded exe from _probe_process's own output makes the test platform-stable.

Nothing to add on the P2 (body test counts) — agreed it should be refreshed with the final numbers after the blockers close.

…y fake

- The live_instance() check alone was check-then-act: two overlapping
  launches could both observe no pidfile and the loser's overwrite
  orphaned the winner's Grafana (review repro at fea1726). An exclusive
  non-blocking flock on workdir/launch.lock is now taken BEFORE the
  liveness check and held through process launch and pidfile
  publication; a losing contender exits 1 with a clear message, and
  --stop takes the same lock so it cannot race a launch in flight.
  Regressions: same-process lock exclusivity, and two real contender
  processes with a deterministic test-only hold proving exactly one
  owner ([0, 1] exit codes, loser told a launch is in progress,
  provisioning written exactly once).
- The Linux CI failure: the identity fake recorded /bin/bash while
  Ubuntu's ps reports a different canonical prefix, so the guard treated
  the record as stale and CI's regression exited 0. The fake now records
  the executable exactly as ps reports it (probe-derived), making the
  regression platform-stable; the real-Grafana path was unaffected.

Live reverification with real Grafana 12.3.0: launch, duplicate refusal
with pid/port/stop-hint, first instance healthy throughout, clean stop.
Tests: 69 runner / 95 combined.
@caohy1988

Copy link
Copy Markdown
Collaborator Author

Both P1s closed at 547287a, plus the stale counts:

  1. Concurrent-launch race — ownership is now atomic: an exclusive non-blocking flock on workdir/launch.lock is acquired before the live_instance() check and held through process launch and pidfile publication, so the check-then-act window is gone. A losing contender exits 1 with "another launch is already in progress…"; --stop takes the same lock so it cannot race a launch mid-flight. Regressions: same-process lock exclusivity, and two real contender processes (with a clearly-marked test-only hold that widens the critical section deterministically) proving exit codes [0, 1], the loser's message, and provisioning written exactly once. Live rerun with real Grafana 12.3.0 after the change: launch → duplicate refused with pid/port/stop-hint → first instance healthy throughout → clean stop.
  2. Red Linux CI — root cause confirmed as diagnosed: the fake recorded /bin/bash while Ubuntu's ps reports a different canonical prefix, so the guard correctly treated the record as stale and the regression tested nothing on Linux. The fake now records the executable exactly as _probe_process reports it, making the regression platform-stable by construction rather than by per-OS path guesses. (The real-Grafana identity path was never affected — the binary is exec'd by its literal path.)
  3. PR body refreshed — 69 runner / 95 combined, and the hardening list now includes the atomic-ownership property.

All required checks should go green on this head; local combined suite is 95 passed with zero warnings.

@caohy1988

Copy link
Copy Markdown
Collaborator Author

CI still red at 547287a — same test, same signature; the exe fix wasn't the (whole) cause

All five matrix jobs fail test_second_launch_refused_while_instance_lives identically again: expected exit 1, got exit 0 with "provisioning written" — live_instance() still declines the fake record on Linux and treats it as stale.

Since two blind attempts at the platform difference haven't cured it, the next iteration needs observability rather than another guess. Cheapest instrument: in the test, after the refusal assertion fails, re-probe the victim and dump _probe_process(victim.pid) plus the pidfile record — one CI run will show which of the three identity fields (exe prefix, --homepath argument, start string) diverges on procps-ng. Or run the whole test in a Linux container locally first (docker run --rm -v "$PWD":/src -w /src python:3.12 bash -c "pip install -e . && pytest tests/test_grafana_local_runner.py -k second_launch -x") and iterate there before pushing.

One structural suggestion worth considering while in there: _identity_matches could compare the parsed start time (parsed to epoch) rather than the exact string, and match the exe by basename-or-abspath — that removes the two most locale/platform-sensitive comparisons entirely, at a small cost in strictness (start-second equality plus homepath match is still a strong identity for this threat model).

Not posting guesses as findings this time — the code on macOS is verified correct by probes, and the Linux divergence needs direct observation.

… stale

The CI diagnostic showed procps cutting the probed command at ~80
columns ('--homepath /'), so the --homepath containment check failed
and the guard treated a live record as stale. This was a real Linux
bug, not only a test artifact: a genuine grafana under a long workdir
path would have been mis-judged the same way by --stop and the
duplicate-launch guard. -ww requests unlimited width on both procps
and BSD ps.
@caohy1988

Copy link
Copy Markdown
Collaborator Author

Both P1s are now closed with all required checks green at c7f9076 (Python 3.10–3.14 all passing, zero failing checks).

The Linux investigation deserves an honest correction and a credit: the red matrix was not merely the test fake's identity, as I first fixed. A CI diagnostic dump showed Ubuntu's ps truncating the probed command at ~80 columns — the output literally ended at --homepath / — so the --homepath <home> containment check failed and the guard correctly treated a live record as stale. That was a real Linux production bug: a genuine Grafana under any long workdir path would have been mis-judged as stale by both --stop and the duplicate-launch guard. My earlier statement that "the real-Grafana identity path was never affected" was wrong for Linux, and your requirement that the regression actually pass on Linux is what surfaced it. Fix: ps -ww (unlimited width; procps and BSD ps both support it), with a comment explaining why the flag is load-bearing.

Recap of the round at this head:

  1. Concurrency race — exclusive flock on workdir/launch.lock taken before the liveness check and held through pidfile publication; --stop takes the same lock. Two-contender regression asserts exit codes [0, 1], the loser's message, and single-write provisioning; lock exclusivity unit-tested; live real-Grafana sequence re-verified.
  2. Linux CI — probe-derived fake identity and the ps -ww production fix; matrix green on all five interpreters.
  3. Counts — PR body reports 69 runner / 95 combined, current and verified.

Awaiting maintainer review.

@caohy1988

Copy link
Copy Markdown
Collaborator Author

CI green at 6919c6c — with an important caveat

All required checks pass at this head, and #424 is merged (verified byte-identical to the reviewed head, 29cec7e).

The caveat: 6919c6c changed only test diagnostics — no functional change to the identity path — yet the previously all-red matrix is now green. Two consecutive red runs followed by green on a diagnostics-only commit means the Linux failure was timing-dependent, not a deterministic platform divergence. The most plausible window is the setup probe racing the victim process's own startup (Popen → bash exec → argv visibility to ps), where the recorded identity and the launch-time probe disagree only under runner load.

That has two consequences:

  1. The guard code itself is fine — my direct probes of live_instance, _identity_matches, and the flock all behaved correctly, and the two red runs never showed a real Grafana being mismatched.
  2. The test may flake again. If it does, the new assertion context will now name the diverging field on the first failed run — which is exactly the right position to be in. If it recurs more than rarely, the structural fix (compare parsed start time, not the string) is still worth taking.

From my side: #422 is merge-ready when the maintainers are comfortable with the flake posture.

@haiyuan-eng-google
haiyuan-eng-google merged commit b979f83 into main Aug 13, 2026
16 checks passed
@caohy1988

Copy link
Copy Markdown
Collaborator Author

Root cause confirmed: ps -ww at e96d512 — and it retroactively explains the "flake"

CI is green at this head, and c7f9076 is the real fix: without -ww, Linux ps truncates the command column, and on the runner the long pytest tmp path pushed --homepath <home> past the cut — so _identity_matches never saw the homepath argument and every live record read as stale. Suite 69/69 locally; -ww verified harmless on BSD ps (macOS probe returns the full command).

One correction to my earlier caveat: I attributed the green run at 6919c6c to a timing flake. The truncation explanation is better and subsumes it — whether --homepath survives an ~80-column cut depends on the tmp-path length, which shifts with pytest's run numbering (pytest-0, pytest-1, …). Red, red, green across three runs with no functional change is exactly what path-length-dependent truncation produces. No residual flake hypothesis needed.

With this, every finding from all four rounds is closed with its root cause identified, and the matrix is green at the same head. Merge-ready from my side.

haiyuan-eng-google pushed a commit that referenced this pull request Aug 30, 2026
…configurator (#450)

* chore(release): 0.5.1 — evalbench reader, canonical rubrics, single-input configurator

Version bump 0.5.0 -> 0.5.1 and the changelog cut for everything merged
since v0.5.0 (2026-08-11). In the wheel: the EvalBench BigQuery run
reader (#444), canonical evaluation rubrics in core (#431), and the CLI
judge-feedback escaping fix (#438). Repo/live-template side: the
single fully-qualified table-ID configurator entrance (#449), Console
table-link paste (#424), the attested external-access contract with its
staleness workflow (#446), the end-user manual (#425), Grafana metric
and scan-bound fixes (#433) with the one-command local run (#422), and
the documentation and CI follow-ups.

* chore(release): fold #432 golden-matching into the 0.5.1 cut

The release branch was cut one commit before #432 landed on main; the
synthetic merge CI builds would already ship golden_matching.py in the
0.5.1 wheel, so the module and its three top-level exports must be in
the release section. Merges main and documents the module in Release
highlights and Added.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants