diff --git a/AUDIT_TODO.md b/AUDIT_TODO.md new file mode 100644 index 000000000000..4ffbcbf633d5 --- /dev/null +++ b/AUDIT_TODO.md @@ -0,0 +1,201 @@ +# Rill Code Audit — Pending Findings + +**Last verified:** 2026-09-20, item by item cross-referenced with changed files, against `origin/main` merged into `review_code` (HEAD `008315ff3`). +**Consolidates:** the `audit/` area reports, `audit/MUST-FIX.md`, and `REVIEW_FINDINGS_TODO.md` (both superseded by this file). Full failure scenarios and test guidance for MF items remain in the linked `audit/*.md` reports. +**Now/next/later work queue:** derived from this file in [`audit/todo/`](audit/todo/README.md). + +**107 findings pending** — **39 must-fix** (stable MF ids) · **62 medium** (1 partial) · **6 low**. + +### 2026-09-20 re-verification result + +- 53 PRs merged 2026-08-30 → 2026-09-20. Changed files were intersected with every finding's cited paths (31 cited files touched); each overlapping finding was re-checked at its cited location. **3 findings fixed, 1 partially mitigated:** + - **MF-33 FIXED** — canvas `timeAndFilterStore` inner-subscription leak: the unified expression filter refactor ([#9746](https://github.com/rilldata/rill/pull/9746)) rewrote it as a single flat `derived([...])` with no inner `subscribe(set)` calls (`BaseCanvasComponent.ts:190+`). + - **G-4 FIXED** — expression mapping no longer drops falsy literals: `if (expr.val !== undefined)` at `map-metrics-resolver-query-to-dashboard.ts:139-140`. + - **G-5 FIXED (obsolete)** — the `dimensionsWithInListFilter` marker mechanism no longer exists anywhere in `web-common` (removed by the unified expression filter refactor #9746/#9886); the cited flaw cannot occur. + - **MF-38 PARTIAL** — the new `ExpressionFilterManager.setUrlParams` wraps `expandCompressedParams` in try/catch, but the main `convertURLToExplorePreset.ts:92` call is still unguarded and the `String.fromCharCode(...spread)` overflow in `compression.ts:23` remains. Still pending. +- Everything else re-checked at touched locations survives verbatim: MF-07/08/09/11/13/14/20/21/23/32/34/37/41, A-7/8/9/10, B-1/8/10/11, C-2, F-3, G-1/2, L-1/2/3/4. Notably `MetricsViewAnnotations` still assigns `limit = &req.Offset` (B-10) despite the file being touched. +- Cited line drift: MF-34 is now `layout-util.ts:186-325` (`generateArrayRearrangeFunction`; `insertRow` splices `newArray` at `:220,258,285` without splicing `touchedRows`); MF-32 is now `rduckdb/db.go:953`; A-9 is now `organizations.go:1110-1140`; L-1 is now `controller.go:1220`; MF-21 send is now `controller.go:1386`. +- Related but not findings: `feat: map` ([#8931](https://github.com/rilldata/rill/pull/8931)) landed native map charts, and `skills/*.md` AI agent skills shipped ([#9851](https://github.com/rilldata/rill/pull/9851)) — both items from the competitive roadmaps in `audit/*/roadmap.md`. + +### 2026-08-30 re-verification result + +- Every previously pending finding was re-checked against current code (42 PRs merged 2026-07-31 → 2026-08-30). **Zero pending findings were fixed** in that window; several cited files were refactored (SSE refactor #9261/#9260, pivot orchestration #9538, URI links #9588, view-as invalidation #9804, catalog-flush race #9815) but the specific failure modes survived in every case. Line numbers below are current. +- Removed as fixed: “runtime repo file APIs allow paths that escape the project root” (fixed by [#9723](https://github.com/rilldata/rill/pull/9723) via `drivers.ResolveRepoPath`, verified across all file/admin repo driver methods) — it was still listed as pending in `REVIEW_FINDINGS_TODO.md`. +- Reclassified: credit-trial start (A-7) is now **partial** — a `balance <= 0` guard makes retries idempotent, but concurrent starts can still double-grant. +- The GitHub-issue triage reports (`OPEN_ISSUES_REPORT.md`, `codex_issues_report.md`) were also re-checked on 2026-08-30: every tracked backlog issue is still open on GitHub, so both reports remain current as written. + +--- + +## Must-fix (39) + +MF ids are stable and never renumbered. Grouped by theme; each item links its source report. + +### Security boundaries + +- [ ] **MF-01 — Unsafe web-admin redirects after billing/device flows.** Untrusted `redirect` param opened verbatim, even after a swallowed mutation error; device flow also interpolates un-encoded `user_code` — `web-admin/src/routes/[organization]/-/upgrade-callback/+page.svelte:97-103`, `web-admin/src/features/billing/plans/upgrade-to-plan.ts:58`, `web-admin/src/routes/-/auth/device/+page.svelte:24,32`. ([web-admin](audit/web-admin.md)) +- [ ] **MF-13 — Magic tokens replay the creator's `admin` flag and privileged attributes.** Shared/embed links inherit `admin:true`, defeating `{{ .user.admin }}` policies — `admin/server/magic_tokens.go:90-99`, `admin/server/server.go:385`, `admin/server/runtime_jwt.go:113-119`. ([admin-auth-rbac](audit/admin-auth-rbac.md)) +- [ ] **MF-15 — Object-store `path_prefixes` bypassed by glob listing and downloads.** Only `ListObjects` enforces prefixes; `ListObjectsForGlob`/`DownloadFiles` go straight to the bucket — `runtime/drivers/s3/object_store.go:74-106`, `gcs/object_store.go:81-94`, `azure/object_store.go:87-98`. ([drivers-object-store](audit/drivers-object-store.md)) +- [ ] **MF-16 — Object-store prefix checks are not boundary-aware.** Raw `strings.HasPrefix`, so allowing `data` also admits `database/` — `runtime/drivers/object_store.go:177-180,276`. ([drivers-object-store](audit/drivers-object-store.md)) +- [ ] **MF-17 — AI `query_sql` executes mutations despite `ReadOnlyHint: true`.** Arbitrary SQL passed to the generic resolver with only row limit/timeout — `runtime/ai/query_sql.go:41,91-97`. ([ai](audit/ai.md)) +- [ ] **MF-18 — Local credentials written world-readable.** `os.WriteFile(..., 0o644)` and `MkdirAll(dotrill, os.ModePerm)` — `cli/pkg/dotrill/dotrill.go:113,362`. ([cli](audit/cli.md)) +- [ ] **MF-19 — Local PKCE auth/logout handlers accept external redirects.** Raw `?redirect=` used as post-auth origin and logout target — `cli/pkg/local/server.go:815-827,878,897-901`. ([cli](audit/cli.md)) +- [ ] **MF-30 — ClickHouse object-store credentials leak into SQL traces/logs.** S3/GCS keys embedded verbatim in generated `s3(...)`/`gcs(...)` SQL executed through the otelsql-instrumented connection — `runtime/drivers/clickhouse/model_executor_objectstore_self.go:127-161`. ([deep-connectors](audit/deep-connectors.md)) +- [ ] **MF-39 — TDD row headers render dimension values through `innerHTML` (stored XSS).** `escapeHtml` from #9588 covers only link `href`/`title`, not the value itself — `web-common/src/features/dashboards/time-dimension-details/TDDTable.svelte:210-214,262`. ([deep-audit-time-dimension-detail](audit/deep-audit-time-dimension-detail.md)) +- [ ] **MF-40 — Data-controlled `javascript:`/`data:` URIs reach dashboard links.** `makeHref` has no safe-scheme allowlist; #9588 widened exposure to leaderboard and pivot links — `web-common/src/features/dashboards/dashboard-utils.ts:155-180`. ([deep-audit-time-dimension-detail](audit/deep-audit-time-dimension-detail.md)) + +### Crashes and panics on ordinary input + +- [ ] **MF-04 — Pinot schema enumeration panics on a transient table-schema failure.** Per-table lookup errors swallowed, leaving nil slots that `sort.Slice` dereferences — `runtime/drivers/pinot/information_schema.go:274-287`. ([drivers-olap](audit/drivers-olap.md)) +- [ ] **MF-05 — `logbuffer.GetLogs(limit=0)` panics.** Only `limit < 0` is remapped; `0` indexes `logs[-1]` — `runtime/pkg/logbuffer/buffer.go:77-93`. ([runtime-pkg](audit/runtime-pkg.md)) +- [ ] **MF-38 — Malformed or oversized `gzipped_state` crashes dashboard load (PARTIAL).** `ExpressionFilterManager.setUrlParams` now guards decompression, but `convertURLToExplorePreset.ts:92` calls `expandCompressedParams` unguarded and the `String.fromCharCode(...bytes)` spread overflow remains — `web-common/src/features/dashboards/url-state/compression.ts:20-23,36`. ([deep-audit-state-management](audit/deep-audit-state-management.md)) +- [ ] **MF-28 — rduckdb `deleteRemote` panics on listing errors and deletes the wrong `meta.json`.** Deletes root-level `meta.json` instead of `/meta.json`; non-EOF iterator error falls through to nil deref — `runtime/pkg/rduckdb/remote.go:276,287-294`. ([deep-connectors](audit/deep-connectors.md)) + +### Deadlocks, hangs and races + +- [ ] **MF-06 — A slow log subscriber deadlocks instance logging.** `AddEntry` does unbuffered sends under `b.mu`; `WatchLogs` fan-out is a synchronous blocking `srv.Send` — `runtime/pkg/logbuffer/buffer.go:38-49`, `runtime/server/instances.go:274-276`. ([runtime-pkg](audit/runtime-pkg.md)) +- [ ] **MF-07 — `DeleteInstance` blocks forever after registry-store delete fails.** `registryCache.delete` returns a nil channel on error and the caller unconditionally receives — `runtime/registry.go:114-120,398-401`. ([runtime-core](audit/runtime-core.md)) +- [ ] **MF-08 — AI session notification strands the producer under the session lock.** `Subscribe` is unbuffered; `AddMessage` sends while holding `s.mu`; consumer exits on `ctx.Done()` — `runtime/ai/ai.go:653,889-895`, `runtime/server/chat.go:385-388`. ([ai](audit/ai.md)) +- [ ] **MF-09 — Static runtime slot allocation is a TOCTOU race (overcommit).** Capacity read and unconditional upsert are separate plain statements — `admin/provisioner/static/static.go:94-121`, `admin/database/postgres/postgres.go:794-810`. ([admin-billing-provision](audit/admin-billing-provision.md)) +- [ ] **MF-21 — Late reconcile completions block forever after controller shutdown.** Plain `c.completed <- inv` on an unbuffered channel; shutdown drain gives up after 30s (#9815 did not touch this) — `runtime/controller.go:148,325-350,1335`. ([REVIEW_FINDINGS](audit/00-summary.md)) +- [ ] **MF-22 — DuckDB connection-count metrics data race.** Callback reads `dbConnCount` without `dbCond.L` — `runtime/drivers/duckdb/duckdb.go:213-214,718-748`. ([REVIEW_FINDINGS](audit/00-summary.md)) + +### Data loss and silent failure + +- [ ] **MF-10 — File rename/delete helpers swallow errors; callers navigate as if success.** — `web-common/src/features/entity-management/actions/actions.ts:227-231,271-275`, callers `RenameAssetModal.svelte:106-118`, `FileExplorer.svelte:155-167,192-196`. ([frontend-shared](audit/frontend-shared.md)) +- [ ] **MF-11 — Failed chat send loses the draft and keeps a false optimistic message.** `startStreaming` resolves on "close" and never rejects; rollback in `handleTransportError` unreachable — `web-common/src/features/chat/core/conversation.ts:377-388,436-451,705-723`. ([frontend-runtime-client](audit/frontend-runtime-client.md)) +- [ ] **MF-14 — Editable deployment deletion continues after checkpoint push failure.** `GitPush` failure logged at Warn, then deprovision/branch delete/DB delete proceed — `admin/deployments.go:414-422,465-476,480`. ([admin-projects-deploy](audit/admin-projects-deploy.md)) +- [ ] **MF-20 — Failed delete reconciliation still hard-deletes the catalog resource.** Error only logged before `c.catalog.delete(...)` — `runtime/controller.go:1457-1467`. ([REVIEW_FINDINGS](audit/00-summary.md)) +- [ ] **MF-25 — Exhausted deployment reconcile jobs never persist a terminal error state.** River error handler only logs at max attempts; deployments stay “Provisioning…” forever — `admin/jobs/river/river.go:873-880` (only `DeploymentStatusErrored` write is the enqueue-failure path at `admin/deployments.go:817`). ([REVIEW_FINDINGS](audit/00-summary.md)) +- [ ] **MF-29 — rduckdb deletes the old remote version even when new metadata upload fails.** Failed `meta.json` upload only logged; old version deleted before `return err` — `runtime/pkg/rduckdb/remote.go:244-255`. ([deep-connectors](audit/deep-connectors.md)) +- [ ] **MF-31 — Salesforce batch-result fetch errors become empty files.** Errors logged and replaced with `bytes.NewReader(nil)`; ingestion proceeds silently partial — `runtime/drivers/salesforce/bulk.go:211-231`. ([deep-connectors](audit/deep-connectors.md)) + +### Correctness, leaks and wrong results + +- [ ] **MF-12 — Redshift `UNLOAD` breaks on any query containing a single quote.** Query interpolated unescaped — `runtime/drivers/redshift/warehouse.go:120`. ([drivers-object-store](audit/drivers-object-store.md)) +- [ ] **MF-23 — ClickHouse partial-open failures leak pools/embedded process.** After `embed.start()` and read-handle open, later failures return without cleanup — `runtime/drivers/clickhouse/clickhouse.go:224-395` (esp. `:303,308,322,336-339`). ([REVIEW_FINDINGS](audit/00-summary.md)) +- [ ] **MF-24 — Runtime-client JWT can become `Bearer undefined` after waiting for refresh.** Token checked before the await, header written after — `web-common/src/runtime-client/v2/runtime-client.ts:64-67`. ([REVIEW_FINDINGS](audit/00-summary.md)) +- [ ] **MF-26 — Migration reconciliation re-executes the current version.** `for v := from; v <= to; v++` with `from = state.Version` re-runs the persisted version every reconcile — `runtime/reconcilers/migration.go:76-83`. ([REVIEW_FINDINGS](audit/00-summary.md)) +- [ ] **MF-27 — Embed singleton retains the previous token/host/instance/external user.** `EmbedStore.init(url)` only when no singleton exists; store is immutable with no reset (#9761 didn't change init) — `web-admin/src/routes/-/embed/+layout.ts:7-9`, `web-common/src/features/embeds/embed-store.ts:37-49`. ([REVIEW_FINDINGS](audit/00-summary.md)) +- [ ] **MF-32 — rduckdb registers a non-removable DB-stats callback per write-handle open.** `otelsql.RegisterDBStatsMetrics` on every model build with no unregister — `runtime/pkg/rduckdb/db.go:956` (via `acquireWriteConn:780`). ([deep-connectors](audit/deep-connectors.md)) +- [ ] **MF-34 — Canvas row insertion marks the wrong rows touched.** `touchedRows` never spliced when `insertRow` splices `newArray`; flags desync from indices after upward moves — `web-common/src/features/canvas/layout-util.ts:196-318`. ([deep-audit-canvas](audit/deep-audit-canvas.md)) +- [ ] **MF-35 — Pivot row-total merging can assign cells to the wrong dimension rows.** Skeleton built from filtered `mergedRowTotals` while cells indexed against unfiltered `rowDimensionValues` — `web-common/src/features/dashboards/pivot/pivot-table-transformations.ts:66-86,222-252`, `pivot-data-store.ts:403-416,445-455`. ([deep-audit-pivot](audit/deep-audit-pivot.md)) +- [ ] **MF-36 — Pivot expanded-table cache discards new pages and fresh data.** Cached `expandedTableMap[configKey]` returned unconditionally (moved by #9538, flaw intact) — `web-common/src/features/dashboards/pivot/pivot-data-assembly.ts:90-96`. ([deep-audit-pivot](audit/deep-audit-pivot.md)) +- [ ] **MF-37 — Module-level pivot `lastKey` breaks pagination across instances.** Shared `let lastKey` across all pivot instances — `web-common/src/features/dashboards/pivot/pivot-data-config.ts:25,164-166`, `web-common/src/features/canvas/components/pivot/util.ts:98,239-241,329-331`. ([deep-audit-pivot](audit/deep-audit-pivot.md)) +- [ ] **MF-41 — TDD global scroll position is never reset or scoped.** Module-level `lastKnownPosition` restored with no per-dashboard scoping — `web-common/src/features/dashboards/time-dimension-details/time-dimension-data-store.ts:469`, `TDDTable.svelte:403-408`. ([deep-audit-time-dimension-detail](audit/deep-audit-time-dimension-detail.md)) +- [ ] **MF-42 — Metrics SQL accepts unsupported operators into invalid IR.** `operator` default case passes unknown opcodes through as `metricsview.Operator(op.String())`; fails late with confusing errors (#9716/#9721 didn't touch this) — `runtime/metricsview/metricssql/parser.go:509-512`. ([deep-metrics-sql](audit/deep-metrics-sql.md)) + +--- + +## Medium (62) + +### A. Admin, provisioning, billing and GitHub (11) + +- [ ] **A-1 `CreateProject` failure paths leave partial state.** Project tx commits before deploy-input validation; deployment creation/primary update not compensated — `admin/projects.go:24-115`. Fix: validate before commit; add compensating cleanup or an idempotent outbox flow. +- [ ] **A-2 `used_flusher` drops IDs after DB update failures.** Maps swapped before `flushToDB`, whose errors are only logged — `admin/used_flusher.go` (`flush`/`flushToDB`). Fix: requeue failed IDs or clear batches only after successful update. +- [ ] **A-3 `used_flusher` shutdown races the background goroutine.** `Close` does `cancel(); flush(); flushWg.Wait()` while the ticker flush can still `flushWg.Add(1)`; goroutine never joined — `admin/used_flusher.go` (`Close`/`runBackground`). Fix: join the goroutine and stop it before the final flush. +- [ ] **A-4 Kubernetes readiness ping ignores context and HTTP status.** Final `retryClient.Get(pingURL)` without ctx; `resp.StatusCode` never checked — `admin/provisioner/kubernetes/kubernetes.go:424`. Fix: `NewRequestWithContext`, bounded timeout, require 2xx. +- [ ] **A-5 Kubernetes provisioner setup panics on bad config.** Nil `TemplatePaths` deref, `template.Must`, `strings.Split(host, "//")[1]` — `admin/provisioner/kubernetes/kubernetes.go:125-133,206`. Fix: validate spec fields; parse host with `url.Parse`; return wrapped errors. +- [ ] **A-6 Static ClickHouse provisioning does not roll back DDL after later failure.** User/grant errors leave orphan DB/user; `Deprovision` exits early when `cfg.DSN == ""` — `admin/provisioner/clickhousestatic/provisioner.go:110+,264-266`. Fix: best-effort rollback or persist cleanup identifiers before DDL. +- [ ] **A-7 Credit-trial start is not serialized (PARTIAL).** A `balance <= 0` guard makes retries idempotent, but there is no per-org lock/idempotency key, so concurrent starts across the three call sites can double-grant — `admin/billing.go:203,283-291`, `admin/server/billing.go:149`, `admin/jobs/river/org_jobs.go:150`. Fix: per-org advisory lock or idempotency key around trial start. +- [ ] **A-8 Project-wide deployment updates have a data race on `prodErr`.** Goroutines assign the shared variable without synchronization — `admin/deployments.go:148-175`. Fix: mutex or per-deployment results through the errgroup. +- [ ] **A-9 Deployment annotations not refreshed when org custom domain changes.** `req.CustomDomain != org.CustomDomain` compared after `org` is reassigned with the new value, so the refresh branch never runs — `admin/server/organizations.go:1046-1079`. Fix: capture the old domain before update. +- [ ] **A-10 GitHub webhook processing is synchronous and unbounded.** `s.admin.ProcessGithubEvent(context.Background(), event)` inline in the handler — `admin/server/github.go:926`. Fix: enqueue a durable job after signature validation; bounded worker contexts; idempotent event keys. +- [ ] **A-11 Managed GitHub repos orphaned when DB metadata insert fails.** External repo created, then `InsertManagedGitRepo` failure returns with no compensation; cleanup job only sees DB-tracked repos — `admin/github.go:263-274`. Fix: best-effort delete on insert failure, or persist a pending row first. + +### B. Runtime controller, reconcilers and server (11) + +- [ ] **B-1 Catalog store release skipped on `newCatalogCache` init failures.** `NextControllerVersion`/`FindResources` errors return without `release()` — `runtime/catalog_cache.go:52-55,73-76`. Fix: release on all post-acquire error paths. +- [ ] **B-2 Controller accepts mutations after shutdown starts.** `c.closed` set only after the 30s drain + reconciler close; `checkRunning` is the sole guard — `runtime/controller.go:364,855`. Fix: mark stopping before leaving the event loop or reject mutations at shutdown start. +- [ ] **B-3 Staged model cleanup uses the canceled context.** `stageResultManager.Delete(ctx, stageResult)` deferred on the same cancellable ctx; leak accepted by comment — `runtime/reconcilers/model.go:1505-1513`. Fix: fresh bounded background context for cleanup. +- [ ] **B-4 Migration templates panic on non-model lookups.** Unconditional `res.Resource.(*runtimev1.Resource_Model)` type assert in template `Lookup` — `runtime/reconcilers/migration.go:149-150`. Fix: check `res.GetModel()` and return a template error. +- [ ] **B-5 Metrics-view reconciliation treats any model lookup error as “external table”.** Branches on `err == nil` and falls back to `Table = Model` for transient/context errors too — `runtime/reconcilers/metrics_view.go:81-88,94-98`. Fix: fall back only on `drivers.ErrResourceNotFound`. +- [ ] **B-6 Refresh-trigger processing is not durable before direct reconciles.** `r.C.Reconcile(ctx, rn)` fired for generic resources with progress kept only in the in-memory cloned spec; retry re-fires them — `runtime/reconcilers/refresh_trigger.go:87-94`. Fix: persist progress or make retries idempotent. +- [ ] **B-7 Alert ref-hash lookup failures silently change the hash.** All `c.Get` errors (incl. cancellation) collapse to `stateVersion = -1` — `runtime/reconcilers/alert.go:445-451`. Fix: return non-not-found errors from `refsStateHash`. +- [ ] **B-8 Report notification dirty state overwritten across notifiers.** Single `sent` flag per iteration; earlier successful email forgotten when a later notifier fails → duplicate send on retry — `runtime/reconcilers/report.go:619-635`. Fix: accumulate `anySent`. +- [ ] **B-9 Runtime SSE adapter sends are not cancellation-aware.** Plain `events <- event` while `serveSSEUntilClose` can return early on write error, stranding producers — `runtime/server/sse.go:137,171,218,265`, `runtime/server/chat.go:525,545`. Fix: select on `ctx.Done()` for every send. +- [ ] **B-10 `MetricsViewAnnotations` passes request `offset` as `limit`.** `if req.Offset != 0 { limit = &req.Offset }`, `offset` stays nil — `runtime/server/queries_metrics.go:630-633`. Fix: assign `offset = &req.Offset`. +- [ ] **B-11 Unknown time-grain enum values panic instead of validating.** `TimeGrainFromProto` default case panics; called on client-supplied enums — `runtime/metricsview/query.go:397-398` (call sites `queries_metrics.go:641,652`). Fix: return `(TimeGrain, error)` or validate at API boundaries. + +### C. Drivers and connectors (10) + +- [ ] **C-1 DuckDB metrics registration/context not cleaned up on open failure.** `ctx/cancel` and `registration` created before `reopenDB`; error path only closes remote — `runtime/drivers/duckdb/duckdb.go:191,213,219-229`. Fix: deferred cleanup until successful return. +- [ ] **C-2 ClickHouse `openHandle` leaks handles on ping/register failure and HTTP retry.** Ping failures return without `db.Close()`; retry reassigns `db` without closing the first — `runtime/drivers/clickhouse/clickhouse.go:940-960`. Fix: close failed handles; guard with cleanup defer. +- [ ] **C-3 Athena result pagination ignores the caller context.** `GetQueryResults(context.Background(), ...)` for next pages — `runtime/drivers/athena/olap.go:208`. Fix: store the query ctx on the rows object. +- [ ] **C-4 Redshift result pagination ignores the caller context.** `GetStatementResult(context.Background(), ...)` — `runtime/drivers/redshift/olap.go:242`. Fix: same as C-3. +- [ ] **C-5 Embedded ClickHouse binary download is unbounded.** Raw `http.Get(url)`, no ctx or timeout — `runtime/drivers/clickhouse/embed.go:437-448`. Fix: `NewRequestWithContext` + bounded client timeout. +- [ ] **C-6 HTTPS connector ignores configured `headers` and `path_prefixes`.** Connector-level values decoded but never merged into requests or enforced; only per-model headers apply — `runtime/drivers/https/https.go:53-58,259-266`. Fix: merge connector headers with documented precedence; enforce URL-prefix boundaries. +- [ ] **C-7 Azure connector uses default host credentials despite `allow_host_access=false`.** `NewDefaultAzureCredential` constructed unconditionally — `runtime/drivers/azure/object_store.go:174`. Fix: gate on `AllowHostAccess`. +- [ ] **C-8 Cached connector handles evicted on delete but not spec update.** `EvictWhere` only when `connector == nil`; credential rotation leaves the old handle live — `runtime/runtime.go:248-254`. Fix: evict on successful update too. +- [ ] **C-9 Driver handles opened after caller cancellation are leaked.** `openAndMigrate` returns an error when `ctx.Err() != nil` without closing the successfully opened handle — `runtime/connection_cache.go:169-182`. Fix: close the handle on every post-open error path. +- [ ] **C-10 Connector open-time validation is not cancelable.** StarRocks 30s background ping (`starrocks.go:350`), Pinot `dbx.Ping()` (`pinot.go:212`), ClickHouse `db.Ping()` (`clickhouse.go:942,959`), Slack `AuthTest()` (`slack.go:86`), Salesforce context-free login (`salesforce.go:217`). Fix: thread the caller context or defer validation to `Ping(ctx)`. + +### D. Shared runtime utilities (6) + +- [ ] **D-1 Blob download temp dir not removed when listing fails.** Temp dir created before `pagination.CollectAll`; failure returns without `os.RemoveAll` — `runtime/pkg/blob/download.go:71-83`. Fix: cleanup on all pre-iterator error returns. +- [ ] **D-2 Blob iterator `Next(ctx)` ignores cancellation.** Blocks on `<-it.batchCh` with no select on `ctx.Done()` — `runtime/pkg/blob/download.go:183`. +- [ ] **D-3 Git merge helpers don't accept a caller context.** `MergeWithStrategy`/`MergeWithBailOnConflict` (+`mergeInProgress`) use `Run(context.Background(), ...)` — `runtime/pkg/gitutil/sync.go:481-529`. +- [ ] **D-4 Connection-cache hanging checks nil-deref without `HangingFunc`.** Goroutine started whenever `CheckHangingInterval != 0`; optional callback called unconditionally — `runtime/pkg/conncache/conncache.go:137,446,450`. Fix: nil-check or require the callback in `New`. +- [ ] **D-5 `LazyWatcher.Subscribe` nil-derefs during concurrent close.** Unlocks after `count++`, then dereferences `w.watcher` which `Close` can nil out — `runtime/pkg/filewatcher/lazy.go:31,38-61`. Fix: capture the watcher under the mutex. +- [ ] **D-6 Admin repo git helpers don't receive the caller context.** `resetToRemoteTrackingBranch`, `setGitConfig`, `setRemoteURL`, `setFetchBranch`, `currentBranch` all use `context.Background()` — `runtime/drivers/admin/repo_git.go:397-433`. + +### E. Frontend runtime client (web-common) (6) + +- [ ] **E-1 Aborted requests keep waiting for a fresh JWT.** `waitForFreshJwt` polls on `disposed` + 60s deadline only; `req.signal` never consulted — `web-common/src/runtime-client/v2/runtime-client.ts:119-140`. Fix: reject immediately on abort. +- [ ] **E-2 Intentional SSE stop surfaces as an error.** `abort("SSE stream stopped by client")` string reason fails the `error?.name !== "AbortError"` suppression — `web-common/src/runtime-client/sse/sse-fetch-client.ts:110,126`. Fix: abort without a custom reason or treat `signal.aborted` as intentional. +- [ ] **E-3 SSE reconnect hook errors emitted after close/pause.** `onBeforeReconnect` catch emits `error` before checking `signal.aborted` — `web-common/src/runtime-client/sse/sse-connection.ts:190-201`. +- [ ] **E-4 Request queue cross-resource scheduling ignores request priority.** Every `NameEntry.weight` initialized to `ACTIVE_PRIORITY`; drain schedules by name-heap weight only — `web-common/src/runtime-client/v2/request-queue.ts:176-194,210-222`. Fix: track max pending priority per resource. +- [ ] **E-5 `removeByName` doesn't cancel or track active entries.** Only queued heap entries rejected; fired entries untracked, no AbortController — `web-common/src/runtime-client/v2/request-queue.ts:147-166,196-208`. +- [ ] **E-6 OLAP table lists not invalidated when only the connector changes.** Invalidation gated on table-name changes — `web-common/src/runtime-client/invalidation/resource-invalidators.ts:264-283`. Fix: include `connectorName != previousConnectorName`. + +### F. Cloud frontend (web-admin) (7) + +- [ ] **F-1 Embed iframe RPC handlers not disposed on route teardown.** `createIframeRPCHandler()` disposer discarded in `onMount`; `window` "message" listeners stack — `web-admin/src/routes/-/embed/+layout.svelte:111-123`, `web-common/src/lib/rpc.ts:79-91`. Fix: compose both cleanups in the `onMount` return. +- [ ] **F-2 "View As" falls back to real project permissions while mocked permissions load.** `mockUser.permissions ?? projectData?.projectPermissions` with `permissions` undefined during the fetch (#9804 fixed invalidation, not this) — `web-admin/src/features/projects/project-runtime.ts:38-39`, `web-admin/src/routes/[organization]/[project]/+layout.svelte:205-211`. Fix: treat mock mode as authoritative with a loading/empty permission set. +- [ ] **F-3 Alert/report metadata actions lack permission and confirmation gates.** Edit/one-click delete gated only on `!createdByCode`; `ProjectAccessControls` wraps only the owner block — `web-admin/src/features/alerts/metadata/AlertMetadata.svelte:149-163`, `web-admin/src/features/scheduled-reports/metadata/ReportMetadata.svelte:201-209`. Fix: wrap mutations in the access guard; confirm destructive actions. +- [ ] **F-4 Create-project form has duplicate submit paths.** Form `onsubmit={submit}` plus button `type="submit"` with `onClick={submit}` — `web-admin/src/features/projects/CreateProjectForm.svelte:148-175`. Fix: one submission path; disable while pending. +- [ ] **F-5 Report-run and project-wake polling loops are unbounded.** 1s loop until history changes; `while (true)` refetch every 2s until deployment appears — `web-admin/src/features/scheduled-reports/metadata/RunNowButton.svelte:39-53`, `web-admin/src/features/projects/RedeployProjectCTA.svelte:38-52`. Fix: abortable polling with timeout/max attempts and teardown cleanup. +- [ ] **F-6 Destructive delete dialogs close before the async delete finishes.** `onDelete(...)` not awaited; `open = false` immediately — `web-admin/src/features/public-urls/DeletePublicURLConfirmDialog.svelte:18-25`, `web-admin/src/features/projects/environment-variables/DeleteDialog.svelte:65-72`. Fix: await, show pending/error, close only on success. +- [ ] **F-7 GitHub connection component reads project data before the loading guard.** Top-level reactive destructure of `$proj.data` before the `{#if $proj.data}` check — `web-admin/src/features/projects/github/ProjectGithubConnection.svelte:19-21,37`. + +### G. Shared frontend features (web-common) (11 — G-4 and G-5 fixed 2026-09-20; ids are stable and not renumbered) + +- [ ] **G-1 Canvas `lastVisitedState` keyed by canvas name, not instance ID.** Module-level `Map` shared across projects/embeds — `web-common/src/features/canvas/stores/canvas-entity.ts:54,612,673`. Fix: key by the same `${instanceId}::${canvasName}` used by the store registry. +- [ ] **G-2 Dashboard time-range derivation applies stale async results.** `onTimeDimensionSelect`/`onSelectRange` apply whichever `deriveInterval` resolves last — `web-common/src/features/dashboards/filters/Filters.svelte:245-262,308-337`. Fix: generation counter or abort signal. +- [ ] **G-3 Canvas time-interval derivation applies stale async results.** `Promise.all(...).then(set)` with no guard — `web-common/src/features/canvas/stores/time-state.ts:163-220`. Fix: derived cleanup or generation counter. +- [ ] **G-6 Runtime file read errors swallowed as missing content.** `RuntimeFileIO.read` catches everything and returns `undefined` — `web-common/src/features/entity-management/file-io.ts:38-48`. Fix: typed not-found only for 404; rethrow the rest. +- [ ] **G-7 Uploaded filenames and generated DuckDB paths are not sanitized/quoted.** `data/${file.name}` unsanitized; path interpolated into single-quoted SQL and double-quoted YAML — `web-common/src/features/sources/modal/file-upload.ts:18`, `web-common/src/features/sources/sourceUtils.ts:126,129-148`. Fix: safe basename, URL-encode params, SQL-escape literals. +- [ ] **G-8 Generated local-file source detection never matches.** Generator emits `type: model` + `connector: duckdb` while `useIsLocalFileConnector` checks `yaml?.type === "duckdb"` — `web-common/src/features/sources/sourceUtils.ts:16-22,119-127`, `selectors.ts:60-62`. Fix: shared marker/helper for generation and detection. +- [ ] **G-9 Add-data import leaves committed secret edits after later failure.** Env session committed before model write; rollback only via user-initiated `cleanupAndBack` — `web-common/src/features/add-data/manager/steps/import.ts:218`, `GenerateDashboardStatus.svelte:105-121`. Fix: commit env after file creation succeeds, or auto-rollback on failure. +- [ ] **G-10 Source/model column derived stores leak inner subscriptions.** Inner `derived(...).subscribe(set)` return discarded — `web-common/src/features/sources/selectors.ts:81-102`, `web-common/src/features/models/selectors.ts:33-53`. Fix: return the unsubscribe from the outer callback. +- [ ] **G-11 File invalidation races overlapping write/delete events.** Fire-and-forget `void handleFileEvent(...)` with no per-path serialization while the write handler awaits `fetchContent(true)` — `web-common/src/features/entity-management/file-and-resource-watcher.ts:121-128`, `web-common/src/runtime-client/invalidation/file-invalidators.ts:64`. Fix: serialize per path or attach event versions. +- [ ] **G-12 Directory delete events don't clear child artifact state.** Delete cleanup inside `if (!event.isDir)`; dir deletes only refetch the list — `web-common/src/runtime-client/invalidation/file-invalidators.ts:55-101`. Fix: remove child artifacts/queries by prefix. +- [ ] **G-13 File invalidation ignores any path containing `.db`.** `event.path.includes(".db")` early return also matches e.g. `/models/my.dbt.sql` — `web-common/src/runtime-client/invalidation/file-invalidators.ts:49`. Fix: basename/extension rules for real DB artifacts only. + +--- + +## Low (6) + +- [ ] **L-1 `markPending` clears errors on the wrong node.** IDLE branch calls `updateErrorAndWarning(n, nil, nil)` inside the visit over descendant `dn` — `runtime/controller.go:1169`. +- [ ] **L-2 Partition JSON serialization panics instead of returning an error.** `json.Unmarshal` panic + `must(structpb.NewStruct(...))` in `modelPartitionToPB` — `runtime/server/controller.go:516-532`. +- [ ] **L-3 Canvas validation helpers ignore metrics-view lookup errors.** `continue` on any `r.C.Get` error in `validateMetricsViewTimeConsistency`/`validateRequiredFilters` — `runtime/reconcilers/canvas.go:266-268,337-339`. +- [ ] **L-4 Download-token parsing does not bound decompressed size.** `gzipDecompress` ends in unbounded `io.ReadAll` — `runtime/server/downloads.go:469-475`. +- [ ] **L-5 Auth-token cache entries not invalidated on revocation.** `PurgeAuthTokenCache` exists but has zero callers; revoked tokens valid for up to the cache TTL — `admin/auth_token.go:250-270`. +- [ ] **L-6 `Runtime.Repo` returns a non-nil release after rejecting a non-repo connector.** Returns `nil, release, err` after already releasing; defensive callers double-release — `runtime/connections.go:73-76`. Fix: return `nil, nil, err`. + +--- + +## Suggested fix order + +1. **Immediate security boundaries:** MF-39/MF-40 (stored XSS, unsafe schemes), MF-13 (magic-token privilege replay), MF-17 (destructive AI SQL), MF-30 (credentials in traces), MF-01/MF-19 (open redirects). +2. **Process-wide crash/deadlock risks:** MF-05/MF-06 (logbuffer), MF-07 (instance deletion), MF-08 (AI session send), MF-04 (Pinot panic), MF-21 (controller shutdown). +3. **Irrecoverable or silent data loss:** MF-14, MF-20, MF-29, MF-31, then MF-10/MF-11. +4. **Concurrency and capacity invariants:** MF-09, MF-22, MF-23, MF-25, MF-32, A-7, A-8. +5. **Wrong-result and stale-state bugs:** MF-26, MF-34 through MF-38, MF-41, MF-42, then the remaining medium items by area. + +## Appendix: resolved-finding register + +25 PRs merged 2026-07-11 → 2026-07-31 exactly resolved audit findings (see git history of `audit/MUST-FIX.md` predecessor for the original one-line register): #9683 (ClickHouse static DB-name collision), #9699 (`.env` pushed to wrong project), #9700 (ConnectorService authorization), #9701 (DashboardStateSync lock leak), #9702 (component-variable parse panic), #9703 (nil time ranges in AI resolver), #9704 (security-blind query cache key), #9705 (annotations-resolver access check), #9706 (BigQuery client leak), #9707 (alert notifier nil deref), #9709 (full rebuild after model rename), #9711 (partition catalog rows leaked), #9712 (`IS FALSE` inversion), #9714 (QueryBatch RPC removed), #9715 (aggregation export panic), #9716 (metrics SQL clause drops), #9717 (Summary security-filter leak), #9719 (`NOT BETWEEN` inversion), #9720 (decimal literal loss), #9721 (joins silently ignored), #9722 (canvas tab-group PDF export), #9723 (repo-root escape in AI file tools and repo drivers), #9724 (annotation validation parent fields), #9725 (parquet timeseries export panic), #9726 (`ResolveLocalPath` sandbox bypass). + +No pending finding was resolved between 2026-07-31 and 2026-08-30. + +Resolved 2026-08-30 → 2026-09-20 (verified at HEAD `008315ff3`): **MF-33** (canvas `timeAndFilterStore` subscription leak — eliminated by the unified expression filter refactor, #9746), **G-4** (falsy filter literals dropped — `expr.val !== undefined`), **G-5** (canvas in-list filter marker — mechanism removed by #9746/#9886). **MF-38** partially mitigated (guarded decompression in `ExpressionFilterManager` only) and remains pending. diff --git a/OPEN_ISSUES_REPORT.md b/OPEN_ISSUES_REPORT.md new file mode 100644 index 000000000000..cc78c63d80dc --- /dev/null +++ b/OPEN_ISSUES_REPORT.md @@ -0,0 +1,239 @@ +# Rill Open Issues Report — Triage, Phasing & Labels + +**Repo:** `rilldata/rill` · **Open issues:** 121 · **Generated:** 2026-07-26 · **Updated:** 2026-07-31 +**Code verification:** ~45 of the most-suspect issues were checked against the current codebase. Verdicts are marked 🟡 PARTIAL or ❌ still open; the 12 verified-done issues have been removed from the phases and are listed once in Phase 0 for GitHub closure. + +## TL;DR + +- Only 8 issues were filed in 2026; the rest are a 2024–2025 backlog, much of it unlabeled and with zero comments. +- **12 issues are already implemented** (verified against code) — they are excluded from the work phases and only need closing on GitHub; 11 more are partially done and rescoped to their remaining gap. See "Phase 0" below. +- Recommended order of work: **(0)** close verified-done issues and re-triage stale ones, **(1)** data-correctness and security bugs, **(2)** customer-requested Explore/filter/time features, **(3)** ClickHouse & connectors, **(4)** Rill Developer UX bugs and quick wins, **(5)** refactors, cloud features and big bets. +- The label taxonomy is inconsistent (`Type:Bug` vs `enhancement`, one-off `Area:ClickHouse`, `nit`, `from-slack`). A normalized `type:` / `area:` / `priority:` scheme is proposed at the end, with per-issue suggestions in every table. + +--- + +## Phase 0 — Close and re-triage (near-zero engineering cost) + +### ✅ Already implemented — close on GitHub (removed from the phases below) + +These 12 issues were verified as already implemented in current code and are excluded from all work phases. They are still open on GitHub (checked 2026-07-31) and just need closing: + +`#3764` (`--no-open` flag) · `#5202` ("now" in rilltime) · `#5061` (fixed by the rilltime replacement) · `#5775` (TDD chart resizer) · `#5575` (canvas `max_width`) · `#4007` (derived metrics views via `parent_*`) · `#4446` (multiple time dimensions + picker) · `#5469` (ClickHouse `database` config) · `#5645` (`ProjectStorage` on status page) · `#4675` (theme parse errors surfaced) · `#4821` (ingesting spinner in inspector) · `#5905` (OLAP-aware project init) + +### 🟡 Partially implemented — rescope to the remaining gap before working on them + +| # | What's done | What remains | +|---|---|---| +| [#6357](https://github.com/rilldata/rill/issues/6357) Custom time ranges | Rich rilltime grammar; explore/canvas `time_ranges` validated through it | No `label`/`display_name` on `ExploreTimeRange` — custom ranges can't be given friendly names | +| [#5026](https://github.com/rilldata/rill/issues/5026) Auto-populate dimensions | Explore YAML supports `dimensions: '*'` (and defaults to all) | No wildcard at the metrics-view level; "all columns" only via non-AI generator fallback | +| [#4898](https://github.com/rilldata/rill/issues/4898) Inline 4xx errors | `InlineErrorIndicator.svelte` on measure charts and big numbers | Leaderboards render no error at all; TDD shows a generic message without the server error | +| [#5564](https://github.com/rilldata/rill/issues/5564) Dashboard formatting | Data-driven column widths (leaderboard + pivot), d3 locale/currency, tooltip formatters | Generic table formatting rules; resize-driven dynamic formatting | +| [#5647](https://github.com/rilldata/rill/issues/5647) Sharing thumbnail | Org-level thumbnail upload (`ThumbnailSettings.svelte`, `thumbnail_asset_id`) | `og:image` still hardcoded in `web-admin/src/app.html`; no per-dashboard thumbnail | +| [#5699](https://github.com/rilldata/rill/issues/5699) `metrics_sql` aliases | Aliases honored for function-call expressions | `parseSelect` still has `TODO no alias handling for column names`; filter parser rejects aliases | +| [#5975](https://github.com/rilldata/rill/issues/5975) Idle detection | Per-tab SSE pause on blur/visibility with idle timeouts | No cross-tab "keep 2 most-recent tabs active" coordination (no BroadcastChannel/tab registry) | +| [#4838](https://github.com/rilldata/rill/issues/4838) File-explorer icons | Special icons for `.env` and `rill.yaml`; resource-kind icons | `.py`/`.json`/`.md` etc. still fall through to the generic file icon | +| [#5713](https://github.com/rilldata/rill/issues/5713) New-file positional context | "Add folder"/"Add blank file" respect the current directory | Typed resources (canvas, metrics view, API…) still land in fixed top-level folders (`new-files.ts:119-137`) | +| [#5985](https://github.com/rilldata/rill/issues/5985) Info-schema search | `search_pattern` API + search box on the local Tables page | No search input in the connector explorer sidebar itself | +| [#6399](https://github.com/rilldata/rill/issues/6399) ClickHouse source forms | Add-data flow emits `output.connector: clickhouse` based on project OLAP | No ClickHouse-specific source-step form fields (`templates/schemas/clickhouse.ts` is connector-step only) | + +### Stale-triage sweep + +Roughly a third of the backlog is from H1 2024, unlabeled, with zero comments. Several likely no longer apply after the explore/canvas rewrites — the 12 verified-done issues above prove drift is real. Re-confirm or close: + +`#3760 #3784 #3792 #3803 #3820 #3854 #3896 #3906 #4308 #4309 #4310 #4439 #4440 #4441 #4445 #4579 #4887 #5055 #5229 #5330 #5584 #5608 #5633 #5634 #5892 #5958` + +Suggested label: `stale-candidate` (or a stale-bot with a 90-day window going forward). + +--- + +## Phase 1 — Correctness & security bugs (work on these first) + +These produce **wrong numbers, broken dashboards, or broken access control**, which is existential for a BI tool. + +| # | Title (abridged) | Verified status / why now | Suggested labels | +|---|---|---|---| +| [#9395](https://github.com/rilldata/rill/issues/9395) | Pivot "Absolute change" ignores new dimension members, shows 0 change | Wrong numbers in time comparison; recent (May 2026) | `type:bug` `area:pivot` `priority:p0` | +| [#3835](https://github.com/rilldata/rill/issues/3835) | An `include` access policy breaks the dashboard | Security policies failing is a trust issue | `type:bug` `area:security-policies` `priority:p0` | +| [#8573](https://github.com/rilldata/rill/issues/8573) | "Invalid interval UTC" when selecting time interval | ❌ Confirmed still broken: fallback text still in `RangeDisplay.svelte`. Note: a suppression-only fix exists on unmerged branch `origin/cursor/APP-761-…` (`97044728f`) — the underlying resolution failure in `new-time-controls.ts:363-403` is unfixed | `type:bug` `area:time-controls` `priority:p1` | +| [#4001](https://github.com/rilldata/rill/issues/4001) | Data column missing in TDD table | ❌ Confirmed, root cause found: table strips boundary buckets the chart renders (`time-dimension-data-store.ts:222` — `data?.slice(1, -1)`) | `type:bug` `area:explore` `priority:p1` | +| [#5076](https://github.com/rilldata/rill/issues/5076) | Runtime: don't cache connection errors indefinitely | 7 comments; projects stuck in error until restart | `type:bug` `area:runtime` `priority:p1` | +| [#5799](https://github.com/rilldata/rill/issues/5799) | `metrics_sql` `date_trunc` day precision not formatted to day | Wrong output from the metrics SQL layer | `type:bug` `area:metrics-layer` `priority:p1` | +| [#4638](https://github.com/rilldata/rill/issues/4638) | Pivot: one row dim + one column dim shows an empty table | Core pivot layout broken | `type:bug` `area:pivot` `priority:p1` | +| [#6350](https://github.com/rilldata/rill/issues/6350) | Waking a hibernated project: settings navigation stops the wake in UI | Cloud onboarding/resume friction | `type:bug` `area:cloud` `priority:p2` | + +## Phase 2 — Explore dashboard & filter/time features (biggest customer cluster) + +The largest coherent cluster of `customer`-tagged asks. Clubbing them lets one engineer own filters + time controls end to end. All verified ❌ still open unless noted. + +### 2a. Filters (club together) + +| # | Title | Verified | Suggested labels | +|---|---|---|---| +| [#5040](https://github.com/rilldata/rill/issues/5040) | Include **and** exclude filter on the same dimension | ❌ One expression per dimension (`dimension-filters.ts`); read-only "Advanced" chip can display but not build it | `type:feature` `area:filters` `customer` | +| [#4044](https://github.com/rilldata/rill/issues/4044) | Define and apply filter states across dashboards | — | `type:feature` `area:filters` `customer` | +| [#4421](https://github.com/rilldata/rill/issues/4421) | Cross-dashboard filters (overlaps #4044 — consider merging) | — | `type:feature` `area:filters` `customer` `duplicate?` | +| [#5060](https://github.com/rilldata/rill/issues/5060) | Order filters by order added, not alphabetically | ❌ Still `a.name > b.name` sort (`selectors/filters.ts`) | `type:feature` `area:filters` `good-first-issue` | +| [#5428](https://github.com/rilldata/rill/issues/5428) | Ability to unset column sorting | ❌ `enableSortingRemoval: false` in all four table components | `type:feature` `area:explore` `good-first-issue` | + +### 2b. Time ranges & grains (club together) + +| # | Title | Verified | Suggested labels | +|---|---|---|---| +| [#6357](https://github.com/rilldata/rill/issues/6357) | Custom time-range **labels** (rescoped; grammar itself is done) | 🟡 | `type:feature` `area:time-controls` | +| [#4366](https://github.com/rilldata/rill/issues/4366) | Custom time-grain formatting | ❌ Grain labels hardcoded in `web-common/src/lib/time/config.ts` | `type:feature` `area:time-controls` | +| [#3958](https://github.com/rilldata/rill/issues/3958) | Grey out unavailable time grains rather than hiding them | ❌ Selectors still filter grains out (`TimeGrainSelector.svelte`, `new-grains.ts:219-239`) | `type:feature` `area:time-controls` `customer` `good-first-issue` | +| [#8768](https://github.com/rilldata/rill/issues/8768) | Support ISO identifiers while retaining temporal type | — | `type:feature` `area:time-controls` `from-slack` | + +### 2c. Leaderboard, TDD & pivot enhancements + +| # | Title | Verified | Suggested labels | +|---|---|---|---| +| [#4405](https://github.com/rilldata/rill/issues/4405) | Leaderboard comparison: previous value as a column | ❌ Still hover-only (`LeaderboardRow.svelte:218`) | `type:feature` `area:explore` | +| [#5547](https://github.com/rilldata/rill/issues/5547) | Pivot exports should respect selected granularity | ❌ Server writes full timestamps regardless of grain (`runtime/queries/metricsview.go:345`) | `type:feature` `area:pivot` `customer` | +| [#5624](https://github.com/rilldata/rill/issues/5624) | Show comparison dates in pivot headers | ❌ Headers still generic "Δ"/"Δ %" (`pivot-column-definition.ts:218-228`) | `type:feature` `area:pivot` | +| [#5612](https://github.com/rilldata/rill/issues/5612) | Raw data viewer for TDD | ❌ Rows viewer explicitly excluded in TDD mode (`Dashboard.svelte:285`) | `type:feature` `area:explore` | +| [#4898](https://github.com/rilldata/rill/issues/4898) | Inline 4xx errors on leaderboards + TDD (rescoped) | 🟡 | `type:feature` `area:explore` | +| [#5648](https://github.com/rilldata/rill/issues/5648) | Additional Time Dimension graph capabilities | — | `type:feature` `area:explore` `needs-triage` (vague scope) | + +### 2d. Metrics layer (club together — definition reuse & governance theme) + +| # | Title | Verified | Suggested labels | +|---|---|---|---| +| [#8085](https://github.com/rilldata/rill/issues/8085) | Templating of model names/properties in metrics views | ❌ Parser explicitly disallows structural templating (`runtime/parser/template.go:26`) | `type:feature` `area:metrics-layer` | +| [#8711](https://github.com/rilldata/rill/issues/8711) | Native, exportable dictionary of metrics and definitions | — | `type:feature` `area:metrics-layer` | +| [#5026](https://github.com/rilldata/rill/issues/5026) | Wildcard dimensions at metrics-view level (rescoped) | 🟡 | `type:feature` `area:metrics-layer` `customer` | +| [#5699](https://github.com/rilldata/rill/issues/5699) | Column-name aliases in `metrics_sql` (rescoped) | 🟡 | `type:feature` `area:metrics-layer` `good-first-issue` | + +## Phase 3 — ClickHouse & connectors + +### 3a. ClickHouse (club together) + +| # | Title | Verified | Suggested labels | +|---|---|---|---| +| [#5199](https://github.com/rilldata/rill/issues/5199) | Better error handling for ClickHouse OLAP engine | — | `type:feature` `area:clickhouse` | +| [#5544](https://github.com/rilldata/rill/issues/5544) | `unnest` throws SQL compilation error on ClickHouse | — | `type:bug` `area:clickhouse` | +| [#5318](https://github.com/rilldata/rill/issues/5318) | Debug query cancellation in `clickhouse-go` | — | `type:bug` `area:clickhouse` | +| [#5081](https://github.com/rilldata/rill/issues/5081) / [#5082](https://github.com/rilldata/rill/issues/5082) | LIKE vs ILIKE + prefix-LIKE for suggestions | ❌ Search hardcodes `ILIKE '%x%'` (`executor.go:994-1021`); no toggle exists. Club as one "configurable dimension search matching" issue with [#5269](https://github.com/rilldata/rill/issues/5269) | `type:feature` `area:clickhouse` | +| [#6399](https://github.com/rilldata/rill/issues/6399) | ClickHouse-specific source form fields (rescoped) | 🟡 | `type:feature` `area:clickhouse` `area:dev-ux` | + +### 3b. Connectors & sources + +| # | Title | Verified | Suggested labels | +|---|---|---|---| +| [#5798](https://github.com/rilldata/rill/issues/5798) | Trino connector support (5 comments — community interest) | — | `type:feature` `area:connectors` | +| [#8911](https://github.com/rilldata/rill/issues/8911) | Arrow Flight SQL transport for StarRocks connector | — | `type:feature` `area:connectors` | +| [#5101](https://github.com/rilldata/rill/issues/5101) | MongoDB connector | — | `type:feature` `area:connectors` `customer` | +| [#5173](https://github.com/rilldata/rill/issues/5173) | Parquet files without type extension fail to ingest | — | `type:bug` `area:connectors` | +| [#5430](https://github.com/rilldata/rill/issues/5430) | VARCHAR → LIST conversion error on ingest | — | `type:bug` `area:connectors` | +| [#4260](https://github.com/rilldata/rill/issues/4260) | `limit` source property | ❌ No dedicated `limit`, but `dev:`/`environment_overrides:` cover the use case — consider closing as "workaround supported" | `type:feature` `area:connectors` `customer` | +| [#4579](https://github.com/rilldata/rill/issues/4579) | Schema relaxation: cast numbers to strings when needed | — | `type:feature` `area:connectors` | +| [#4895](https://github.com/rilldata/rill/issues/4895) | Noisy `gosnowflake` DBUS warning | — | `type:bug` `area:connectors` `good-first-issue` | +| [#3784](https://github.com/rilldata/rill/issues/3784) | Warn when Add Source URI lacks a file format | — | `type:feature` `area:connectors` `good-first-issue` | +| [#4887](https://github.com/rilldata/rill/issues/4887) | Create a dev partition when generating initial source spec | — | `type:feature` `area:connectors` | +| [#5985](https://github.com/rilldata/rill/issues/5985) | Search in connector explorer sidebar (rescoped; API + Tables page done) | 🟡 | `type:feature` `area:connectors` `area:dev-ux` | + +## Phase 4 — Rill Developer UX: bugs first, then quick wins + +Individually small; batching them gives an outsized "quality" release. Several are `good-first-issue` material. + +### 4a. Developer bugs + +| # | Title | Verified | Suggested labels | +|---|---|---|---| +| [#4917](https://github.com/rilldata/rill/issues/4917) | SQL autocomplete fails when table name is quoted | — | `type:bug` `area:editor` | +| [#4933](https://github.com/rilldata/rill/issues/4933) | Duplicate column missing from `rows` API response | — | `type:bug` `area:editor` `area:runtime` | +| [#3807](https://github.com/rilldata/rill/issues/3807) | Model results sometimes don't show when typing slowly | — | `type:bug` `area:editor` | +| [#3949](https://github.com/rilldata/rill/issues/3949) | "X of Y rows" doesn't update Y when switching models | — | `type:bug` `area:editor` `good-first-issue` | +| [#5379](https://github.com/rilldata/rill/issues/5379) | 404 flash when a file is dropped onto Rill Developer | — | `type:bug` `area:dev-ux` | +| [#5455](https://github.com/rilldata/rill/issues/5455) | Same-name/different-case file collision not caught | — | `type:bug` `area:parser` | +| [#4944](https://github.com/rilldata/rill/issues/4944) | Source inspector sometimes missing reconciling spinner | — (base feature exists per #4821; this is a flicker/timing bug) | `type:bug` `area:dev-ux` | +| [#5681](https://github.com/rilldata/rill/issues/5681) | File header jumps after zooming timestamp chart + navigating | — | `type:bug` `area:dev-ux` | +| [#5958](https://github.com/rilldata/rill/issues/5958) | Welcome screen: example project click sometimes hangs | — | `type:bug` `area:dev-ux` | +| [#3960](https://github.com/rilldata/rill/issues/3960) | Hiding a measure/dimension cancels outstanding queries | — | `type:bug` `area:explore` | +| [#4213](https://github.com/rilldata/rill/issues/4213) | Leaderboard filter often shows a cancelled query | ❌ No cancellation handling in `Leaderboard.svelte:175-265`; still plausible | `type:bug` `area:explore` | +| [#4258](https://github.com/rilldata/rill/issues/4258) | Misaligned columns for measures without time series | — | `type:bug` `area:explore` | +| [#5601](https://github.com/rilldata/rill/issues/5601) | Clicking pivot cell doesn't expand model viewer | — | `type:bug` `area:pivot` | + +### 4b. Quick wins & polish + +| # | Title | Verified | Suggested labels | +|---|---|---|---| +| [#5326](https://github.com/rilldata/rill/issues/5326) | File explorer: remember open directories | ❌ In-memory store only; connector explorer already shows the localStorage pattern to copy (`connector-explorer-store.ts:65-67`) | `type:feature` `area:dev-ux` `good-first-issue` | +| [#5713](https://github.com/rilldata/rill/issues/5713) | Typed resources should respect current directory (rescoped) | 🟡 | `type:feature` `area:dev-ux` `good-first-issue` | +| [#4838](https://github.com/rilldata/rill/issues/4838) | Extension-specific icons for `.py`/`.json`/`.md`… (rescoped) | 🟡 | `type:feature` `area:dev-ux` `good-first-issue` | +| [#4828](https://github.com/rilldata/rill/issues/4828) | Close the application from the Developer UI | ❌ No shutdown RPC in `proto/rill/local/v1/api.proto` | `type:feature` `area:dev-ux` `community` `good-first-issue` | +| [#5588](https://github.com/rilldata/rill/issues/5588) | Table preview: show underlying datatypes | ❌ `ProfileColumn` has a single `type`; non-DuckDB OLAPs return runtime codes (`table_columns.go:136-141`) | `type:chore` `area:dev-ux` | +| [#5970](https://github.com/rilldata/rill/issues/5970) | Generated metrics YAML should match Visual Metrics Editor layout | ❌ Generator and editor still emit different key orders | `type:chore` `area:dev-ux` `good-first-issue` | +| [#5975](https://github.com/rilldata/rill/issues/5975) | Cross-tab idle coordination (rescoped) | 🟡 | `type:feature` `area:dev-ux` | +| [#5495](https://github.com/rilldata/rill/issues/5495) | Support creating mapping tables in Developer | ❌ No UI table-authoring path exists | `type:feature` `area:dev-ux` | +| [#4871](https://github.com/rilldata/rill/issues/4871) | Comparison selector color selection | — | `type:chore` `area:explore` `good-first-issue` | +| [#3906](https://github.com/rilldata/rill/issues/3906) | Background line CSS animation on welcome page | — | `type:chore` `area:dev-ux` `good-first-issue` | + +## Phase 5 — Refactors, cloud features & big bets (schedule deliberately) + +### 5a. Frontend tech debt & state management (re-validate before starting — most predate current architecture) + +| # | Title | Suggested labels | +|---|---|---| +| [#4308](https://github.com/rilldata/rill/issues/4308) / [#4309](https://github.com/rilldata/rill/issues/4309) / [#4310](https://github.com/rilldata/rill/issues/4310) | State management revamp: filters, time controls, measure filters to backend | `type:chore` `area:frontend` `needs-triage` | +| [#4439](https://github.com/rilldata/rill/issues/4439) / [#4440](https://github.com/rilldata/rill/issues/4440) / [#4441](https://github.com/rilldata/rill/issues/4441) / [#4445](https://github.com/rilldata/rill/issues/4445) | Menu replacement, MeasureChart refactor, loading states, scrollbar styling | `type:chore` `area:frontend` `stale-candidate` | +| [#7107](https://github.com/rilldata/rill/issues/7107) | Unify/simplify tooltips | `type:chore` `area:frontend` | +| [#5229](https://github.com/rilldata/rill/issues/5229) / [#5055](https://github.com/rilldata/rill/issues/5055) | Superforms migration / form-library research | `type:chore` `area:frontend` `stale-candidate` | +| [#5330](https://github.com/rilldata/rill/issues/5330) | Dimension detail: reuse the pivot table component | `type:chore` `area:frontend` | +| [#5608](https://github.com/rilldata/rill/issues/5608) | Consistent global header in Rill Developer | `type:chore` `area:dev-ux` | +| [#3803](https://github.com/rilldata/rill/issues/3803) | Remove profiling queries from dashboard component | `type:chore` `area:frontend` | +| [#5633](https://github.com/rilldata/rill/issues/5633) / [#5634](https://github.com/rilldata/rill/issues/5634) | Chart brush / stacked-area brush styling | `type:chore` `area:charts` | +| [#5584](https://github.com/rilldata/rill/issues/5584) | Canvas UXQA | `type:chore` `area:canvas` `needs-triage` (likely partially done) | + +### 5b. Runtime & infra + +| # | Title | Suggested labels | +|---|---|---| +| [#3854](https://github.com/rilldata/rill/issues/3854) | Persistent storage for distributed workers | `type:feature` `area:runtime` | +| [#3760](https://github.com/rilldata/rill/issues/3760) | Serve from local SSD with persistent GCS backup | `type:feature` `area:runtime` | +| [#3792](https://github.com/rilldata/rill/issues/3792) | Flush catalog when adding a trigger | `type:chore` `area:runtime` `stale-candidate` | +| [#3820](https://github.com/rilldata/rill/issues/3820) | Don't send reports for obviously invalid queries | `type:bug` `area:alerts-reports` | +| [#5892](https://github.com/rilldata/rill/issues/5892) | Remove data resolvers for components | `type:chore` `area:runtime` | +| [#5284](https://github.com/rilldata/rill/issues/5284) | Fix pagination in GitHub List APIs | `type:bug` `area:admin` | +| [#3896](https://github.com/rilldata/rill/issues/3896) | Add dependency validation to CI | `type:chore` `area:ci` | +| [#5988](https://github.com/rilldata/rill/issues/5988) | e2e test for editing security policies | `type:chore` `area:testing` | + +### 5c. Rill Cloud features + +| # | Title | Verified | Suggested labels | +|---|---|---|---| +| [#8756](https://github.com/rilldata/rill/issues/8756) | Custom role creation | ❌ Roles hardcoded (`admin/database/database.go:960-1010`); no CreateRole RPC | `type:feature` `area:cloud` `from-slack` | +| [#8850](https://github.com/rilldata/rill/issues/8850) | Filter canvas KPI/Table based on metrics security policy | — | `type:feature` `area:canvas` `area:security-policies` `from-slack` | +| [#5664](https://github.com/rilldata/rill/issues/5664) | Dashboard bookmarks for user groups | ❌ `Bookmark` has only `UserID`/`Default`/`Shared` — no group scope | `type:feature` `area:cloud` | +| [#4877](https://github.com/rilldata/rill/issues/4877) | Organize content in Rill Cloud (folders) | — | `type:feature` `area:cloud` `customer` | +| [#4429](https://github.com/rilldata/rill/issues/4429) | Global asset search | ❌ All web-admin search is scoped; no cross-project RPC | `type:feature` `area:cloud` `customer` | +| [#5647](https://github.com/rilldata/rill/issues/5647) | Per-dashboard sharing thumbnail / og:image (rescoped) | 🟡 | `type:feature` `area:cloud` | +| [#5493](https://github.com/rilldata/rill/issues/5493) | Improve journey from Project Status page to dashboard after deploy | — | `type:feature` `area:cloud` | +| [#5755](https://github.com/rilldata/rill/issues/5755) | Alerts: support dimension criteria | ❌ Criteria limited to measures (`alerts/form-utils.ts:31`, `CriteriaForm.svelte:30-77`) | `type:feature` `area:alerts-reports` | + +### 5d. Big bets (need product decision before engineering) + +| # | Title | Verified | Suggested labels | +|---|---|---|---| +| [#4404](https://github.com/rilldata/rill/issues/4404) | Plot two metrics on a single chart (6 comments) | — | `type:feature` `area:charts` `epic` | +| [#4863](https://github.com/rilldata/rill/issues/4863) | Forecasting in time-series charts | — | `type:feature` `area:charts` `epic` `customer` | +| [#4817](https://github.com/rilldata/rill/issues/4817) | Postgres wire protocol support | — | `type:feature` `area:runtime` `epic` | +| [#4235](https://github.com/rilldata/rill/issues/4235) | Local LLM support for privacy | — | `type:feature` `area:ai` `epic` | +| [#4407](https://github.com/rilldata/rill/issues/4407) | Locked-down enterprise environment support | — | `type:feature` `area:deployment` `epic` | +| [#4577](https://github.com/rilldata/rill/issues/4577) | Interactive UI for custom API management | ❌ APIs only get the generic code editor; no API workspace | `type:feature` `area:dev-ux` `epic` | +| [#4858](https://github.com/rilldata/rill/issues/4858) | Panning for alternate charts | — | `type:feature` `area:charts` | +| [#9130](https://github.com/rilldata/rill/issues/9130) | Canvas heatmap: `normalize` option for row/column % | — | `type:feature` `area:canvas` | + +--- + +## Proposed label taxonomy + +Current labels are inconsistent: `Type:Bug`/`Type:Feature` coexist with `enhancement`, `nit`, `from-slack`, a single `Area:ClickHouse`, and `Team:Applications`. Suggested normalized scheme: + +- **Type (exactly one):** `type:bug`, `type:feature`, `type:chore` (replaces `nit`, refactors, tech debt) +- **Area (one or more):** `area:explore`, `area:pivot`, `area:canvas`, `area:time-controls`, `area:filters`, `area:metrics-layer`, `area:charts`, `area:clickhouse`, `area:connectors`, `area:runtime`, `area:cloud`, `area:admin`, `area:dev-ux`, `area:editor`, `area:cli`, `area:parser`, `area:security-policies`, `area:alerts-reports`, `area:ai`, `area:frontend`, `area:testing`, `area:ci`, `area:deployment` +- **Priority:** `priority:p0` (correctness/security), `priority:p1`, `priority:p2` +- **Source (keep, they're useful signal):** `customer`, `community`, `from-slack` +- **Process:** `good-first-issue`, `needs-triage`, `stale-candidate`, `epic`, `duplicate?` + +Notable clubbing opportunities: **#4044 + #4421** (cross-dashboard filter state — likely duplicates), **#4308/#4309/#4310** (one state-management epic), **#5081/#5082/#5269** (one "configurable dimension search matching" epic), **#3958/#4366/#6357** (time-grain/range UX polish bundle). diff --git a/audit/00-summary.md b/audit/00-summary.md new file mode 100644 index 000000000000..fce3a10a1615 --- /dev/null +++ b/audit/00-summary.md @@ -0,0 +1,219 @@ +# Rill Deep Code Audit — Executive Summary & Roadmap + +**Date:** 2026-07-19 +**Method:** 24 area-scoped review agents, each followed by an independent adversarial verifier that re-checked every finding against the actual code (removing false positives, fixing severities and `file:line` citations), plus a cross-cutting product-idea synthesis. Static review only — no builds or tests were run. +**Corpus:** ~150k LOC Go (`runtime/`, `admin/`, `cli/`) + ~230k LOC TypeScript/Svelte (`web-common/`, `web-admin/`, `web-local/`). + +Per-area detail lives in the sibling files (see [README.md](./README.md)). This document rolls everything up and categorizes it three ways, as requested: **by severity**, **by priority**, and **new features to build**. + +## Remediation update (2026-07-25) + +- Of the original 27 unique Tier-1 findings (28 witnesses because the cache leak was found twice), **15 are fixed and merged; 12 remain**. +- The all-source pass also includes `REVIEW_FINDINGS_TODO.md` and the later deep-dive audit files. After deduplication, **22 must-fix findings are fixed and 42 remain pending**. +- **24 merged PRs** from the 2026-07-11 through 2026-07-25 window exactly match audit findings. The authoritative pending list and PR mapping are in [../AUDIT_TODO.md](../AUDIT_TODO.md) (re-verified 2026-08-30). +- Counts below are the original audit snapshot and remain useful as corpus/severity totals; they are not decremented when remediation lands. + +--- + +## 1. Headline numbers + +**278 verified findings** across 24 areas. + +| Severity | Count | | Priority | Count | Meaning | +|---|---|---|---|---|---| +| High | 29 | | **P0** | 28 | High severity **and** high confidence — confirmed serious defects, fix now | +| Medium | 90 | | **P1** | 44 | High severity (lower confidence) or high-confidence medium security/data/concurrency — next | +| Low | 159 | | **P2** | 47 | Remaining medium — planned | +| | | | **P3** | 159 | Low — backlog / opportunistic | + +**By category:** correctness 89 · bug 40 · security 39 · product-improvement 34 · concurrency 30 · performance 16 · tech-debt 13 · readability 10 · data-loss 5 · simplification 2. + +**Overall read:** the codebase is fundamentally sound and well-tested in its core (parser, metricsview, reconcilers all landed "fair" with strong test suites). The risk is concentrated in **cross-cutting classes** that recur across many areas — path-traversal sandboxing, security-context cache keys, resource cleanup on error paths, goroutine/lock lifecycle, and stale-async handling in the frontend. Fixing these as *classes* (shared helpers + test harnesses) will retire far more than the individual line items. + +**Areas needing the most attention:** `runtime-core`, `resolvers`, `runtime-server`, `runtime-pkg`, `ai`, `drivers-object-store`, `drivers-connectors-ai`, `admin-billing-provision`, `frontend-dashboard-state` (all rated *needs-attention*). + +--- + +## 2. Cross-cutting themes (the highest-leverage fixes) + +These patterns appear in multiple independent areas. Each is worth a single coordinated fix rather than N scattered ones. + +1. **Path traversal / sandbox escape (security).** The same weakness — building a filesystem path from user/agent input without confining it to the project root — appears in the AI file tools (`runtime/ai/file_read.go`, `file_write.go`, `develop_file.go`), the admin & file repo stores (`runtime/drivers/admin/repo.go`, `runtime/drivers/file/repo.go`), `runtime/pkg/fileutil/fileutil.go:ResolveLocalPath`, and the object-store `path_prefixes` checks (`runtime/drivers/*` — non-boundary prefix match). **One `SecureJoin`-style helper + one root-confinement helper, adopted everywhere, closes the entire class.** + +2. **Security-context-blind cache keys (data leakage).** `runtime/resolver.go:210` builds the query-result cache key without `AdditionalRules`/`SkipChecks`, so results computed under one row-access policy can be served to a different security context. Found independently by the `resolvers` and `runtime-core` agents — it is one bug with two witnesses, and it is the single most dangerous item in the report. + +3. **Missing authorization on data/control endpoints.** `ConnectorService` handlers do no authz at all; the `metrics_annotations` resolver never calls `CanAccess()`; the AI `query_sql` tool runs non-read-only SQL despite advertising `ReadOnlyHint`; magic tokens replay the creator's `admin` flag. A per-service authz test harness would prevent regressions. + +4. **Resource cleanup missing on error paths.** ClickHouse and DuckDB leak DB handles / embedded processes / metric registrations when open partially fails; BigQuery leaks its client on *success*; connector handles opened after context cancellation are never closed. Consistent `defer`-with-rollback on partial-open is the pattern. + +5. **Goroutine / lock lifecycle.** Unbuffered sends under locks and unbounded loops strand goroutines: `logbuffer.AddEntry` deadlocks on a slow subscriber, the AI session send blocks the producer, `DeleteInstance` blocks forever on store-delete failure, `QueryBatch` calls `srv.Send` concurrently, the JWKS bootstrap never breaks on success. The frontend analog is the `updating` lock in `DashboardStateSync` that is never released on two early returns, permanently freezing URL↔state sync. + +6. **Crash-on-valid-input panics.** Unchecked type assertions and nil derefs turn ordinary requests into panics: a bare `value: 2024-01-01` in a component panics the *entire* project parse; `MetricsViewAggregation.Export` panics with no time range; the AI resolver panics when `time_range` is omitted; Pinot `All()` panics on a nil table; `logbuffer.GetLogs` panics when `limit == 0`. None of `runtime/parser`/several drivers have a `recover()`. + +7. **Silent failure & partial-state (data-loss / trust).** Frontend `renameFileArtifact`/`deleteFileArtifact` swallow errors so callers navigate as if they succeeded; `duplicateFileArtifact` overwrites without a collision check; the CLI `DeployProject` pushes `.env` to the *wrong* project after a name collision; editable-deployment deletion discards uncommitted work when the checkpoint push fails; `CreateProject` can orphan a project (and a managed GitHub repo) on partial failure. + +8. **Stale-async in the frontend.** Canvas time-interval derivation and dashboard time-range derivation apply out-of-order async results with no request sequencing; canvas `lastVisitedState` is keyed by canvas *name* not instance, leaking state across projects. + +--- + +## 3. Priority backlog + +### P0 — Original confirmed serious defects (28 witnesses / 27 unique; 15 fixed, 12 pending) + +Grouped by theme. Format: **area** — issue — `location`. + +**Security · path traversal / sandbox escape** +- **ai** — File tools (`file_read`/`file_write`/`develop_file`) allow paths outside the project root — `runtime/ai/file_read.go:52`, `file_write.go:61`, `develop_file.go:59` +- **drivers-connectors-ai** — `RepoStore` file APIs allow path traversal outside the project root — `runtime/drivers/admin/repo.go:257` (+ file repo, `runtime/repos.go:42`) +- ✅ [#9726](https://github.com/rilldata/rill/pull/9726) — **runtime-pkg** — `ResolveLocalPath` sandbox bypass + +**Security · authorization & tenant isolation** +- ✅ [#9704](https://github.com/rilldata/rill/pull/9704) — **resolvers / runtime-core** — security-context-blind query cache key *(one bug, two witnesses)* +- ✅ [#9705](https://github.com/rilldata/rill/pull/9705) — **resolvers** — missing `metrics_annotations` access check +- ✅ [#9700](https://github.com/rilldata/rill/pull/9700) — **runtime-server** — missing `ConnectorService` authorization +- **web-admin** — Open redirect via unvalidated `redirect` query param — `web-admin/src/routes/[organization]/-/upgrade-callback/+page.svelte:34` +- ✅ [#9683](https://github.com/rilldata/rill/pull/9683) — **admin-billing-provision** — clickhouse-static database-name collision + +**Concurrency · deadlocks, goroutine leaks, races** +- **runtime-pkg** — `logbuffer.AddEntry` blocks/deadlocks on a slow subscriber — `runtime/pkg/logbuffer/buffer.go:38-49` +- **runtime-core** — `DeleteInstance` blocks forever when the registry store delete fails — `runtime/registry.go:114-120` +- **ai** — Subscriber send under the session lock strands the producer on cancellation — `runtime/ai/ai.go:898-900` +- ✅ [#9714](https://github.com/rilldata/rill/pull/9714) — **runtime-server** — concurrent `QueryBatch` stream sends (RPC removed) +- ✅ [#9701](https://github.com/rilldata/rill/pull/9701) — **frontend-dashboard-state** — `updating` lock leak +- **admin-billing-provision** — Static runtime slot allocation is a TOCTOU race (slot overcommit) — `admin/provisioner/static/static.go:93-122` + +**Panics on valid input** +- ✅ [#9702](https://github.com/rilldata/rill/pull/9702) — **parser** — component/canvas `value:` panic +- ✅ [#9715](https://github.com/rilldata/rill/pull/9715) — **queries** — aggregation export nil-time-range panic +- ✅ [#9703](https://github.com/rilldata/rill/pull/9703) — **resolvers** — AI resolver nil-time-range panic +- ✅ [#9707](https://github.com/rilldata/rill/pull/9707) — **reconcilers** — non-email alert notifier nil dereference +- **drivers-olap** — Pinot `All()` panics on nil table when any schema fetch fails — `runtime/drivers/pinot/information_schema.go:266-288` +- **runtime-pkg** — `logbuffer.GetLogs` panics (index `-1`) when `limit == 0` — `runtime/pkg/logbuffer/buffer.go:93` + +**Data-loss, leaks & silent failure** +- ✅ [#9699](https://github.com/rilldata/rill/pull/9699) — **cli** — `.env` variables pushed to the wrong project +- ✅ [#9722](https://github.com/rilldata/rill/pull/9722) — **frontend-canvas** — tab groups omitted from PDF export +- **frontend-shared** — `renameFileArtifact`/`deleteFileArtifact` swallow errors; callers treat failure as success — `.../entity-management/actions/actions.ts:206-232` +- **frontend-runtime-client** — Failed chat send loses the user's draft and never rolls back the optimistic message — `.../chat/core/conversation.ts:378` +- ✅ [#9709](https://github.com/rilldata/rill/pull/9709) — **reconcilers** — full rebuild after model rename +- **drivers-object-store** — Redshift `UNLOAD` breaks on any query containing a single quote — `runtime/drivers/redshift/warehouse.go:120` +- ✅ [#9706](https://github.com/rilldata/rill/pull/9706) — **drivers-object-store** — BigQuery client leak + +### P1 — Next (44) + +Full list with `area` and one-line. (Details and `file:line` in each area file.) + +- **admin-auth-rbac** — Magic tokens capture the creator's `admin` flag + custom attributes and replay them +- **admin-database** — Four billing read methods bypass the transaction context +- **admin-projects-deploy** — Unguarded `*proj.PrimaryDeploymentID` deref panics on hibernated/undeployed projects +- **admin-projects-deploy** — Editable deployment deletion discards uncommitted work when checkpoint push fails +- **admin-projects-deploy** — `LookupCanvas` has an inverted state check (NotFound when spec exists; panics) +- **admin-projects-deploy** — `SudoUpdateOrganizationCustomDomain` never propagates to deployments (dead condition) +- **admin-projects-deploy** — `CreateProject` leaves an orphaned project (and possibly managed GitHub repo) on partial failure +- **ai** — `query_sql` executes arbitrary (non-read-only) SQL despite `ReadOnlyHint` +- **cli** — Unsynchronized `pkceAuthenticators` map races between `/auth` and `/auth/callback` +- **cli** — `Helper.Client()/Telemetry()` mutate shared state from concurrent local-server RPCs +- **cli** — Open redirect in the local PKCE auth/logout handlers +- **cli** — Credentials and config in `~/.rill` written world-readable +- **cli** — `ListMatchingProjects` swallows non-inference errors and returns an empty list +- **drivers-connectors-ai** — Successfully-opened handle leaked when the open context is already cancelled +- **drivers-object-store** — `path_prefixes` access scoping bypassed by glob listing and downloads +- **drivers-object-store** — `path_prefixes` enforcement uses non-boundary prefix matches +- **drivers-object-store** — `ResolveLocalPath` root confinement uses a non-boundary prefix check +- **drivers-object-store** — Redshift result pagination fetches with `context.Background()` +- **drivers-object-store** — Athena/Redshift `autoDeleteFileIterator.Close` skips S3 cleanup when inner Close errors +- **drivers-olap** — DuckDB data race on `dbConnCount` in the metrics callback +- **drivers-olap** — ClickHouse `Open` leaks read/write DB handles + embedded server on post-connect failure +- **drivers-olap** — DuckDB `Open` leaks the metrics-callback registration when `reopenDB` fails +- **frontend-canvas** — In-list→Select conversion never clears the in-list marker (discarded `.filter()`) +- **frontend-canvas** — Async time-interval derivation has no request sequencing; stale results overwrite current +- **frontend-canvas** — `lastVisitedState` keyed by canvas name only; leaks state across instances/projects +- **frontend-dashboard-viz** — Big number hides all comparison deltas when the comparison value is exactly 0 +- **frontend-dashboard-viz** — Dimension-table export always sorts by a measure, ignoring "sort by dimension" +- **frontend-runtime-client** — Status-page Tables list not invalidated on reconcile (wrong query keys) +- **frontend-runtime-client** — `removeByName/clear` leave a live abort listener that throws when it later fires +- **frontend-shared** — `waitForResourceReconciliation` compares `stateVersion` strings with `>`, hanging at digit boundaries +- **frontend-shared** — `duplicateFileArtifact` overwrites an existing `(copy)` file with no collision check +- **metricsview** — LIKE→regex conversion does not escape regex metacharacters (Druid ILIKE/search wrong results) +- ✅ [#9724](https://github.com/rilldata/rill/pull/9724) — **parser** — metrics-view annotation validation checked the parent's model/table +- **parser** — Incremental `.env` reparse can drop a real change when multiple `.env` files reparse together +- **plg-first-run** — Splash "Generate sample data" is ungated and can silently dead-end +- **queries** — Millisecond time grain panics timeseries null-fill via unchecked type assertion +- **queries** — Profiling APIs inline caller-supplied SQL expressions (`ColumnTopK.Agg`, column-timeseries) +- ✅ [#9711](https://github.com/rilldata/rill/pull/9711) — **reconcilers** — partition rows leaked on materialized-model deletion +- **reconcilers** — Report retry can re-deliver to notifiers that already succeeded +- **reconcilers** — `markPartitionsExecutedExceptFirst` stops after the first 1000 partitions +- **resolvers** — Built-in `/metrics-sql` API silently ignores its documented `additional_where` +- **runtime-pkg** — Telemetry intake sink uses `http.DefaultClient` with no timeout; `Close` can hang +- **runtime-server** — `OpenAudience` JWKS bootstrap loop never breaks on success, leaking refreshers +- **web-admin** — "View As" falls back to the real admin's permissions while mocked permissions load + +### P2 (47) and P3 (159) + +Planned / backlog. Enumerated in full within each area file. The P2 set is mostly medium-confidence correctness and product-robustness gaps; P3 is low-severity polish, readability, dead-code removal, and defensive hardening. + +--- + +## 4. New features to build + +The full, themed catalog is in **[product-ideas.md](./product-ideas.md)** — **55 synthesized ideas across 10 themes** (plus 144 area-specific ideas embedded in the individual reports). Highlights below. + +### Standout bets (marked by the synthesis) + +| Theme | Idea | Effort | +|---|---|---| +| Onboarding & PLG | One-click "aha": seeded datasets + offline sample-data generator | M | +| Data & Ingestion | Guaranteed-clean connector test-drive (test + preview before import) | M | +| Data & Ingestion | Unified object-store access-policy boundary | M | +| Metrics Layer | Ratio / "per"-dimension derived measures | L | +| Metrics Layer | Structured query-validation surface | M | +| Dashboarding | Deterministic dashboard state-sync engine | M | +| Dashboarding | Complete + tab-aware canvas export | M | +| AI / NL Analytics | Sandboxed AI: read-only introspection role + project-root jail | M | +| AI / NL Analytics | "Fix with AI" recovery, standardized everywhere | M | +| AI / NL Analytics | Scheduled AI narrative reports | M | +| Collaboration | Short share links via server-side state tokens | XL | +| Collaboration | Scoped magic tokens + origin-pinned embeds | M | +| Performance | Streaming / chunked exports | L | +| Performance | Security-aware cache keys + a correctness harness | M | +| Dev Experience | Reversible file operations: trash/undo + multi-select + conflict dialog | M | +| Dev Experience | `rill deploy --dry-run` + named profiles + CI login | M | +| Governance | One `SecureJoin` helper to kill the path-traversal class | S | +| Governance | Per-service authz test harness | S | +| Monetization | Post-deploy → share growth loop | S | +| Monetization | Per-session AI cost budget + usage-based metering | M | +| Monetization | Customer-facing usage & consumption dashboard | M | + +Several standout bets (security-aware cache keys, sandboxed AI, tab-aware canvas export, deterministic state-sync, `SecureJoin`, authz harness) **double as the fix for a P0/P1 class** — building the feature retires the bug. Prioritize those. + +--- + +## 5. PLG & first-user-experience + +Full report: **[plg-first-user-experience.md](./plg-first-user-experience.md)** (and the agent's extra brainstorming in `plg_improvement_ideas.md`). + +**Friction found in the first-run funnel (`rill start` → sample/import → auto-generated dashboard → deploy/share):** +- Splash "Generate sample data" is **ungated** and silently dead-ends if the developer agent can't start (P1). +- "Generate dashboard with AI" can **spin forever** on a hard backend error; example/blank unpack failures are **swallowed with no feedback**. +- Local example selection blocks on a **fixed 5-second `setTimeout`** then hard-reloads. +- `/deploy?org=` redirects to a **non-existent route (404)** — broken share/deploy funnel. +- Every "add data" run generates **four resources** (model + metrics view + explore + canvas) per source — noisy for a first project. +- Auto-generated metrics view can yield a **dimension-less dashboard** with no warning; welcome examples are **hardcoded in the frontend** instead of using `ListExamples`. + +**Top PLG features (activation-focused):** offline/deterministic sample-data generator · one-click seeded datasets on the splash · reconciliation-driven first-dashboard progress bar with skip · guided onboarding checklist · test-connection + table-preview before import · **post-deploy share funnel** + CLI "deploy to share" nudge · first-run activation-funnel instrumentation. + +--- + +## 6. Suggested sequencing + +**Now (this cycle) — P0 + the cheap class-killers.** +Ship the `SecureJoin` + root-confinement helpers (retires 6+ path-traversal findings), fix the security-context cache key (`runtime/resolver.go:210`) and add the security-aware cache-key harness, add `ConnectorService`/annotation authz, and clear the panic and deadlock P0s (parser, logbuffer, `DeleteInstance`, `QueryBatch`, `DashboardStateSync` lock). Fix the CLI wrong-project `.env` push and the frontend error-swallowing. + +**Next — P1 + PLG activation.** +Driver resource-leak cleanups, `path_prefixes` boundary enforcement, magic-token scope fix, editable-deployment checkpoint safety, `CreateProject` rollback. In parallel, ship the PLG activation set (seeded datasets, first-dashboard progress, fix `/deploy` 404, connector test-drive) and the post-deploy share loop. + +**Later — P2/P3 + bigger bets.** +Structured query-validation surface, streaming exports, ratio measures, short share links, customer-facing usage dashboard, and the dead-code / readability cleanup. + +--- +*Generated by a multi-agent code audit (find → adversarially verify → synthesize). Every P0/P1 was independently re-checked against the source before inclusion.* diff --git a/audit/COMPETITORS.md b/audit/COMPETITORS.md new file mode 100644 index 000000000000..8e0f82c25f5b --- /dev/null +++ b/audit/COMPETITORS.md @@ -0,0 +1,37 @@ +# Rill Competitive Landscape — Audit Index & Triage (Aug 2026) + +Full audits follow a common structure per competitor: research file(s), an honest current-state Rill inventory, a feature-by-feature comparison matrix (✅/🟡/❌/➕), and a phased competitive roadmap. Shared roadmap items are cross-marked (♻) so investments that win multiple fights are visible. + +## Completed audits + +| Directory | Competitor | Why they matter to Rill | +|---|---|---| +| [`omni/`](omni/) | **Omni** | Fastest-rising direct rival: Looker-lineage semantic BI + workbooks + AI ops suite + Explo-acquired embedded; $120M Series C at $1.5B (Apr 2026). The best-funded "governance + finished interface" competitor | +| [`cube/`](cube/) | **Cube** | Coined "agentic analytics" (D3 → GA Oct 2025); universal semantic layer + Semantic SQL + full AI-ops loop (skills/rules/evals); collides with Rill in embedded + agent-grounding deals | +| [`quicksight/`](quicksight/) | **AWS QuickSight / Amazon Quick** | The procurement-gravity incumbent in AWS shops ($3 readers, EDP, compliance); pivoted to an agentic workspace (Oct 2025), vacating the fast-governed-dashboards position | + +| [`sigma/`](sigma/) | **Sigma** | The momentum leader ($200M ARR, $3B Series E May 2026); spreadsheet self-service + writeback/data apps + Sigma Agents; its live-warehouse architecture makes the customer's compute bill its Achilles' heel | +| [`looker/`](looker/) | **Google Looker** | Incumbent code-first semantic BI (LookML + git) + Gemini CA GA/CA API/managed MCP; simultaneously Rill's biggest migration *source* (Omni/Lightdash monetize the wave today) and a Google-gravity rival | +| [`thoughtspot/`](thoughtspot/) | **ThoughtSpot** | AI-BI incumbent (Gartner Leader 2025/2026, Spotter everywhere) with public wounds: 54.67% runQL accuracy, credit bill-surprise, $92.5K median contracts, SpotCache conceding live-query's limits | +| [`hex/`](hex/) | **Hex** | The most complete AI-ops stack shipping (Context Studio, Evals + public DataBench benchmark, MCP both ways, memory); no RLS engine, no data plane, Enterprise-gated embedding | +| [`metabase/`](metabase/) | **Metabase** | The default OSS/cheap embedded choice — now shipping MCP/Slack/BYO-model AI + git sync; no engine (scale is complaint #1), RLS/SSO paywalled. Rill = the graduation path | +| [`tinybird/`](tinybird/) | **Tinybird** | Most architecturally-kindred: managed ClickHouse + SQL-as-REST-APIs, local-first, MCP-native; no semantic layer or BI surface; exposes Rill's streaming-ingestion gap; squeezed by ClickHouse Inc. | + +## Considered, deferred (revisit on deal-signal) + +- **Superset / Preset** — overlaps Metabase's slot (OSS default) with a heavier ops burden; Metabase audit covers the objection pattern. Defer unless Preset shows up in deals. +- **Lightdash** — philosophically closest OSS "BI-as-code on dbt" rival, but small (~$11M raised); watch, and fold into a dbt-ecosystem note if it grows. +- **Grafana** — the incumbent for ops dashboards; competes in observability-adjacent operational analytics. Defer: different buyer center (SRE), meets Rill mostly in IoT/infra verticals. +- **Databricks AI/BI (Genie) & Snowflake (Cortex Analyst / Semantic Views)** — platform-native gravity, covered as landscape pressure in the cube audit §6; a dedicated "platform-native BI" audit is worth doing if warehouse-direct mode becomes a sales motion. +- **Holistics, GoodData, Luzmo, Embeddable, Explo (†Omni), Hashboard** — embedded/as-code niche players; individually below audit threshold. +- **Zenlytic, TextQL, Dot, Querio** — AI-analyst startups; collectively commoditize "chat with governed data" (see cube audit §6) but individually small. +- **Power BI / Tableau** — incumbent giants; Rill rarely competes head-on for enterprise-wide BI standardization. The relevant surface (Microsoft-estate interop) is addressed in the cube roadmap (DAX/Excel decisions). + +## Cross-cutting themes (across all nine audits) + +1. **Everyone converged on "agentic analytics"** — Cube coined it, Gartner blessed it (2026 Market Guide + Hype Cycle), AWS rebuilt around it, Omni/Hex/Sigma productized AI ops, ThoughtSpot ships four named agents, even Metabase has MCP + Slack + AI governance. Rill's agent *architecture* is competitive or ahead; its *packaging* lags everyone — the shared Phase-1 investment in every roadmap. +2. **The evidence race is on**: Hex published DataBench; Tinybird runs a public LLM-SQL benchmark; Cube ships CI-gateable evals; Google claims "errors cut two-thirds"; ThoughtSpot's public 54.67% shows what happens without evidence. **A published accuracy benchmark + customer evals is the single highest-leverage shared item** — it reframes bake-offs against six of nine competitors at once. +3. **Recurring Rill gaps** (frequency-ranked across audits): customer evals/benchmark (all 9) · Slack agent (8) · semantic joins/multi-fact (7) · SCIM/audit (7) · maps + chart breadth (6) · viewer-side calcs (5) · embed React SDK + chat API (5) · outbound MCP client (4) · Python/forecasting agent tool (4) · delivery destinations (4) · cloud SQL console (4) · Kafka/streaming ingestion (3, decisive vs Tinybird) · paginated/report layouts (3) · drill-to-records (3). +4. **Recurring Rill advantages**: full data plane (ingestion→OLAP→BI) at fixed cost — the direct counter to Sigma/Looker/ThoughtSpot/Metabase's warehouse-bound architectures; one governed semantic layer grounding humans and agents (vs Topics/coaching/glossary parallel artifacts); write-capable MCP + git-native agent buildability; OSS completeness (only Metabase/Tinybird/Cube are partially comparable, all gate more); pricing simplicity; per-recipient-security AI reports (no one matches). +5. **Migration/graduation plays** are the cheapest offense: LookML converter (Looker wave, contested by Omni/Lightdash), QuickSight JSON importer (rebrand churn + AI fee), Metabase importer (scale graduation), Cube-model importer (OSS users watching Cloud-only AI), Tinybird guide (Classic sunset Sept 15, 2026). +6. **Platform gravity is the common enemy**: AWS EDP, GCP commits, Snowflake/Databricks native semantics squeeze *every* independent — marketplace listings (AWS, GCP) and BYO-engine posture (ClickHouse/MotherDuck alignment) are Rill's counters, and they hurt no other fight. diff --git a/audit/README.md b/audit/README.md new file mode 100644 index 000000000000..c2237de045c9 --- /dev/null +++ b/audit/README.md @@ -0,0 +1,93 @@ +# Rill Deep Code Audit + +**Date:** 2026-07-19 +**Scope:** whole repository — `runtime/`, `admin/`, `cli/` (Go) and `web-common/`, `web-admin/`, `web-local/` (TypeScript/Svelte). +**Method:** 24 area-scoped review agents run one at a time, each followed by an independent **adversarial verifier** that re-opened every cited line, tried to refute the finding, removed false positives, and corrected severities/locations. A final synthesis pass produced the cross-cutting product-idea catalog. Static review only — no builds or tests were executed. + +## Start here + +- **[../AUDIT_TODO.md](../AUDIT_TODO.md)** — the current consolidated pending list (110 findings: 40 must-fix, 64 medium, 6 low), re-verified item by item against `main` on 2026-08-30. It supersedes the old `MUST-FIX.md` and root `REVIEW_FINDINGS_TODO.md` (both removed; MF ids and the merged-PR register are carried over). Start here if you only read one file. +- **[verified/](./verified/README.md)** — the exhaustive per-source classification of all 506 findings (2026-07-31 snapshot), including P2/P3 long-tail queues and product-idea backlogs. +- **[00-summary.md](./00-summary.md)** — executive roll-up: findings **by severity**, **by priority (P0–P3)**, the cross-cutting themes, the consolidated feature list, PLG highlights, and a suggested Now/Next/Later roadmap. +- **[product-ideas.md](./product-ideas.md)** — 55 synthesized product/feature ideas across 10 themes, with effort ratings, quick wins, and bigger bets. +- **[plg-first-user-experience.md](./plg-first-user-experience.md)** — the first-run / product-led-growth review (funnel friction + activation features). Supplementary brainstorm in `plg_improvement_ideas.md`. + +## Later focused reviews + +- **[user-management.md](./user-management.md)** (2026-08-10) — user, usergroup, org/project membership and invite management across `admin/`, `cli/` and the `web-admin` user-management UI. 43 findings (6 High · 20 Medium · 17 Low); top risks are member attributes overriding the reserved runtime JWT keys, an unguarded nil dereference in `SetProjectMemberUsergroupRole`, account deletion orphaning organizations, and cache invalidation that never matches the infinite queries the UI renders. Remediation sequencing in **[user-management-fix-plan.md](./user-management-fix-plan.md)**. + +## Remediation status (2026-08-30) + +- 25 PRs merged 2026-07-11 through 2026-07-31 exactly resolved audit findings (register preserved in [../AUDIT_TODO.md](../AUDIT_TODO.md)). +- The 42 PRs merged 2026-07-31 through 2026-08-30 resolved **zero** of the pending findings; every pending item was individually re-verified against current code on 2026-08-30 and line numbers refreshed. See [../AUDIT_TODO.md](../AUDIT_TODO.md) for the deduplicated inventory. +- The totals below remain the original 2026-07-19 audit snapshot; they are not reduced when a finding is fixed. Individual source findings now carry explicit merged-PR status where applicable. +- Supplemental deep dives included in the all-source pass: canvas, pivot, state management, time-dimension detail, connectors, data security, Metrics SQL, SQL aggregation, AI performance, cloud deploy, and leaderboards. Findings explicitly tagged `Must-fix: no` remain in those reports but are excluded from the ship-blocker count. + +## Totals + +**278 findings** — **29 High · 90 Medium · 159 Low**. Priority: **P0 28 · P1 44 · P2 47 · P3 159**. +Categories: correctness 89 · bug 40 · security 39 · product-improvement 34 · concurrency 30 · performance 16 · tech-debt 13 · readability 10 · data-loss 5 · simplification 2. + +## Area reports + +Counts are **High / Medium / Low**. "Health" is the reviewing agent's overall rating after verification. + +### Runtime (data plane) + +| Area | Report | Health | H/M/L | Top risk | +|---|---|---|---|---| +| Runtime Parser | [parser.md](./parser.md) | fair | 1 / 2 / 7 | Component `value:` panics the whole project parse | +| Reconcilers | [reconcilers.md](./reconcilers.md) | fair | 2 / 5 / 4 | Alert via non-email notifier nil-derefs `adminMeta` | +| Runtime Core (controller/caches/security) | [runtime-core.md](./runtime-core.md) | needs-attention | 2 / 1 / 7 | Resolver cache key omits `AdditionalRules` → data leak | +| Metrics View Engine | [metricsview.md](./metricsview.md) | fair | 0 / 6 / 2 | LIKE→regex doesn't escape metacharacters | +| Resolvers | [resolvers.md](./resolvers.md) | needs-attention | 3 / 2 / 3 | `metrics_annotations` skips `CanAccess()` | +| Legacy Queries | [queries.md](./queries.md) | fair | 1 / 4 / 7 | `MetricsViewAggregation.Export` panics with no time range | +| Runtime Server + Auth | [runtime-server.md](./runtime-server.md) | needs-attention | 2 / 4 / 5 | `ConnectorService` handlers do no authorization | +| AI Assistant / Agents | [ai.md](./ai.md) | needs-attention | 2 / 4 / 7 | File tools allow path traversal outside project root | +| Runtime Shared Utilities | [runtime-pkg.md](./runtime-pkg.md) | needs-attention | 3 / 3 / 6 | `ResolveLocalPath` sandbox bypassable | + +### Drivers + +| Area | Report | Health | H/M/L | Top risk | +|---|---|---|---|---| +| OLAP Drivers | [drivers-olap.md](./drivers-olap.md) | fair | 1 / 6 / 10 | Pinot `All()` panics on nil table | +| Object Store & Warehouse Drivers | [drivers-object-store.md](./drivers-object-store.md) | needs-attention | 2 / 11 / 3 | Redshift `UNLOAD` breaks on a single quote; `path_prefixes` bypass | +| Connector Framework & AI/Notifier Drivers | [drivers-connectors-ai.md](./drivers-connectors-ai.md) | needs-attention | 1 / 4 / 6 | `RepoStore` file APIs allow path traversal | + +### Admin (control plane) + +| Area | Report | Health | H/M/L | Top risk | +|---|---|---|---|---| +| Admin Auth & RBAC | [admin-auth-rbac.md](./admin-auth-rbac.md) | fair | 0 / 1 / 12 | Magic tokens replay creator's `admin` flag | +| Admin Projects & Deployments | [admin-projects-deploy.md](./admin-projects-deploy.md) | fair | 0 / 7 / 5 | Editable-deploy delete discards uncommitted work on push fail | +| Admin Billing, Provisioners & Jobs | [admin-billing-provision.md](./admin-billing-provision.md) | needs-attention | 2 / 2 / 8 | clickhouse-static DB-name collision (cross-tenant) | +| Admin Database Layer | [admin-database.md](./admin-database.md) | fair | 0 / 2 / 7 | Billing reads bypass the transaction context | + +### CLI + +| Area | Report | Health | H/M/L | Top risk | +|---|---|---|---|---| +| CLI & Local App | [cli.md](./cli.md) | fair | 1 / 5 / 8 | `DeployProject` pushes `.env` to the wrong project on name collision | + +### Frontend + +| Area | Report | Health | H/M/L | Top risk | +|---|---|---|---|---| +| Dashboard State Management | [frontend-dashboard-state.md](./frontend-dashboard-state.md) | needs-attention | 1 / 1 / 10 | `updating` lock never released → state sync frozen | +| Dashboard Visualizations | [frontend-dashboard-viz.md](./frontend-dashboard-viz.md) | fair | 0 / 3 / 9 | Big number hides deltas when comparison value is 0 | +| Canvas Dashboards | [frontend-canvas.md](./frontend-canvas.md) | fair | 1 / 4 / 5 | PDF export omits all tab-group content | +| Runtime Client, SSE & Chat | [frontend-runtime-client.md](./frontend-runtime-client.md) | fair | 1 / 3 / 7 | Failed chat send loses the user's draft | +| Web Admin (Cloud Frontend) | [web-admin.md](./web-admin.md) | fair | 1 / 2 / 8 | Open redirect via `redirect` query param | +| Shared Frontend Features | [frontend-shared.md](./frontend-shared.md) | fair | 1 / 3 / 7 | File rename/delete swallow errors (callers treat as success) | + +### Product + +| Area | Report | Health | H/M/L | Top risk | +|---|---|---|---|---| +| PLG & First-User Experience | [plg-first-user-experience.md](./plg-first-user-experience.md) | fair | 1 / 5 / 6 | Splash "Generate sample data" ungated, silently dead-ends | + +## How to read a finding + +Each area report lists findings most-severe-first with: **Category · Confidence · Location (`file:line`)**, the problem, a concrete failure scenario, and a recommended fix. A **Verification Notes** section at the end of each file records what the adversarial verifier removed or corrected (e.g. `frontend-shared` had one theme-CSS-injection finding removed as unreachable dead code). + +**Severity** = impact if it triggers. **Confidence** = how sure the (verified) finding is real. **Priority** in the summary is derived as: P0 = High+High-confidence; P1 = other High, or High-confidence Medium in security/data-loss/concurrency/correctness; P2 = remaining Medium; P3 = Low. diff --git a/audit/admin-auth-rbac.md b/audit/admin-auth-rbac.md new file mode 100644 index 000000000000..c9f072bcee2f --- /dev/null +++ b/audit/admin-auth-rbac.md @@ -0,0 +1,223 @@ +# Admin Auth & RBAC — Code Review + +**Scope:** `admin/server/auth/{auth,claims,device_code,handlers,middleware,mcp_oauth,pkce}.go`, `admin/server/{roles,users,usergroups,magic_tokens,runtime_jwt,runtime_proxy,sudo,page_token}.go`, `admin/server/cookies/cookies.go`, `admin/{permissions,auth_token,auth_code,user}.go`, plus supporting `admin/server/server.go` (cookie/JWT helpers), `admin/pkg/authtoken` | **Health:** fair + +## Overview + +This area implements the cloud control plane's authentication (Auth0/OIDC login, device code, PKCE authorization code, refresh tokens, magic tokens), the token model (`authtoken`), session cookies, RBAC permission composition (org/project roles), superuser/sudo, runtime JWT minting, and the runtime reverse proxy. The overall structure is sound: permissions are composed by OR-union of roles, tokens are stored as SHA-256 hashes, redirect URLs are validated against an allow-list on the main login/logout paths, cookies are `HttpOnly`/`SameSite`, PKCE is S256-only with single-use codes that are deleted before validation, and the auth endpoints are rate-limited. + +After adversarial verification, the most substantive issue is the magic-token attribute capture (admin-auth-rbac-03): a shareable/embeddable magic link inherits the creating admin's `admin: true` attribute and custom attributes and replays them into the runtime JWT, which can subvert attribute-based row/field security policies. The remaining findings are lower-severity correctness, defense-in-depth, and hardening items. Several findings that the prior reviewer rated medium are latent rather than presently exploitable (per-request claims are not cached across requests, and the shipped roles couple prod/dev), and have been downgraded accordingly. + +## Findings + +### admin-auth-rbac-03 [MEDIUM] Magic tokens capture the creator's `admin` flag and custom attributes and replay them into the runtime JWT +- **Category:** security **Confidence:** high **Location:** `admin/server/magic_tokens.go:90-100` (capture), `admin/server/server.go:380-386` (`jwtAttributesForUser` sets `"admin": projectPermissions.ManageProject`), `admin/server/runtime_jwt.go:113-119` (replay: `attr = mdl.Attributes`) +- **Problem:** When a project admin/editor issues a magic token, `jwtAttributesForUser` is invoked with the creator's live project permissions (`projPerms` from `magic_tokens.go:45`), so the stored attribute map contains `admin: true` (because `ManageProject` is true for admins/editors) plus all of the creator's custom org-member attributes. When the magic token is later used, `issueRuntimeToken` sets the runtime JWT attributes directly from `mdl.Attributes`, so the JWT carries `admin: true`. The resource allow-list in `securityRulesFromMagicAuthToken` restricts *which resources* are reachable but does not neutralize attribute-based row/field security policies. The code comments (`magic_tokens.go:93-94`) explicitly acknowledge this risk. +- **Failure scenario:** A metrics view uses a security policy gated on `{{ .user.admin }}` (a documented Rill pattern for row-level security) or on a custom attribute. An admin creates a shareable magic link (often embedded in an iframe or sent to external viewers). Anyone holding that link inherits `admin: true` (and the admin's custom attributes) and therefore sees unfiltered rows/fields the policy intended to hide from non-admins. +- **Recommendation:** Strip or force `admin: false` (and drop privilege-bearing custom attributes) when capturing attributes for a magic token, or compute magic-token attributes from an explicitly non-admin permission set rather than the creator's live permissions. + +**Verification:** CONFIRMED — the capture→store→replay chain is intact: `magic_tokens.go:95` calls `jwtAttributesForUser(..., projPerms)`, which sets `"admin": projectPermissions.ManageProject` (`server.go:385`) plus all custom attributes; the map is persisted (`InsertMagicAuthToken` at `auth_token.go:207-221`) and replayed verbatim as `attr = mdl.Attributes` in `runtime_jwt.go:119`, with no admin-stripping anywhere. Note the creator must have `ManageProject=true` (project admin role) for `admin:true` to be captured. + +**Manual Reproduction Steps (for QA):** +1. In a Rill Cloud project, add a metrics view with a security policy that gates row or field access on the user attribute `admin` (for example, only show a sensitive dimension/rows when `{{ .user.admin }}` is true). +2. Log in as a user with the project `admin` role and open a dashboard built on that metrics view. Confirm you see the admin-only rows/fields. +3. As that admin, create a shareable magic link for the dashboard (the "Share" / public URL / embed link feature that issues a magic auth token). +4. Open the magic link in a private/incognito window (no login), or hand it to a non-admin colleague. +5. Observe that the dashboard opened via the magic link shows the admin-only rows/fields that the security policy was meant to hide from non-admins — confirming the link inherited `admin: true`. + +### admin-auth-rbac-01 [LOW] Handlers mutate the shared cached permission objects returned by `Claims` +- **Category:** security **Confidence:** high **Location:** `admin/server/auth/claims.go:201-242` (and `:246-279`); mutating callers at `admin/server/runtime_proxy.go:83-84`, `admin/server/projects.go:287-300`, `admin/server/organizations.go:75-77`, `admin/server/bookmarks.go:58-60,88` +- **Problem:** `authTokenClaims.ProjectPermissions` and `organizationPermissionsUnsafe` cache and return the *same* `*adminv1.ProjectPermissions` / `*adminv1.OrganizationPermissions` pointer they store in `projectPermissionsCache` / `orgPermissionsCache`. Several handlers take that pointer and write to it (`permissions.ReadProject = true`, `perms.Guest = true`, etc.) to apply public-project / superuser-force elevation. Every write persists into the claims cache, and the mutation happens without holding the claims mutex the getters otherwise use. +- **Failure scenario:** Not directly exploitable today: `newAuthTokenClaims` is constructed fresh per request in `middleware.go:201`, so the blast radius is a single request, and the flags mutated (public/force read + guest) are not re-read for an authorization decision later in the same handler. It is a latent privilege-escalation footgun (if the `Claims` wrapper is ever memoized across requests, an anonymous hit on a public project would leave `ReadProd`/`ReadProject` flipped true in the cached object) and a latent data race if a streaming handler ever touches claims from two goroutines. +- **Recommendation:** Have the getters return a defensive copy (e.g. `proto.Clone`) of the cached permissions, or construct the public/force elevation as a locally-owned permission object instead of writing through the returned pointer. + +**Verification:** PLAUSIBLE — `ProjectPermissions` returns the same cached pointer (`claims.go:205-207,240-241`) and callers write through it (`runtime_proxy.go:83-84`, `projects.go:290-300`, `organizations.go:75`, `bookmarks.go:59-60`), but claims are built fresh per request (`middleware.go:201` `newAuthTokenClaims`), so it is a latent footgun/race rather than a present exploit as the finding itself concedes. + +**Manual Reproduction Steps (for QA):** +Not user-reproducible today — the mutation is confined to a single request and no user-facing decision re-reads the flipped flag. Confirm in code: `admin/server/auth/claims.go:205-207` and `:240-241` return the cached `*adminv1.ProjectPermissions` pointer directly; then `admin/server/runtime_proxy.go:83-84` and `admin/server/projects.go:290-300` write `permissions.ReadProd = true` etc. through that shared pointer. Verify no `proto.Clone`/copy sits between the getter and the writes. + +### admin-auth-rbac-02 [LOW] Revoked / logged-out / rotated tokens stay valid for up to 10s (cache is never evicted on revoke) +- **Category:** security **Confidence:** high **Location:** `admin/auth_token.go:274-312` (cache), `admin/auth_token.go:249-267` (`RevokeAuthToken`); revoke call sites in `admin/server/users.go:335,363,456`, `admin/server/magic_tokens.go:252`, `admin/server/auth/handlers.go:366,426,435,537,569`, `admin/server/auth/pkce.go:371` +- **Problem:** `ValidateAuthToken` caches successful validations (keyed by SHA-256 of the token) for `_authCacheTTL = 10s`. `PurgeAuthTokenCache` exists to flush that cache but is called only from tests (`admin/server/users_test.go:39,51`), never from any production revocation path — every revoke path (`RevokeAuthToken`, `DeleteUserAuthToken`, `DeleteAllUserAuthTokens`, magic-token revoke, logout, refresh-token rotation) only deletes the DB row. That the tests must manually purge the cache to observe revocation confirms the gap. +- **Failure scenario:** A user (or admin) revokes a leaked token, logs out, or calls "revoke all sessions" after a compromise. The stolen token continues to authenticate successfully for up to 10 seconds on any admin replica that has it cached, because validation short-circuits on the cache before hitting the DB. Impact is bounded (≤10s, per-replica, and only where the token was recently used) but the revocation control is not immediate. +- **Recommendation:** On any revoke/delete, evict the specific token from `s.authCache` (add a `Remove(hash)` helper keyed like `ValidateAuthToken`) or call `PurgeAuthTokenCache`. At minimum, do not serve a cache hit for a token deleted in the same flow (e.g. refresh-token rotation). + +**Verification:** CONFIRMED — `ValidateAuthToken` caches successful validations for `_authCacheTTL` (`auth_token.go:288-312`); `PurgeAuthTokenCache` (`auth_token.go:269-272`) is called only from `users_test.go:39,51` (grep confirms zero production call sites), and `RevokeAuthToken` (`auth_token.go:249-267`) only deletes the DB row without touching the cache. + +**Manual Reproduction Steps (for QA):** +1. Create a Rill service token (or personal access token) via CLI/UI and note the token string. +2. Make an authenticated admin API call with the token (e.g. `curl -H "Authorization: Bearer " /v1/users/me` or any endpoint) and confirm it succeeds — this populates the 10s validation cache. +3. Immediately revoke/delete that same token (CLI `rill token revoke`, or the UI "Delete token" / "Revoke" action). +4. Within ~10 seconds, repeat the same authenticated API call with the revoked token against the same admin replica. +5. Observe the call still succeeds (200) for up to 10 seconds after revocation, instead of returning 401 immediately. + +### admin-auth-rbac-04 [LOW] Runtime proxy gates every deployment (prod, dev, branch) on `ReadProd`, and public projects expose branch deployments anonymously +- **Category:** security **Confidence:** low **Location:** `admin/server/runtime_proxy.go:41-93`; branch route at `admin/server/server.go:221` +- **Problem:** The proxy resolves the primary deployment or a branch deployment (`FindDeploymentsForProject(..., branch)`) and then gates access solely on `permissions.ReadProd` (after forcing `ReadProd = true` for `proj.Public`). It never consults `ReadDev` even when the resolved deployment runs in the `dev` environment. The issued runtime JWT always grants the base read permissions (`ReadAPI/ReadMetrics/ReadObjects/UseAI`) regardless of environment (only the *elevated* `ReadInstance`/`Manage*` permissions in `runtime_jwt.go:178-187` are environment-aware). +- **Failure scenario:** For a public project, the `/branch/{branch}/runtime/...` route forces `ReadProd = true` for anonymous callers and then serves the branch (potentially in-development) deployment's data anonymously — broader than the "public prod dashboard" intent. Note: the parallel "a custom role granting `ReadProd` but not `ReadDev` reaches dev" concern is **not reachable today** — the three shipped project roles (admin/collaborator/viewer, `migrations/0003.sql:40-42`) all grant `read_prod` and `read_dev` together, and roles are not user-customizable — so this reduces to the public-project branch-exposure question, which is partly a design choice (a public project arguably exposes all its deployments). +- **Recommendation:** Select the permission to check based on `depl.Environment` (`ReadProd` for prod, `ReadDev` for dev/branch), and decide explicitly whether public projects should expose non-primary/branch deployments at all. + +**Verification:** CONFIRMED — the proxy resolves a branch deployment (`runtime_proxy.go:52-61`) and gates solely on `permissions.ReadProd` after forcing `ReadProd=true` for `proj.Public` (`runtime_proxy.go:82-93`), never consulting `ReadDev`/environment; the branch route exists at `server.go:221`. The "custom role" escalation is correctly ruled out — `migrations/0003.sql:40-42` shows all three built-in roles couple `read_prod` and `read_dev`. + +**Manual Reproduction Steps (for QA):** +1. Create a Rill Cloud project and mark it Public. +2. Push a non-primary branch that produces a separate (e.g. dev/in-development) branch deployment for that project. +3. In an incognito window with no authentication, request the branch runtime proxy route: `curl /v1/orgs/{org}/projects/{project}/branch/{branch}/runtime/v1/instances/.../`. +4. Observe the anonymous request is served the branch deployment's data (200) rather than being restricted to the primary/prod deployment. + +### admin-auth-rbac-13 [LOW] `CookieRefreshMiddleware` logs the user out on any token-validation error, including transient ones +- **Category:** product-improvement **Confidence:** high **Location:** `admin/server/auth/middleware.go:102-112` +- **Problem:** On every request carrying a session cookie, `CookieRefreshMiddleware` calls `ValidateAuthToken` and, on *any* error, deletes `cookieFieldAccessToken` from the session and saves the cookie. The comment acknowledges the error "can be due to expiry or transient context issues," yet treats all of them as a reason to clear the session. Combined with admin-auth-rbac-07 (transient DB errors are negatively cached for up to 10s), a brief admin-DB blip evicts a valid browser session and forces a re-login. +- **Failure scenario:** The admin DB has a transient hiccup while a logged-in user is browsing. `ValidateAuthToken` returns a non-context error, the middleware wipes the auth cookie, and the user is silently logged out even though their token is valid. +- **Recommendation:** Only clear the cookie when the token is definitively invalid (expired, not found, hash mismatch). On transient/infrastructure errors, leave the cookie intact and continue. + +**Verification:** CONFIRMED — `CookieRefreshMiddleware` deletes `cookieFieldAccessToken` on *any* non-nil error from `ValidateAuthToken` (`middleware.go:102-107`), with no distinction between definitive-invalid and transient errors; the comment at `:104` acknowledges the error "can be due to expiry or transient context issues." + +**Manual Reproduction Steps (for QA):** +1. Log in to Rill Cloud in a browser so a valid session cookie is set. +2. In a controlled/staging environment, induce a transient admin-DB failure (e.g. briefly stop or firewall the admin Postgres, or use a fault-injection proxy) while the session is still valid. +3. Reload any authenticated Rill Cloud page during the outage so the request passes through `CookieRefreshMiddleware`. +4. Restore the DB and reload again. +5. Observe you have been logged out (redirected to login) even though the token had not expired — confirming a transient error wiped the cookie. (If DB fault injection is not feasible, confirm in code at `admin/server/auth/middleware.go:102-107`.) + +### admin-auth-rbac-07 [LOW] `ValidateAuthToken` negatively caches transient errors, rejecting valid tokens for up to 10s +- **Category:** correctness **Confidence:** high **Location:** `admin/auth_token.go:298-311` +- **Problem:** After a cache miss, any non-context error from `validateAuthTokenUncached` is cached alongside the (nil) token for `_authCacheTTL`. Only errors matching `ctx.Err()` bypass caching; a transient DB error with a live context (`err != nil && errors.Is(err, nil)` is false) falls through and is memoized for 10s. +- **Failure scenario:** The admin DB briefly becomes unavailable while validating a token. The failure is cached under that token's hash; even after the DB recovers, every request presenting that exact token is rejected for up to 10 seconds instead of being re-validated. (This is the root cause behind admin-auth-rbac-13's transient logout.) +- **Recommendation:** Only cache definitive negative results (malformed token, not found, expired, hash mismatch). Do not cache infrastructure/transient errors. + +**Verification:** CONFIRMED — after a cache miss, `ValidateAuthToken` only bypasses caching when `errors.Is(err, ctx.Err())` (`auth_token.go:300`); every other error, including transient DB errors, is stored via `s.authCache.Add(cacheKey, authCacheEntry{token, err, ...})` (`auth_token.go:304-309`) and returned for the remaining TTL. + +**Manual Reproduction Steps (for QA):** +1. In a controlled/staging environment, obtain a valid token and prime a failure: induce a transient admin-DB error (stop/firewall Postgres or use a fault-injection proxy). +2. Make an authenticated API call with the valid token during the outage so the failed validation is cached: `curl -H "Authorization: Bearer " /v1/users/me` (expect an error). +3. Immediately restore the DB. +4. Within ~10 seconds, repeat the same call with the same valid token against the same replica. +5. Observe it is still rejected for up to 10 seconds even though the DB has recovered and the token is valid. (If fault injection is not feasible, confirm in code at `admin/auth_token.go:298-311`.) + +### admin-auth-rbac-05 [LOW] Missing `return` after redirecting anonymous users in `handleAuthorizeRequest` +- **Category:** bug **Confidence:** high **Location:** `admin/server/auth/handlers.go:657-666` +- **Problem:** When `claims.OwnerType() == OwnerTypeAnon`, the handler calls `http.Redirect(...)` but does not `return`. Execution falls through to `if claims.OwnerType() != OwnerTypeUser { http.Error(...) }` (anon is not a user), which writes a second response header after the redirect already committed the status. +- **Failure scenario:** An unauthenticated OAuth `/auth/oauth/authorize` request triggers the 307 redirect to `/auth/login`, then also runs `http.Error(w, "only users can be authorized", 400)`, producing a superfluous-`WriteHeader` log line and appending an error body to the redirect. Mostly benign because browsers follow the redirect, but it is a clear control-flow bug that would misbehave with a buffering `ResponseWriter`. +- **Recommendation:** Add `return` immediately after the `http.Redirect` call. + +**Verification:** CONFIRMED — in `handleAuthorizeRequest`, the anonymous branch calls `http.Redirect(...)` (`handlers.go:661`) with no `return`, so execution falls through to `if claims.OwnerType() != OwnerTypeUser { http.Error(w, "only users can be authorized", 400) }` (`handlers.go:663-666`), writing a second response after the redirect. + +**Manual Reproduction Steps (for QA):** +1. In a browser or via curl with no Rill session, hit the OAuth authorize endpoint: `curl -sv "/auth/oauth/authorize?client_id=x&redirect_uri=y&response_type=code"` (with cookies disabled / no auth). +2. Inspect the raw response and the admin service logs. +3. Observe both a 307 redirect to `/auth/login` and the follow-on `only users can be authorized` error body, plus a superfluous-`WriteHeader` warning in the server logs — confirming the missing `return`. + +### admin-auth-rbac-09 [LOW] `DeleteUser` looks up the account before the authorization check, enabling email enumeration +- **Category:** security **Confidence:** medium **Location:** `admin/server/users.go:525-538` (`DeleteUser`); minor: `admin/server/users.go:723-747` (`findUserAuthTokenFuzzy` exact-ID path) +- **Problem:** `DeleteUser` calls `FindUserByEmail` before evaluating the permission gate. A non-existent email returns the raw `ErrNotFound`, which `mapGRPCError` (`server.go:441-456`) maps to `codes.NotFound`, while an existing email that the caller may not delete returns `codes.PermissionDenied`. The two distinct codes form an enumeration oracle for registered emails, reachable even by anonymous callers since the lookup precedes any auth check. +- **Failure scenario:** Any caller enumerates which emails are registered Rill users by observing `NotFound` vs `PermissionDenied`. (The analogous `findUserAuthTokenFuzzy` exact-ID lookup is far weaker because token IDs are 128-bit UUIDs and not guessable, so it is noted only for completeness.) +- **Recommendation:** Perform the coarse authorization check before the lookup where possible, or normalize the response so "missing" and "forbidden" return the same code. + +**Verification:** CONFIRMED — `DeleteUser` calls `FindUserByEmail` (`users.go:528`) and returns its raw error before the permission gate at `users.go:533-538`; a missing email yields `ErrNotFound`→`codes.NotFound` (`mapGRPCError`, `server.go:454-456`) while an existing-but-forbidden email yields `codes.PermissionDenied`, giving distinct responses. + +**Manual Reproduction Steps (for QA):** +1. As a non-superuser (or unauthenticated) caller, invoke the admin `DeleteUser` API with an email you know is NOT registered: e.g. `grpcurl`/REST call to DeleteUser with `email=doesnotexist@example.com`. Note the returned gRPC code is `NotFound`. +2. Repeat with an email you know IS registered but that you are not allowed to delete (any other user's email). Note the returned code is `PermissionDenied`. +3. Observe the two different codes let a caller distinguish registered from unregistered emails (an enumeration oracle) without any account privileges. + +### admin-auth-rbac-06 [LOW] Token secret comparison is not constant-time +- **Category:** security **Confidence:** high **Location:** `admin/auth_token.go:331,352,370,387` (`bytes.Equal(model.SecretHash, parsed.SecretHash())`) +- **Problem:** All four token types validate the presented secret with `bytes.Equal` over the SHA-256 hashes, which short-circuits on the first differing byte and is not timing-safe. +- **Failure scenario:** Exploitability is minimal because the compared values are SHA-256 hashes (a timing leak reveals hash bytes, not the secret, and SHA-256 is not invertible), but this is security-critical credential verification where constant-time comparison is the expected norm and cheap to adopt. +- **Recommendation:** Use `crypto/subtle.ConstantTimeCompare` (or `hmac.Equal`) for the secret-hash comparison. + +**Verification:** CONFIRMED — all four token types compare secrets with `bytes.Equal(.SecretHash, parsed.SecretHash())` (`auth_token.go:331,352,370,387`), which short-circuits on the first differing byte and is not constant-time. Exploitability is minimal since the compared values are non-invertible SHA-256 hashes, as the finding notes. + +**Manual Reproduction Steps (for QA):** +Not user-reproducible through the product (a timing side-channel over SHA-256 hashes is not observable via normal UI/API use and leaks no usable secret). Confirm in code: `admin/auth_token.go:331,352,370,387` use `bytes.Equal` for secret-hash comparison instead of `crypto/subtle.ConstantTimeCompare`/`hmac.Equal`. + +### admin-auth-rbac-12 [LOW] `validPageSize` imposes no maximum, allowing unbounded list queries +- **Category:** performance **Confidence:** high **Location:** `admin/server/page_token.go:70-75` +- **Problem:** `validPageSize` substitutes a default when `pageSize == 0` but otherwise returns `int(pageSize)` with no upper bound. It is the only size gate for ~17 list endpoints (`ListMagicAuthTokens`, `ListOrganizationMemberUsers`, `ListProjectsForOrganization`, `ListUsergroupMemberUsers`, etc.). +- **Failure scenario:** An authenticated caller passes `page_size = 4294967295`; the endpoint issues a single query with that `LIMIT`, defeating pagination and, for a large tenant (thousands of members/tokens/projects), loading the entire table into memory in one response. +- **Recommendation:** Clamp `validPageSize` to a sane maximum (e.g. 1000) in addition to the default. + +**Verification:** CONFIRMED — `validPageSize` substitutes `_defaultPageSize` only when `pageSize == 0` and otherwise returns `int(pageSize)` with no upper clamp (`page_token.go:70-75`). + +**Manual Reproduction Steps (for QA):** +1. Authenticate against an org with many members/tokens/projects (or seed a test org with thousands of rows in one of the paged tables). +2. Call a paged list endpoint with a huge page size, e.g. REST/grpcurl to `ListOrganizationMemberUsers` (or `ListProjectsForOrganization`, `ListMagicAuthTokens`) with `page_size = 4294967295`. +3. Observe the endpoint returns the entire table in a single response (no cap applied), rather than clamping to a reasonable maximum — confirming pagination can be bypassed. + +### admin-auth-rbac-08 [LOW] Device-code request embeds an unvalidated user-supplied `redirect` into the verification URL +- **Category:** security **Confidence:** low **Location:** `admin/server/auth/device_code.go:79-90` +- **Problem:** `handleDeviceCodeRequest` copies `values.Get("redirect")` straight into the `verification_uri_complete` query without running it through `validateRedirectURL`, unlike `authStart` (`handlers.go:192`) and `authLogoutProvider` (`handlers.go:597`), which validate against the external/frontend host or a registered custom domain. +- **Failure scenario:** If the device-verification frontend navigates to this `redirect` after the user approves the code, a device flow initiated with `redirect=https://evil.com` yields an open redirect off a trusted Rill URL. Exploitability is low: the completed URL is returned to the flow initiator (typically the CLI) rather than an unrelated victim, and an attacker who can influence the frontend URL could craft the verification URL directly regardless of this endpoint. It remains an inconsistency worth closing for defense-in-depth. +- **Recommendation:** Validate the `redirect` parameter server-side with the same `validateRedirectURL`/`IsSafeRedirectURL` logic before embedding it. + +**Verification:** CONFIRMED — `handleDeviceCodeRequest` copies `values.Get("redirect")` directly into the `verification_uri_complete` query (`device_code.go:80-90`) with no `validateRedirectURL` call, and the device verify frontend navigates to it unvalidated (`web-admin/src/routes/-/auth/device/+page.svelte:30-31` does `window.location.href = decodeURIComponent(redirectURL)`). Exploitability is low as the finding notes (URL returned to the flow initiator, typically the CLI). + +**Manual Reproduction Steps (for QA):** +1. Initiate a device-code request with an attacker-controlled redirect: `curl -X POST "/auth/deviceauth/authorize" -d "client_id=&scope=full_account&redirect=https://evil.example.com"`. +2. Inspect the JSON response `verification_uri_complete` field and confirm it embeds `redirect=https://evil.example.com` unchanged (no host allow-list validation). +3. Open that verification URL in a browser, log in, and approve the device code; observe the device page navigates to `https://evil.example.com` — an open redirect off a trusted Rill URL. + +### admin-auth-rbac-10 [LOW] Org member-managers can grant project-admin indirectly via usergroup membership +- **Category:** product-improvement **Confidence:** high **Location:** `admin/server/usergroups.go:595-654` (`AddUsergroupMemberUser`, acknowledgement at `:611-612`) +- **Problem:** Adding a user to a usergroup only requires `ManageOrgMembers` on the org (plus `ManageOrgAdmins` if the group holds an *org*-admin role). A usergroup may hold an admin *project* role on a project the actor does not administer, and that case is not checked. The code comment explicitly accepts this ("not a big leak"). +- **Failure scenario:** An org member-manager who is deliberately not a project admin adds themselves (or a colleague) to a usergroup that is project-admin on a sensitive project, gaining admin-level access to it. +- **Recommendation:** When adding members to a group, verify the actor holds the group's effective project roles (or at least `ManageProjectAdmins` for any admin-bearing project), or surface the group's project roles in the UI so the escalation is explicit. + +**Verification:** CONFIRMED — `AddUsergroupMemberUser` only checks `ManageOrgMembers` (`usergroups.go:596`) plus `ManageOrgAdmins` when the group holds an org-admin role (`usergroups.go:608-609`); it never checks the group's *project* roles, and the code comment at `usergroups.go:611-612` explicitly accepts this ("not a big leak of permissions"). + +**Manual Reproduction Steps (for QA):** +1. Set up an org with a usergroup that has been granted the `admin` role on a specific sensitive project, but which holds no org-admin role. +2. Log in as a user who has org member-management rights (`ManageOrgMembers`) but is deliberately NOT an admin on that sensitive project. +3. As that user, add yourself (or a colleague) to the project-admin usergroup via the "Add member to group" UI or the `AddUsergroupMemberUser` API. +4. Confirm the add succeeds, and then open the sensitive project — observe you now have admin-level access to a project you could not previously administer. + +### admin-auth-rbac-11 [LOW] First-user-becomes-superuser bootstrap can race under concurrent first sign-ups +- **Category:** concurrency **Confidence:** low **Location:** `admin/user.go:168-192` (`CheckUsersEmpty` then `InsertUser` with `Superuser: isFirstUser`) +- **Problem:** The first user ever created is granted superuser based on `CheckUsersEmpty` inside a transaction opened with `NewTx(ctx, false)`. Depending on the DB isolation level, two concurrent first-time sign-ups could both observe an empty users table and both be inserted as superusers. +- **Failure scenario:** On a freshly provisioned deployment, two users complete OIDC login simultaneously and both are granted superuser. The window is extremely narrow (only the very first sign-ups on a brand-new install, typically the operator themselves), so practical impact is low, but the consequence (unintended superuser) is high. +- **Recommendation:** Enforce the invariant at the DB level (partial unique constraint / advisory lock), or gate superuser bootstrap on an explicit configuration signal rather than emptiness. + +**Verification:** PLAUSIBLE — `CheckUsersEmpty` then `InsertUser` with `Superuser: isFirstUser` runs inside `NewTx(ctx, false)` (`user.go:168-189`), which does a plain `BeginTxx(ctx, nil)` with no explicit isolation level or locking (`postgres/tx.go:22`); under the default Read Committed isolation two concurrent first sign-ups could both observe an empty table. The window is extremely narrow (only the very first sign-ups on a brand-new install), so it stays PLAUSIBLE. + +**Manual Reproduction Steps (for QA):** +Not reliably user-reproducible — it requires two OIDC logins to race within the same instant on a freshly provisioned, empty-users deployment. Confirm in code: `admin/user.go:174-185` (`CheckUsersEmpty` gating `Superuser: isFirstUser`) inside `admin/database/postgres/tx.go:22` (`BeginTxx(ctx, nil)`, default isolation, no `SELECT ... FOR UPDATE`/advisory lock). Verify there is no unique constraint restricting superusers to one row. + +## Product Improvements + +- **admin-auth-rbac-10** (above) — make indirect project-admin escalation through usergroups explicit or blocked. +- **Token revocation is effectively delayed** (admin-auth-rbac-02) — from a product standpoint, "log out everywhere" / "revoke token" should take effect immediately; wiring cache eviction makes the security control trustworthy. +- **Transient DB blips log users out** (admin-auth-rbac-13/07) — a brief admin-DB hiccup should not evict valid browser sessions. +- **Magic-token secrets are stored recoverable in the DB** (`admin/auth_token.go:210` stores `Secret`, re-materialized in `magic_tokens.go:288-302`) — unlike user/service tokens (hash-only). This is required to re-display shareable links, but it means anyone with `ManageMagicAuthTokens` or DB read access recovers working tokens. Consider surfacing this clearly in the UI and offering a "hide secret after creation" mode. + +## New Feature Ideas + +- **Immediate session/token revocation with cache eviction + audit** — add a `Remove(tokenHash)` on the auth cache and a "Sessions & Tokens" view listing active tokens (client, last-used, expiry) with one-click revoke that takes effect instantly. Value: trustworthy account security. Effort: M. +- **Scoped / least-privilege magic tokens** — let issuers pick an explicit attribute profile (never `admin`, choose which custom attributes carry) when creating a magic link, closing admin-auth-rbac-03 and giving embedders predictable data access. Value: safer embeds. Effort: M. +- **Constant-time token verification + token-format hardening pass** — adopt `subtle.ConstantTimeCompare` and add fuzz/property tests for `authtoken.FromString`/`String` round-trips and truncation. Value: defense-in-depth. Effort: S. +- **Superuser action audit log** — persist every `Superuser`/`SuperuserForceAccess`/assume-user action (who, whom, when, why) surfaced in an admin UI. Value: compliance and incident response for a support-heavy control plane. Effort: M. +- **Redirect allow-list as a first-class, centrally-tested policy** — route every redirect (`authStart`, logout, device code, PKCE) through one validated helper with a shared test matrix, eliminating gaps like admin-auth-rbac-08. Value: systematic open-redirect prevention. Effort: S. +- **Environment-aware runtime proxy access** — gate the proxy on `ReadProd`/`ReadDev` by `depl.Environment` (admin-auth-rbac-04) and add an org setting for whether public projects may serve non-prod/branch deployments. Value: correct exposure of in-development data. Effort: M. + +## Notes & Missing Test Coverage + +- `admin/auth_token.go` has no production-path eviction on revoke; `users_test.go` has to call `PurgeAuthTokenCache()` manually to observe revocation, which pins the gap in admin-auth-rbac-02. A test asserting that a revoked token is rejected within the TTL *without* a manual purge would catch it. +- The permission-composition layer (`admin/permissions.go`) and the public-project/force-access elevation paths lack tests asserting that the returned permission objects are not aliased/mutated (admin-auth-rbac-01). `roles_test.go` only covers DTO conversion. +- No test covers magic-token attribute capture/replay (admin-auth-rbac-03); a test asserting an admin-created magic token does not yield `admin: true` in the issued JWT would pin the intended behaviour. +- The runtime proxy (`runtime_proxy.go`) has no unit test around the branch route / environment-based authorization (admin-auth-rbac-04) or the direct-JWT-passthrough vs mint decision. +- Header forwarding in the proxy copies only the first value of each header (`runtime_proxy.go:135-137`, `req.Header.Add(k, v[0])`); harmless today but untested and would silently drop multi-valued request headers. + +## Verification Notes + +All 11 original findings were re-checked against the code; each survived at least mechanically, and 2 new in-scope findings were added. Net removed: 0. Key adjustments: + +- **Reordered by significance.** admin-auth-rbac-03 (magic-token admin-flag replay) is the strongest issue and is now listed first; it is retained at MEDIUM/high after confirming the full capture→store→replay chain (`magic_tokens.go:95` → `IssueMagicAuthToken`/`InsertMagicAuthToken` → `runtime_jwt.go:119`). +- **admin-auth-rbac-01:** confirmed the getters return the cached pointer and that `runtime_proxy.go`, `projects.go`, `organizations.go`, `bookmarks.go` mutate it. Downgraded MEDIUM→LOW because claims are constructed fresh per request (`middleware.go:201`) and the mutated flags are not re-read for authorization within the same handler, so it is latent, not exploitable today (the reviewer's own scenario conceded this). +- **admin-auth-rbac-02:** confirmed via `grep` that `PurgeAuthTokenCache` is called only from `users_test.go`, never in production. Corrected the claim "never called anywhere" (it exists and is test-only). Downgraded MEDIUM→LOW given the bounded, per-replica ≤10s window. +- **admin-auth-rbac-04:** partially refuted. The "custom role with ReadProd-but-not-ReadDev" escalation is not reachable — `migrations/0003.sql:40-42` shows all three built-in project roles couple `read_prod` and `read_dev`, and roles are not user-customizable. Rewritten to focus on the one reachable concern (anonymous exposure of branch deployments on public projects) and downgraded MEDIUM→LOW, confidence medium→low. +- **admin-auth-rbac-07:** traced the `errors.Is(err, ctx.Err())` guard and confirmed non-context errors are cached; bumped confidence medium→high. +- **admin-auth-rbac-09:** confirmed the enumeration oracle by verifying `mapGRPCError` maps `ErrNotFound`→`codes.NotFound` (`server.go:441-456`). Narrowed the finding to `DeleteUser`'s email enumeration (the token-ID path is weak because IDs are UUIDs). +- **admin-auth-rbac-05, -06, -08, -10, -11:** confirmed as written; severities/categories unchanged (05, 06, 08 verified at the cited lines; 10 and 11 confirmed including the code's own acknowledgements). 08 kept at low confidence with the exploitability caveat spelled out. +- **Added admin-auth-rbac-12** (`page_token.go:70-75`): `validPageSize` has no maximum, so ~17 list endpoints accept an unbounded `page_size`. LOW/performance, confirmed no cap exists elsewhere. +- **Added admin-auth-rbac-13** (`middleware.go:102-112`): `CookieRefreshMiddleware` clears the session cookie on any `ValidateAuthToken` error, so a transient DB error (compounded by admin-auth-rbac-07) silently logs valid users out. LOW/product-improvement. +- PKCE (`pkce.go`), device-code issuance (`auth_code.go`), sudo (`sudo.go`), cookies (`cookies.go`), roles (`roles.go`), and MCP OAuth/DCR (`mcp_oauth.go`) were reviewed and found sound (single-use codes deleted before validation, S256-only, superuser-gated sudo, PKCE redirect exact-match against registered URIs); no additional findings. diff --git a/audit/admin-billing-provision.md b/audit/admin-billing-provision.md new file mode 100644 index 000000000000..f8c2616181d4 --- /dev/null +++ b/audit/admin-billing-provision.md @@ -0,0 +1,213 @@ +# Admin Billing, Provisioners & Jobs — Code Review + +**Scope:** `admin/billing/**`, `admin/provisioner/**`, `admin/jobs/**`, `admin/metrics.go`, `admin/billing.go`, `admin/used_flusher.go` (plus call sites in `admin/provision.go`, `admin/server/provision.go`, `admin/deployments.go`, `admin/jobs/org_jobs.go`, and the `static_runtime_assignments` DB layer for tracing) | **Health:** needs-attention + +## Overview +This area covers the Orb-backed billing lifecycle (trials, subscriptions, credit grants, invoices, webhooks), the runtime/ClickHouse provisioners (static slots, `clickhouse-static` multi-tenant DBs, Kubernetes), and the River background-job fleet that drives trial/grace-period/hibernation state machines and usage reporting. The code is generally careful: webhook signatures are verified, most jobs are idempotent via River unique keys, and trial/credit flows have explicit "already done" guards. The biggest risks are concentrated in two places: (1) the `clickhouse-static` provisioner truncates the only unique component of a database name, which can collide when org/project names are long and cause data loss on deprovision (and, in narrower cases, cross-tenant access); and (2) static runtime slot allocation performs an unserialized read-then-write, allowing slot overcommit. Secondary risks are a handful of job workers whose retry/partial-failure paths are not fully idempotent (hibernation abandoned after a committed state transition; emails emitted inside an open DB transaction) and unbounded "first 100 projects" loops in org teardown/hibernation. Concurrency in `used_flusher` shutdown is fragile but low-impact. + +## Findings + +### abp-01 [HIGH] `clickhouse-static` truncates the unique resource ID out of the database name, causing collisions + +**Status (2026-07-25):** ✅ Fixed and merged in [#9683](https://github.com/rilldata/rill/pull/9683). + +- **Category:** security **Confidence:** high **Location:** `admin/provisioner/clickhousestatic/provisioner.go:335-350` (used at `:146` create, `:182` grant, `:275` drop) +- **Problem:** `generateDatabaseName` builds `rill___` and then blindly truncates to 63 bytes with `name[:63]`. Because the resource ID (the only globally-unique component) is appended **last**, it is exactly what gets cut off when the org/project prefix is long. The repo's own test documents this: input id `very_long_resource_id_..._12345678` yields `rill_verylongorganizationname_verylongprojectname_verylongresou` — the ID is gone. The per-resource `user` is built as `rill_` (`:136`) and is **not** truncated, so it stays unique. Provisioning does `CREATE DATABASE IF NOT EXISTS ` and then `GRANT ... ON .* TO `, so two resources whose names truncate identically get **distinct users granted on the same shared database**. +- **Reachability:** Requires the sanitized `org + project` prefix to be long enough to truncate the 32-char resource ID. There is no server-side length cap on org/project names (`CreateOrganizationRequest.name`/project name are `min_len = 1` only in `proto/rill/admin/v1/api.proto`, and the `orgs`/`projects` name columns are bare `TEXT` in `migrations/0001.sql`), so long names are possible. The most reachable harm is **same-tenant**: the ClickHouse resource is keyed per-deployment (`admin/server/provision.go:52,72` → new `uuid.New()` per deployment in `admin/provision.go:75`), so a redeploy of a project with a long `org+project` prefix produces a new resource ID that truncates to the *same* database name as the previous deployment. Deprovisioning the old deployment then runs `DROP DATABASE IF EXISTS ` (`:275`), destroying the live deployment's data. Cross-project (same org) and cross-org collisions are also possible but require the org/project prefix (or a shared org prefix) to survive truncation identically, which is less likely. +- **Recommendation:** Never truncate away the uniqueness. Reserve a fixed suffix for a deterministic hash of `r.ID` (e.g. truncate the human-readable org/project prefix, then always append `_`), or key on the full sanitized `r.ID`. Add a collision test with long org/project names asserting distinct names for distinct IDs. + +**Verification:** CONFIRMED — `generateDatabaseName` (`admin/provisioner/clickhousestatic/provisioner.go:335-350`) appends the resource ID last and then truncates with `name[:63]`, so long org/project prefixes cut off the only unique component; the untruncated per-resource user is built at `:136`, provisioning uses the name at `:146`/`:182`, and deprovision runs `DROP DATABASE IF EXISTS` on it at `:275`. The existing test (`provisioner_test.go`) shows the ID fully truncated away for long inputs. + +**Manual Reproduction Steps (for QA):** +1. On a staging Rill Cloud environment configured with a `clickhouse-static` provisioner, create an organization and project whose combined sanitized names exceed ~58 characters (e.g. org `verylongorganizationnameforcollisiontesting`, project `verylongprojectnameforcollisiontesting`), and deploy the project so a ClickHouse database is provisioned. +2. Connect to the ClickHouse cluster as an admin and run `SHOW DATABASES LIKE 'rill_%'`; note the database name is exactly 63 characters and does not end with the deployment's resource ID. +3. Redeploy the project (e.g. hibernate and wake it, or trigger a redeploy that creates a new deployment) so a second ClickHouse resource with a new resource ID is provisioned. +4. Run `SHOW DATABASES LIKE 'rill_%'` again: only one database exists for both deployments (the names truncated identically), and `SHOW USERS` shows two distinct `rill_` users. +5. Deprovision/tear down the old deployment (e.g. delete it or let cleanup run), then query the new deployment's dashboard: its data is gone because `DROP DATABASE` removed the shared database. + +### abp-02 [HIGH] Static runtime slot allocation is a TOCTOU race (not serialized) → slot overcommit +- **Category:** concurrency **Confidence:** high **Location:** `admin/provisioner/static/static.go:93-122` +- **Problem:** `Provision` calls `ResolveStaticRuntimeSlotsUsed` (a plain `SELECT host, SUM(slots) ... GROUP BY host`, `admin/database/postgres/postgres.go:821-828`), filters hosts with free capacity in memory, then writes `UpsertStaticRuntimeAssignment` (a plain `INSERT ... ON CONFLICT`, `:794-810`). There is no transaction, `SELECT ... FOR UPDATE`, or advisory lock spanning the read and the write, and the call site (`admin/provision.go:106`, reached from `admin/deployments.go:743-758`) invokes this without any external lock. Provisioning runs concurrently (River `MaxWorkers: 10`, and `ProvisionerMaxConcurrency` up to 30), so concurrent provisions can observe the same "slots used" snapshot. +- **Failure scenario:** A host has 8 free slots. Two deployments provision 6 slots each at the same time. Both read `used` showing 8 free, both select that host, both upsert → 12 slots committed onto an 8-slot host. The runtime is silently overcommitted (memory/CPU limits exceeded → OOM/contention), and the capacity `Check` only warns after the fact. +- **Recommendation:** Serialize allocation: wrap the resolve+upsert in a single transaction with `SELECT ... FOR UPDATE` on the affected host rows, take a Postgres advisory lock keyed on the provisioner, or push the capacity check into the `INSERT ... WHERE (SELECT SUM(slots) ...) + $slots <= capacity` statement so the DB enforces the invariant atomically. + +**Verification:** CONFIRMED — `Provision` (`admin/provisioner/static/static.go:93-122`) reads `ResolveStaticRuntimeSlotsUsed` (plain `SELECT ... SUM(slots) ... GROUP BY host`, `admin/database/postgres/postgres.go:821-828`), filters in memory, then calls `UpsertStaticRuntimeAssignment` (plain `INSERT ... ON CONFLICT`, `postgres.go:794-810`) with no transaction or lock spanning the two; concurrency is real (`MaxWorkers: 10` in `admin/jobs/river/river.go:182`, `ProvisionerMaxConcurrency` default 30 in `cli/cmd/admin/start.go:60`). + +**Manual Reproduction Steps (for QA):** +1. On a staging environment using the `static` runtime provisioner, configure a single runtime host with a small capacity (e.g. 8 slots) in the provisioner spec. +2. Simultaneously deploy two projects that each request more than half the capacity (e.g. 6 slots each) — for example, run two `rill project deploy`/redeploy operations for two different projects at the same moment (a script firing both API calls in parallel is the most reliable way). +3. After both deployments succeed, query the admin Postgres database: `SELECT host, SUM(slots) FROM static_runtime_assignments GROUP BY host;`. +4. Observe the summed slots exceed the host's configured capacity (e.g. 12 > 8), confirming overcommit. Note: timing-dependent; repeat step 2 several times if both provisions do not overlap on the first try. + +### abp-03 [MEDIUM] `CreditBalanceDepletedWorker` abandons project hibernation on retry after committing the issue swap +- **Category:** correctness **Confidence:** medium **Location:** `admin/jobs/river/credit_balance_event_handlers.go:110-201` +- **Problem:** The worker (a) confirms the org is `OnCreditTrial` (`:110-117`), (b) cancels the subscription (`:136`), (c) in a transaction deletes the `OnCreditTrial` issue and raises `TrialCreditsDepleted`, commits (`:141-166`), then (d) loops hibernating every project with keyset pagination (`:168-184`). If hibernation fails partway (step d), or the subsequent email send fails (`:188-198`), `Work` returns an error and River retries — but the retry re-runs the guard at `:114`, finds no `OnCreditTrial` issue (it was deleted and committed in step c), logs "org is not on the credit trial", and returns `nil`. The remaining projects are never hibernated. +- **Failure scenario:** Org with 10 projects depletes credits; hibernation of project #3 fails (transient runtime error). On retry the worker no-ops, leaving projects #3–#10 running compute indefinitely on a depleted trial. Unlike the trial-grace worker (`trial_checks.go:263-289`), this path also never zeroes org quotas, so nothing else forces the projects down. +- **Recommendation:** Make hibernation idempotent and independent of the trial-issue state: drive it off `TrialCreditsDepleted` (the state the retry can still observe) or hibernate before/inside the committed transition, and treat "already depleted" as a resumable state rather than an early return. + +**Verification:** CONFIRMED — `admin/jobs/river/credit_balance_event_handlers.go`: the `OnCreditTrial` guard returns `nil` when the issue is absent (`:114-117`), the issue swap is committed at `:164-166`, and both the hibernation loop (`:168-184`) and the email send (`:188-198`) after the commit return errors that trigger a River retry, which then hits the guard and no-ops, leaving remaining projects running. + +**Manual Reproduction Steps (for QA):** +1. This requires inducing a failure mid-job, which is not achievable through the product UI alone; it needs a staging environment with Orb billing webhooks enabled and the ability to cause a transient failure (e.g. temporarily break the email provider credentials or take one project's runtime offline). +2. Create an org on the credit trial with several deployed projects (e.g. 5). +3. Break the email provider configuration (e.g. invalid SMTP/API key) so `SendCreditTrialDepleted` will fail, then deplete the org's trial credits so Orb fires the `credit_balance_depleted` webhook. +4. Watch the admin logs: the first job run cancels the subscription, hibernates all projects, then fails on the email and is retried; the retry logs "credit_balance_depleted webhook ignored: org is not on the credit trial" and completes without sending the email. (To observe the more severe variant — projects left running — cause a hibernation failure for one project instead of the email failure in step 3; on retry the remaining projects stay un-hibernated: check each project's status shows a live deployment.) +5. Confirm the depleted-trial email was never delivered and/or projects after the failed one still have running deployments. + +### abp-04 [MEDIUM] Org teardown and inactive-org hibernation only process the first 100 projects +- **Category:** correctness **Confidence:** medium **Location:** `admin/jobs/river/org_jobs.go:207-221` (DeleteOrg), `:250-267` (HibernateInactiveOrgs) +- **Problem:** Both workers call `FindProjectsForOrganization(ctx, orgID, "", 100)` once, with no keyset loop (contrast `credit_balance_event_handlers.go:168-184`, `trial_checks.go:291-310`, and `biller_event_handlers.go:215-234`, which all loop with `afterProjectName`). The query is `... WHERE org_id=$1 AND lower(name) > lower($2) ORDER BY lower(name) LIMIT $3` (`postgres.go:340-351`). + - `HibernateInactiveOrgsWorker` (`:250-267`) has **no retry and no pagination**: it always fetches the same first 100 projects by name and hibernates those with a live deployment. Projects beyond the first 100 (alphabetically) are never hibernated — the query does not filter on deployment state, so already-hibernated projects keep occupying the first-100 window on every weekly run. + - `DeleteOrgWorker` (`:207-227`) tears down ≤100 projects (`TeardownProject` deletes the project row, `projects.go:138-...`) then calls `DeleteOrganization`; the `projects.org_id` FK is `ON DELETE RESTRICT` (`migrations/0001.sql:15`), so with >100 projects the delete fails and relies on River retries (`MaxAttempts: 3`, `river.go:188`) to drain ~100 per attempt (≈300 max). It self-heals under ~300 projects but stalls above that. Separately, `TeardownProject` polls up to 5 minutes per project, so ~100 sequential teardowns can exceed the 1-hour `JobTimeout` (`river.go:187`). +- **Failure scenario:** An inactive org with 150 projects leaves 50 projects running compute forever (no retry, no pagination). An enterprise org with 350 projects is deleted: three attempts clear ~300, the 4th never runs, and the org plus ~50 projects stay half-deleted. +- **Recommendation:** Loop with keyset pagination until exhausted (as the other workers do), and consider fanning teardown out per-project rather than serially polling within one job. + +**Verification:** CONFIRMED — `admin/jobs/river/org_jobs.go`: `DeleteOrgWorker` calls `FindProjectsForOrganization(ctx, job.Args.OrgID, "", 100)` once at `:207` with no pagination loop, and `HibernateInactiveOrgsWorker` does the same at `:251`; contrast the keyset loop in `credit_balance_event_handlers.go:168-184`. `MaxAttempts: 3` and `JobTimeout: time.Hour` confirmed at `admin/jobs/river/river.go:187-188`. + +**Manual Reproduction Steps (for QA):** +1. On a staging Rill Cloud environment, create an organization and deploy (or script-create via the admin API) more than 100 projects in it — e.g. 120 projects named `p001`…`p120`. +2. For the hibernation case: make the org "inactive" per the inactivity criteria (or adjust the staging threshold), then trigger the weekly `hibernate_inactive_orgs` job (enqueue it via the jobs trigger endpoint or wait for the schedule). +3. After the job completes, list the projects: the first 100 alphabetically are hibernated but projects 101-120 still show live deployments. Re-running the job does not fix them (the same first 100 are re-fetched every run). +4. For the deletion case: delete the organization (CLI `rill org delete` or admin API) on an org with >300 projects; observe the `delete_org` job fail after tearing down ~100 projects per attempt, exhaust its 3 attempts, and leave the org and remaining projects half-deleted (org still present in the DB, projects still listed). + +### abp-05 [LOW] `TrialEndCheckWorker` performs the DB state transition and sends email inside one transaction +- **Category:** correctness **Confidence:** medium **Location:** `admin/jobs/river/trial_checks.go:147-203` +- **Problem:** The worker opens a transaction, upserts `TrialEnded`, deletes `OnTrial`, then calls `SendTrialEnded` (a network call to the email provider) **before** `tx.Commit()`. Two consequences: (1) the DB transaction (holding the upserted/deleted `billing_issues` rows) stays open across an external API round-trip, for every ending trial in the batch, so an email-provider slowdown pins connections/locks; (2) the durability ordering is inverted — if the email succeeds but `Commit` fails (`:200-203`) the customer received a "trial ended" email while the DB rolled back, so the next daily run sends it again. Because email failure returns an error that rolls the transaction back (`:191-198`), an email-provider outage also stalls *all* trial-end transitions until it recovers. +- **Failure scenario:** Email provider is slow/commit races a connection drop → a duplicate trial-ended email and a transaction pinned open across email latency; or an email outage blocks every org's trial-end processing. +- **Recommendation:** Perform the DB state transition and commit first, then send the (best-effort, logged-not-returned) email outside the transaction, matching the pattern already used in `PaymentSuccessWorker` (`biller_event_handlers.go:165-175`). + +**Verification:** CONFIRMED — `admin/jobs/river/trial_checks.go:147-203`: the transaction opens at `:147`, `SendTrialEnded` is called at `:184-190` before `tx.Commit()` at `:200`, and an email error rolls the transaction back (`:191-198`), so email I/O sits inside the open transaction and an email outage blocks the trial-end transition. + +**Manual Reproduction Steps (for QA):** +1. On a staging environment with billing enabled, create an org whose trial end date has passed (or shorten the trial in staging config) so the daily `trial_end_check` job will process it. +2. Break the email provider configuration (e.g. invalid API key) so `SendTrialEnded` fails. +3. Trigger or wait for the trial-end check job; observe in logs it errors with "failed to send trial period ended email" and that the org's billing issue remains `on-trial` (no `trial-ended` issue appears in the DB `billing_issues` table) — the whole transition rolled back because of the email failure. +4. Restore email; the next run transitions the org and sends the email. The duplicate-email variant (email sent, commit fails) is timing-dependent and not reliably reproducible manually; confirm in code at `trial_checks.go:184-203` that the email precedes the commit. + +### abp-06 [LOW] `usedFlusher.Close` does not join the background goroutine; `flushWg` is incremented inside the function it waits on +- **Category:** concurrency **Confidence:** medium **Location:** `admin/used_flusher.go:113-134` (Close call site `admin/admin.go:162`, shutdown path) +- **Problem:** `runBackground` calls `flush()` on a 30s ticker; `flush()` itself does `flushWg.Add(1)`/`defer Done()`. `Close()` calls `cancel()`, then its own `flush()`, then `flushWg.Wait()`, but never joins the background goroutine. After `cancel()`, if the ticker and `ctx.Done()` are both ready, the `select` may still pick the tick and run one more `flush()` concurrently with `Close`'s `flush()`/`Wait()`. Because `Add` happens inside the waited-on function rather than being registered before `Wait` for a fixed set, this is the shape Go's `WaitGroup` contract warns about (`Add` racing `Wait` from a zero counter), and the background goroutine can still be writing to the DB after `Close` returns. +- **Failure scenario:** On shutdown, a background tick fires concurrently with `Close`; in a narrow window it can trip `sync: WaitGroup misuse: Add called concurrently with Wait`, or a background flush runs after the pool is torn down (logged error). Shutdown-only, low frequency. +- **Recommendation:** Give the background goroutine its own done channel / `WaitGroup` and `Wait` on *that* in `Close` (join the loop), then do one final synchronous flush. Don't `Add` to the wait group inside the function being awaited. + +**Verification:** CONFIRMED — `admin/used_flusher.go`: `Close()` (`:113-117`) calls `cancel()`, `flush()`, `flushWg.Wait()` but never joins the goroutine started in `newUsedFlusher` (`:52`); `runBackground`'s `select` (`:119-130`) can pick a ready tick over `ctx.Done()`, and `flush()` does `flushWg.Add(1)` inside itself (`:133`), the exact `Add`-racing-`Wait`-from-zero shape the `WaitGroup` contract forbids. + +**Manual Reproduction Steps (for QA):** +Not user-reproducible — this is a narrow shutdown-only race with no user-facing surface. Confirm in code: `admin/used_flusher.go:113-134` (Close does not join the `runBackground` goroutine; `flushWg.Add` is inside `flush`, the function being awaited) and the Close call site on the admin service shutdown path in `admin/admin.go`. A Go engineer can also demonstrate it with a `-race` unit test that spins tickers fast and calls `Close` concurrently, but no QA-visible symptom exists beyond a rare `sync: WaitGroup misuse` panic in admin-service shutdown logs. + +### abp-07 [LOW] Autoscaler logs `.Name` on a nil project/org after a lookup error (nil-panic) +- **Category:** bug **Confidence:** high **Location:** `admin/jobs/river/run_autoscaler.go:55-64` +- **Problem:** `targetProject, err := FindProject(...)` then, on `err != nil`, logs `zap.String("project_name", targetProject.Name)` (`:57`) — but `FindProject` returns a nil `*Project` on error, so `.Name` dereferences nil and panics. Same at `:61-63` with `projectOrg.Name`. The worker is currently gated off by `disableAutoscaler = true` (`:39-42`), so this is latent/dead, but it is a real panic if re-enabled. +- **Failure scenario:** A recommendation references a since-deleted project; `FindProject` returns `ErrNotFound`; the error branch panics instead of logging and continuing. +- **Recommendation:** Log `rec.ProjectID` (and `targetProject.OrganizationID`) instead of dereferencing the nil result; add nil guards. + +**Verification:** CONFIRMED — `admin/jobs/river/run_autoscaler.go:55-64`: on `FindProject` error the code logs `zap.String("project_name", targetProject.Name)` (`:57`) where `targetProject` is nil, and on `FindOrganization` error it logs `projectOrg.Name` (`:63`) where `projectOrg` is nil; both are guaranteed nil-pointer panics on those branches. Latent only, because `disableAutoscaler = true` (`:20`) makes `Work` return at `:39-42`. + +**Manual Reproduction Steps (for QA):** +Not user-reproducible in the current build — the autoscaler is hard-disabled by the `disableAutoscaler` constant, so the panicking branches never execute regardless of configuration. Confirm in code: `admin/jobs/river/run_autoscaler.go:55-64` (nil `targetProject`/`projectOrg` dereferenced in the error-branch log calls) and `:20`/`:39-42` (the constant gate). If an engineer flips the constant in a test build, seeding an autoscaler recommendation row referencing a deleted project ID and triggering the `run_autoscaler` job will panic the worker. + +### abp-09 [LOW] Orb `GetCustomerCreditBalance` and `getAllPlans` don't paginate +- **Category:** correctness **Confidence:** low **Location:** `admin/billing/orb.go:305-317` (balance), `:654-658` (plans) +- **Problem:** `GetCustomerCreditBalance` sums only the first page of `Customers.Credits.ListByExternalID` (no `AutoPaging`/cursor follow); if a customer has more active credit blocks than one page, the balance is undercounted. `getAllPlans` caps at `Limit: 100` with an acknowledged `TODO handle pagination`, silently dropping plans beyond 100. The codebase already uses Orb's auto-paging iterator elsewhere (`CreateCustomerCreditAlerts`, `:232 ListAutoPaging`), so the fix is well-precedented. +- **Failure scenario:** A long-lived customer with many active credit blocks reads low, tripping the low-balance/depleted logic early; or a >100-plan catalog fails `GetPlanByType`/`GetPlanByName` lookups. Both are unlikely at current scale (trial orgs typically have one credit block; Rill has a handful of plans), hence low confidence. +- **Recommendation:** Use Orb's auto-paging iterators for both the credit list and the plan list. + +**Verification:** CONFIRMED — `admin/billing/orb.go`: `GetCustomerCreditBalance` (`:305-317`) sums only `page.Data` from a single `ListByExternalID` call with no cursor follow, and `getAllPlans` (`:654-658`) caps at `Limit: orb.Int(paginationLimit)` with the comment `TODO handle pagination, for now don't expect more than 100 plans`. Impact requires more credit blocks/plans than one page, which is unlikely at current scale. + +**Manual Reproduction Steps (for QA):** +1. In an Orb sandbox account wired to a staging Rill admin service, create a customer (org) and grant it more active credit blocks than one Orb API page (create many small credit grants — e.g. 25+ separate grants if the page size is 20). +2. Compare the org's credit balance shown by Rill (billing page / `GetBillingSubscription` API) against the sum of all block balances shown in the Orb dashboard. +3. Observe Rill undercounts: it reports only the first page's total. With a low enough reported balance, the low-balance/depleted alerts can fire even though real credits remain. +4. For the plans gap: create >100 active plans in the Orb sandbox and confirm plan lookups by name/type for plans beyond the first 100 fail in Rill (e.g. `rill sudo billing` plan operations cannot find them). + +### abp-10 [LOW] `PaymentFailedWorker`/`PaymentSuccessWorker` read-modify-write the invoices map with no cross-job serialization +- **Category:** concurrency **Confidence:** low **Location:** `admin/jobs/river/biller_event_handlers.go:46-82` (failed), `:126-162` (success) +- **Problem:** `PaymentFailedWorker` reads the existing `PaymentFailed` issue, adds one invoice to the `Invoices` map, and upserts the whole metadata (`UpsertBillingIssue` replaces the row wholesale). River `PaymentFailed` jobs are unique `ByArgs` (`river.go:454-458`), and args include `InvoiceID`, so two different failed invoices for the same org are two distinct jobs that can run concurrently (`MaxWorkers: 10`); both read the same base metadata and both overwrite it, losing one invoice entry (last-writer-wins). `PaymentSuccessWorker` has the same read-delete-write shape and can race the failed path. +- **Failure scenario:** Two invoices for one org fail in the same window → only one ends up recorded, so the grace-period/blocking logic under-counts overdue invoices. +- **Recommendation:** Do the merge inside a transaction with row locking (or a single UPSERT that JSON-merges server-side), or serialize payment-issue mutations per org. + +**Verification:** CONFIRMED — `admin/jobs/river/biller_event_handlers.go`: `PaymentFailedWorker` reads the existing issue (`:46`), mutates the `Invoices` map in memory (`:62-71`), and upserts the whole metadata (`:74-79`) with no transaction or locking; `PaymentSuccessWorker` has the same read-delete-write shape (`:126-162`). The jobs are unique `ByArgs` with `InvoiceID` in the args, so two different invoices for one org are distinct jobs that can run concurrently on the 10-worker pool. + +**Manual Reproduction Steps (for QA):** +1. In an Orb/Stripe sandbox wired to staging, set up an org with a payment method that will be declined. +2. Cause two separate invoices for the same org to fail payment at (nearly) the same time — e.g. issue two one-off invoices in the Orb sandbox and fail both, so two `invoice.payment_failed` webhooks arrive within the same second. +3. Inspect the org's `payment failed` billing issue (DB `billing_issues` row for the org, or the billing status shown to the org admin). +4. If the race hit, only one of the two failed invoices is recorded in the issue's invoice map (last writer wins); repeat step 2 several times, as the overlap window is small. + +### abp-11 [LOW] `DeleteOrg` and `PlanChanged` jobs are inserted without unique options +- **Category:** tech-debt **Confidence:** medium **Location:** `admin/jobs/river/river.go:631-643` (DeleteOrg), `:645-657` (PlanChanged) +- **Problem:** Every other trigger sets `UniqueOpts{ByArgs: true}` (and `RepairOrgBilling` additionally sets `ByState` to allow retries while blocking concurrent runs, `:518-526`), but `DeleteOrg` and `PlanChanged` pass a bare `&river.InsertOpts{}`. Duplicate enqueues (repeated webhooks, double-clicks) run concurrently. Two `DeleteOrgWorker` runs race on teardown/`DeleteOrganization`; two `PlanChangedWorker` runs both re-fetch and both write the plan cache. +- **Failure scenario:** A user retries org deletion and two workers concurrently tear down the same projects, producing spurious errors/retries; or duplicated `subscription.*` webhooks spawn redundant plan-cache updates. +- **Recommendation:** Add `UniqueOpts{ByArgs: true}` (with an appropriate `ByState`) to both, consistent with the other insert helpers. + +**Verification:** CONFIRMED — `admin/jobs/river/river.go`: `DeleteOrg` inserts with a bare `&river.InsertOpts{}` at `:634` and `PlanChanged` at `:648`, while virtually every other insert helper in the file sets `UniqueOpts` (e.g. `:342`, `:455`, `:522`). Duplicate enqueues therefore create concurrent duplicate jobs. + +**Manual Reproduction Steps (for QA):** +1. On staging, create a throwaway org with a couple of projects. +2. Fire the org-delete API twice in quick succession (e.g. run `rill org delete --force` from two terminals at once, or two parallel `DELETE` API calls). +3. Query the River jobs table in the admin Postgres DB: `SELECT id, kind, state FROM river_job WHERE kind = 'delete_org' ORDER BY id DESC LIMIT 5;` — two separate `delete_org` jobs exist for the same org (a unique-opts job would show one job and one duplicate-skip). +4. Watch admin logs for spurious teardown errors as both workers race on the same projects. The same double-insert can be shown for `plan_changed` by replaying a `subscription` webhook twice from the Orb sandbox. + +### abp-12 [LOW] The autoscaler is dead code behind `disableAutoscaler = true` +- **Category:** readability **Confidence:** high **Location:** `admin/jobs/river/run_autoscaler.go:20`, `:38-42` +- **Problem:** `const disableAutoscaler = true` makes `Work` return immediately, so `allRecommendations`, `shouldScale`, the quota-overshoot math, and the metrics-project recommendation plumbing are unreachable. The worker is always registered (`river.go:122`) and is scheduled if `adm.AutoscalerCron != ""` (`river.go:157-164`) or triggered manually (`EnqueueByKind` → `run_autoscaler`), but every invocation no-ops because of the constant — so even an operator who sets `AutoscalerCron` gets nothing. This is a meaningful amount of untested, unreachable logic (and it hides the latent nil-panic in abp-07). +- **Failure scenario:** Not a runtime failure; it is maintenance drag — readers cannot tell whether autoscaling is intended to work, and the disabled path silently masks bugs. +- **Recommendation:** Either gate solely on the real `AutoscalerCron` config and delete the constant, or remove the worker+scheduling until it is ready, leaving a tracked issue. + +**Verification:** CONFIRMED — `const disableAutoscaler = true` at `admin/jobs/river/run_autoscaler.go:20` and the early return at `:39-42` make every invocation a no-op; the worker is registered at `admin/jobs/river/river.go:122` and scheduled when `adm.AutoscalerCron != ""` (`river.go:157-161`), so even a configured cron produces nothing. + +**Manual Reproduction Steps (for QA):** +1. On a staging admin service, set the autoscaler cron config (`AutoscalerCron`) to run every minute and restart the service. +2. Trigger the job directly if a jobs-trigger endpoint is available (kind `run_autoscaler`), or wait for the cron tick. +3. Check the admin logs: every run logs exactly "skipping autoscaler: disabled by configuration" and no project's slot count ever changes, regardless of recommendations. +4. Confirm in code that no configuration can enable it: `admin/jobs/river/run_autoscaler.go:20` (compile-time constant). + +### abp-13 [LOW] Two owners of the "trial started" email can double-send when an init-failed org is repaired +- **Category:** product-improvement **Confidence:** low **Location:** `admin/billing.go:209` (`RepairOrganizationBilling` sends `SendCreditTrialStarted`), `admin/jobs/river/org_jobs.go:114` and `:155` (start-trial workers send it) +- **Problem:** The "trial started" email has two independent senders: the start-trial workers (`StartTrialWorker`/`StartCreditTrialWorker`) and `RepairOrganizationBilling(initSub=true)`. Within a single worker the email is *not* re-sent on retry — email failure is logged and swallowed (`org_jobs.go:121-123`, `:162-164`), and the email is the last step — so the reviewer's original "retry re-emails" mechanism does not hold. The real duplicate path is cross-owner: if `InitOrganizationBilling` failed leaving `billing_customer_id` empty and a superuser runs `SudoTriggerBillingRepair` (which selects exactly those orgs, `admin/server/billing.go:945-951` → `FindOrganizationIDsWithoutBilling`), `RepairOrganizationBilling` starts the credit trial and sends email #1, while a still-retrying `StartCreditTrialWorker` later succeeds and sends email #2. This is a narrow operational window, not a routine flow. +- **Failure scenario:** An org whose billing init partially failed is repaired by an operator while its start-trial job is retrying → the customer receives two "your trial has started" emails. +- **Recommendation:** Record an "email sent" marker on the trial billing issue (or only email on an absent→present issue transition) and pick a single owner for the trial-started notification. + +**Verification:** PLAUSIBLE — both senders exist as described: `RepairOrganizationBilling(initSub=true)` sends `SendCreditTrialStarted` at `admin/billing.go:209-215` and `StartCreditTrialWorker` sends it at `admin/jobs/river/org_jobs.go:155-161` (email failures swallowed at `:162-164`, so single-worker retries do not re-send); the repair path is reachable via `SudoTriggerBillingRepair` (`admin/server/billing.go:939`). The double-send requires the narrow interleaving of an operator-triggered repair racing a still-retrying start-trial job, which could not be confirmed to occur in practice. + +**Manual Reproduction Steps (for QA):** +1. On staging, arrange for an org's initial billing setup to fail partway (e.g. temporarily break the Orb API credentials while creating a new org, so `billing_customer_id` stays empty and the `start_credit_trial` job keeps retrying). +2. Restore Orb credentials. +3. Before the retrying `start_credit_trial` job's next attempt succeeds, have a superuser run `rill sudo billing repair` (which enqueues repair for all orgs without billing). +4. Let both the repair job and the retrying start-trial job complete, then check the org's billing email inbox: two "your trial has started" emails were received. Timing-sensitive — the repair must complete before the worker's next successful retry. + +## Product Improvements +- **abp-13** (duplicate trial-started emails) is the clearest user-visible polish item — trial onboarding emails should fire exactly once, owned by one code path. +- **Trial re-grant guard is balance-based, not history-based (defensive hardening, low):** `StartCreditTrial`'s idempotency guard is `if balance <= 0 { GrantCustomerCredits(...) }` (`admin/billing.go:285-291`), which cannot distinguish "never granted" from "granted and fully depleted". No current caller re-invokes `StartCreditTrial` on a depleted org (see Verification Notes, abp-08), so this is not an active bug — but if a future path ever does, a depleted org would silently receive a fresh 250-credit trial. Basing the guard on granted-history (issue/ledger presence) rather than current balance would make this robust by construction. +- **Seat billing gap (observed, low):** `BillingReporterWorker.reportOrgUsageMetrics` (`billing_reporter.go:198-255`) reports the `seats` gauge only for orgs that emitted *runtime* usage this hour (`reportedOrgs`). An org whose projects are all hibernated but that still has active members reports zero seats. If seats are billable independent of compute, confirm this is intended; otherwise report seats for all billing-enabled orgs. +- **Provisioner health is opaque (observed, low):** `clickhouse-static` and `kubernetes` `Check` are no-ops, and static `Check` only logs (`static.go:170-206`). There is no capacity metric/alert surfaced to operators; slot exhaustion is discovered by provisioning failures (`static.go:110`). + +## New Feature Ideas +- **Collision-proof, human-readable resource naming helper (S):** a shared util that composes `_` guaranteeing uniqueness under length limits, reused by `clickhouse-static` and the Kubernetes name builder. Directly retires abp-01 and prevents the class of bug. +- **Provisioner capacity metrics + alerting (M):** emit slot-used/slot-total gauges per host (static) and cluster health (ClickHouse/k8s) to OpenTelemetry, with an alert at the existing 80%/70% thresholds instead of log-only. Gives operators lead time before overcommit/exhaustion. +- **Orphaned-resource reconciler (M):** a periodic job that lists `provisioner_resources` (and static assignments) with no live deployment and deprovisions/reclaims them — closes leaks from abp-04 and interrupted teardowns. +- **Billing-issue admin console (M):** an internal view to list/inspect/resolve per-org billing issues (trial, payment-failed invoices, credit state) and manually re-run repair, since today the state lives only in DB rows and daily jobs. +- **Idempotent "reconcile org billing" (L):** treat Orb as the source of truth and reconcile subscription/plan/quotas/issues in one convergent operation (replacing the several overlapping Init/Repair/Start paths), eliminating duplicate-email and re-grant edge cases. +- **Safeguarded autoscaler re-enable (L):** finish and re-enable the disabled autoscaler behind the real `AutoscalerCron` flag with per-project min/max policies, dry-run logging, and the nil-guards from abp-07 — turning abp-12's dead code into a shipped capability. + +## Notes & Missing Test Coverage +- `TestGenerateDatabaseName` (`provisioner_test.go:275-327`) asserts the truncated output but only checks `len <= 63`; it does **not** assert that distinct IDs with long prefixes stay distinct. A collision test would have caught abp-01. +- No concurrency test exists for static slot allocation (abp-02); `static_test.go` provisions sequentially with a forced `nextIdx`. A test running N concurrent `Provision` calls against a capacity-1 host and asserting no overcommit would cover it. +- No tests exercise the retry/partial-failure paths of the credit-depleted (abp-03), trial-end (abp-05), or >100-project teardown/hibernation (abp-04) workers — these are the highest-value untested branches in the job layer. +- `used_flusher` has no test around `Close()` racing an in-flight background flush (abp-06); the shutdown ordering is unverified. +- The Kubernetes provisioner's resource names use the full untruncated `provisionID` (`kubernetes.go:483-491`), so it does **not** share abp-01's identity-collision bug (only its 63-char `sanitizeLabel` truncation, which affects labels, not identity). The Stripe/Orb webhook signature verification paths were spot-checked and looked correct (HMAC + constant-time compare + timestamp skew window). + +## Verification Notes +Every finding was re-traced against the cited code. Summary of changes made during adversarial verification: + +- **Removed abp-08** (trial credit re-grant): **false positive on reachability.** The claimed trigger — `RepairOrganizationBilling(initSub=true)` re-running `StartCreditTrial` on a depleted org — is unreachable. The only enqueuer of `RepairOrgBilling` is `SudoTriggerBillingRepair` (`admin/server/billing.go:945-951`), which operates on `FindOrganizationIDsWithoutBilling` = `SELECT id FROM orgs WHERE billing_customer_id = ''` (`postgres.go:3027-3033`); a depleted org has a populated `billing_customer_id`, so it is excluded. `StartCreditTrialWorker` is a one-time creation job, not re-enqueued for depleted orgs. The underlying observation (guard keys on current balance, not granted-history) is retained as a defensive-hardening item under Product Improvements. `removed_count = 1`. +- **abp-03** location/description corrected to `:110-201` and to note the email-send failure path (`:188-198`) also triggers the no-op-on-retry behavior. +- **abp-04** rewritten to distinguish the two sub-cases precisely: `HibernateInactiveOrgsWorker` has no retry and no pagination (a real permanent gap for >100 projects), while `DeleteOrgWorker` self-heals via River retries up to ~300 projects (then stalls) and additionally risks the 1-hour `JobTimeout`. Verified the FK is `ON DELETE RESTRICT`, `TeardownProject` deletes the project row, `MaxAttempts: 3`, and `JobTimeout: time.Hour`. +- **abp-05** severity downgraded MEDIUM→LOW. Verified that email failure rolls the transaction back (so the "duplicate email" needs the rarer email-success-then-commit-failure interleaving); the more certain effects are the tx held open across email I/O and an email-outage stalling trial-end transitions. Description sharpened accordingly. +- **abp-06** severity downgraded MEDIUM→LOW; confirmed it is a shutdown-only path (`admin.go:162`). The `WaitGroup`-misuse panic is possible but narrow; the concrete issue is the un-joined background goroutine. +- **abp-09** confidence downgraded MEDIUM→LOW; both pagination gaps are real but unlikely at current scale. Confirmed `CreateCustomerCreditAlerts` already uses `ListAutoPaging`, so the fix is precedented. +- **abp-10** broadened to include `PaymentSuccessWorker`, which shares the same read-modify-write shape; confidence kept LOW (requires two concurrent same-org invoice jobs). Verified `PaymentFailed` is unique `ByArgs` including `InvoiceID`, so distinct invoices are distinct concurrent jobs. +- **abp-12** corrected: scheduling is conditional on `AutoscalerCron` (the worker is not in the base `jobConfigs` list), but the `disableAutoscaler` constant no-ops it regardless, so it is dead even when configured. +- **abp-13** confidence downgraded MEDIUM→LOW and **mechanism corrected**: the original "a retry after the idempotent state work re-emails" is wrong (email failure is logged and swallowed, and the email is the terminal step, so retries do not re-send). The real (narrow) duplicate path is the two independent owners — `RepairOrganizationBilling` and the start-trial worker — both firing for an org whose initial billing setup failed and was later repaired. +- **abp-01, abp-02, abp-07, abp-11** confirmed as reported; abp-01's reachability discussion was expanded (no org/project name length cap; per-deployment ClickHouse resource ID makes same-tenant redeploy data-loss the most likely harm) and abp-02's concurrency source (`MaxWorkers: 10`, `ProvisionerMaxConcurrency`) was verified. +- Feature ideas carried forward (effort on the naming helper set to S). diff --git a/audit/admin-database.md b/audit/admin-database.md new file mode 100644 index 000000000000..38d9a17a1225 --- /dev/null +++ b/audit/admin-database.md @@ -0,0 +1,161 @@ +# Admin Database Layer — Code Review + +**Scope:** `admin/database/database.go`, `admin/database/errors.go`, `admin/database/validate.go`, `admin/database/postgres/` (`postgres.go`, `tx.go`, `migrate.go`, `migrations/*.sql`, tests) | **Health:** fair + +## Overview + +This is the admin (Rill Cloud) control-plane persistence layer: a large `DB` interface (~230 methods) with a single Postgres implementation built on `sqlx` + `pgx/v4`. The code is uniform and readable: nearly every method threads the request context through `getDB(ctx)` (which transparently uses a transaction if one is stored in the context), builds parameterized SQL (no string interpolation of user values — SQL injection risk is low), and maps errors through a shared `parseErr` helper that translates `sql.ErrNoRows` and Postgres unique-violation codes into typed `database` errors. Column-level AES-GCM encryption for secrets/variables is implemented correctly (random nonce per encryption, length checks on decrypt). + +The biggest risks are localized rather than systemic: four billing read methods silently bypass the transaction context by calling `c.db` directly; one membership insert path discards its validated/normalized input; and the migration runner takes a session-level advisory lock over a connection pool without pinning a connection. There is also a scattering of robustness gaps (panics in the persistence layer, an unguarded dynamic INSERT, dead/partially-implemented code, and a few unpaginated list queries). Test coverage exists via testcontainers but is concentrated on orgs/projects/pagination/attributes and misses the transactional and concurrency edge cases flagged below. + +## Findings + +### admin-database-01 [MEDIUM] Four billing read methods bypass the transaction context +- **Category:** correctness **Confidence:** high **Location:** `admin/database/postgres/postgres.go:3082,3096,3105,3119` +- **Problem:** Every method in this file reads/writes through `c.getDB(ctx)`, which returns the active transaction when one is stored in the context (see `tx.go:getDB`). But `FindBillingIssuesForOrg`, `FindBillingIssueByTypeForOrg`, `FindBillingIssueByType`, and `FindBillingIssueByTypeAndOverdueProcessed` call `c.db.SelectContext`/`c.db.GetContext` directly, hitting the connection pool and ignoring any transaction in `ctx`. +- **Failure scenario:** A caller opens a transaction with `NewTx(ctx, ...)`, calls `UpsertBillingIssue` (which correctly writes through the tx), then calls `FindBillingIssueByTypeForOrg(txCtx, ...)` expecting to read back what it just wrote. Because the read runs on a different pooled connection outside the transaction, it returns stale/committed data (or `ErrNotFound`), producing inconsistent billing-issue state. **Verified latent, not active:** every current transaction block that touches billing issues — `credit_balance_event_handlers.go:141`, `trial_checks.go:147`, `admin/server/billing.go:832` — only *writes* inside the tx (`UpsertBillingIssue`/`DeleteBillingIssue`, which correctly use `getDB`) and performs its `FindBillingIssue*` reads *before* opening the tx. So no caller reads a billing issue inside a transaction today, but it is a footgun that will silently misbehave the first time someone does. (Category corrected from `concurrency`: this is a transaction-isolation/read-consistency issue, not a data race.) +- **Recommendation:** Replace `c.db` with `c.getDB(ctx)` in all four methods so they honor the transaction context like every other method. + +**Verification:** PLAUSIBLE — the bypass is real in current code: `FindBillingIssuesForOrg` uses `c.db.SelectContext` at `admin/database/postgres/postgres.go:3082`, `FindBillingIssueByTypeForOrg` uses `c.db.GetContext` at 3096, `FindBillingIssueByType` at 3105, and `FindBillingIssueByTypeAndOverdueProcessed` at 3119, while every neighboring method (e.g. `FindOrganizationForBillingCustomerID` at 3072) goes through `c.getDB(ctx)`. However, no current caller reads a billing issue inside a transaction (the tx blocks in `admin/billing/payment/credit_balance_event_handlers.go`, `admin/worker/trial_checks.go`, and `admin/server/billing.go` only write inside the tx), so the failure is latent, not active. + +**Manual Reproduction Steps (for QA):** +Not user-reproducible — no production code path currently reads a billing issue inside an open transaction, so no user-visible misbehavior occurs today. Confirm in code: `admin/database/postgres/postgres.go:3080-3131`, note the four `c.db.SelectContext`/`c.db.GetContext` calls versus `c.getDB(ctx)` used everywhere else; and `admin/database/postgres/tx.go` (`getDB`) for how the transaction is extracted from `ctx`. Alternatively, an engineer can write a Go test that opens `NewTx`, calls `UpsertBillingIssue` in the tx, then calls `FindBillingIssueByTypeForOrg` with the tx context — it will return `ErrNotFound` instead of the just-written row. + +### admin-database-02 [LOW] `InsertOrganizationMemberUser` discards validated attributes in the `ifNotExists` branch +- **Category:** correctness **Confidence:** medium **Location:** `admin/database/postgres/postgres.go:2124` (function `2099`–`2136`) +- **Problem:** The method computes `attrs, err := c.validateAttributes(attributes)`, which normalizes a `nil` map to a non-nil `{}` (see `validateAttributes`, `postgres.go:4096-4099`). The `!ifNotExists` branch correctly inserts `attrs` (line 2106), but the `ON CONFLICT ... DO NOTHING` (`ifNotExists`) branch inserts the raw, un-normalized `attributes` parameter instead (line 2124). Note the two are identical for any non-nil input (`validateAttributes` returns the same map reference); the branches only diverge when `attributes == nil`, giving `{}` vs. `nil`. +- **Failure scenario:** The guest-membership flow reaches this branch with `attributes == nil` (`admin/user.go`, guest-role path), so the two branches persist different values for the same logical operation. **Severity downgraded from medium — the "at worst the INSERT fails" claim is refuted:** the arg is a typed-nil `map[string]any` (a non-nil interface), so pgx routes it through `pgtype.JSON.Set`, whose `src == nil` check is false and which falls to the default `json.Marshal(nil-map)` → `"null"` with `Status: Present`. That stores JSONB `null` (not SQL `NULL`), which satisfies the `NOT NULL` column and is normalized back to `{}` on read. The realistic effect is therefore benign — a stored `null` instead of `{}` — but the validated value is still silently thrown away, and the two branches should not diverge. +- **Recommendation:** Use `attrs` (the validated/normalized value) in both branches. + +**Verification:** CONFIRMED — at `admin/database/postgres/postgres.go:2099-2136`, the `!ifNotExists` branch inserts `attrs` (line 2106) while the `ON CONFLICT ... DO NOTHING` branch inserts the raw `attributes` parameter (line 2124). The divergent branch is exercised in production: `admin/user.go:64` calls `InsertOrganizationMemberUser(..., attributes, true)` from `InsertProjectMemberUser`, and callers of that path can pass `nil` attributes. The effect is benign (JSONB `null` stored instead of `{}`, normalized back to `{}` on read), which is why severity is LOW. + +**Manual Reproduction Steps (for QA):** +The user-visible effect is nil (values are normalized on read), so this is effectively not user-reproducible through the UI. To observe the stored difference, database access is needed: +1. In Rill Cloud, invite a user directly to a *project* (not the org) — e.g. via the project's Members/Share UI or `rill project share` — for a user who is not yet an org member. This triggers the guest-membership path with nil attributes. +2. Separately, add another user as a direct *org* member (org Members UI or `rill user add`). +3. Ask an engineer to run `SELECT user_id, attributes FROM users_orgs_roles WHERE org_id = ''` against the admin Postgres database: the project-invited guest's row shows JSONB `null` while the direct org member's row shows `{}`. +If DB access is unavailable: confirm in code at `admin/database/postgres/postgres.go:2106` vs. `2124` (`attrs` vs. `attributes`). + +### admin-database-03 [MEDIUM] `Migrate` holds a session-level advisory lock across a connection pool +- **Category:** concurrency **Confidence:** medium **Location:** `admin/database/postgres/migrate.go:40-50` +- **Problem:** `Migrate` acquires `pg_advisory_lock($1)` via `c.db.ExecContext` and releases it with `pg_advisory_unlock($1)` via `c.db.ExecContext` in a deferred call. `c.db` is a `*sqlx.DB` pool, and session-level advisory locks are bound to the specific backend connection that acquired them. The lock, the version checks, the per-migration transactions (`migrateSingle` opens its own `BeginTx`), and the unlock can each run on different pooled connections. No `SetMaxOpenConns(1)` is configured (`admin/admin.go` opens the DB without pool limits), so nothing forces a single connection. +- **Failure scenario:** In the common sequential path, `database/sql` reuses the most-recently-used idle connection, so lock and unlock land on the same backend and it works. But if any other query touches the pool during migration, or the connection is recycled (idle/lifetime timeout) mid-run, the deferred `pg_advisory_unlock` executes on a backend that does not hold the lock — it returns `false` and the original lock leaks until that connection is physically closed, blocking all subsequent migrations that wait on `pg_advisory_lock`. +- **Recommendation:** Pin a single connection for the whole migration (`conn, _ := c.db.Conn(ctx)`; run lock, checks, migrations, and unlock on `conn`), or use `pg_advisory_xact_lock` inside a transaction so the lock auto-releases. This is what the referenced `tern` implementation does (it runs on one dedicated connection). + +**Verification:** PLAUSIBLE — `admin/database/postgres/migrate.go:38-50` acquires `pg_advisory_lock` and releases `pg_advisory_unlock` via `c.db.ExecContext` (the shared `*sqlx.DB` pool), and `migrateSingle` opens separate transactions; grep confirms no `SetMaxOpenConns`/connection pinning anywhere in `admin/`. Session-level advisory locks are connection-bound, so the described leak is real but requires a pooled-connection swap (concurrent query or connection recycling) during a migration run — timing-dependent, hence latent rather than deterministically reproducible. + +**Manual Reproduction Steps (for QA):** +Not reliably user-reproducible — the failure depends on connection-pool timing during service startup migrations. Best-effort check for an engineer: +1. Start the admin service (`rill devtool start cloud`) against a Postgres with pending migrations while another process holds open queries on the same DB, or set aggressive `idle_in_transaction`/connection-lifetime limits. +2. After migration completes, run `SELECT * FROM pg_locks WHERE locktype = 'advisory' AND objid IS NOT NULL;` in Postgres — a leftover row for lock key 5103805673824918 indicates a leaked lock; a subsequent admin start will then hang on `pg_advisory_lock`. +How to confirm in code: `admin/database/postgres/migrate.go:38-50` — lock and unlock both run on `c.db` (pool), not a pinned `*sql.Conn`. + +### admin-database-04 [LOW] `FindDeploymentsToStop` can hibernate dev deployments using the prod TTL +- **Category:** correctness **Confidence:** medium **Location:** `admin/database/postgres/postgres.go:647-660` +- **Problem:** The predicate is `(prod_ttl_seconds IS NOT NULL AND used_on + prod_ttl < now()) OR (environment = 'dev' AND used_on + dev_ttl < now())`. The first clause has no environment filter, so it applies to dev deployments too, not just production ones. +- **Failure scenario:** A project configured with `dev_ttl_seconds` longer than `prod_ttl_seconds` (an unusual but permitted configuration) will have its dev deployments hibernated as soon as the shorter prod TTL elapses, ignoring the intended, longer dev TTL. Conversely the intent (prod uses prod TTL, dev uses dev TTL) is only satisfied when `dev_ttl <= prod_ttl`. +- **Recommendation:** Scope the first clause to non-dev deployments, e.g. `(d.environment != 'dev' AND prod_ttl_seconds IS NOT NULL AND ...)`, so each environment respects only its own TTL. + +**Verification:** PLAUSIBLE — confirmed at `admin/database/postgres/postgres.go:647-660`: the query's first clause `(p.prod_ttl_seconds IS NOT NULL AND d.used_on + p.prod_ttl_seconds * interval '1 second' < now())` has no `d.environment` filter, so dev deployments are matched by the prod TTL too. Misbehavior only manifests with the unusual configuration `dev_ttl_seconds > prod_ttl_seconds`, both of which are settable via `rill project edit --prod-ttl-seconds/--dev-ttl-seconds` (`cli/cmd/project/edit.go:62-69,116-117`). + +**Manual Reproduction Steps (for QA):** +1. On a Rill Cloud project, run `rill project edit --prod-ttl-seconds 300 --dev-ttl-seconds 86400` (prod TTL 5 minutes, dev TTL 24 hours). +2. Start a dev deployment for the project (e.g. open the project in dev mode / Rill's cloud dev environment) and then leave it idle. +3. Wait a bit over 5 minutes without using the deployment, letting the hibernation background job run (`rill sudo project get ` can show TTLs; deployment status is visible via `rill project status`). +4. Observe the dev deployment gets stopped/hibernated after ~5 minutes (the prod TTL) instead of surviving up to the configured 24-hour dev TTL. + +### admin-database-05 [LOW] `UpsertProjectVariable` builds an unguarded dynamic INSERT +- **Category:** correctness **Confidence:** high **Location:** `admin/database/postgres/postgres.go:3214-3250` +- **Problem:** The method concatenates one `VALUES (...)` tuple per entry in `vars` into a single multi-row `INSERT ... ON CONFLICT (project_id, environment, lower(name)) DO UPDATE`. It has two edge-case defects: (1) if `vars` is empty the query becomes `INSERT ... VALUES ON CONFLICT ...`, a syntax error (the sibling `DeleteProjectVariables` explicitly guards `len(names) == 0`, but this method does not); (2) if `vars` contains two keys differing only in case (e.g. `FOO` and `foo`), the two generated rows both conflict on the case-insensitive unique index within one statement, which Postgres rejects with "ON CONFLICT DO UPDATE command cannot affect row a second time." +- **Failure scenario:** The current sole caller guards `len(vars) > 0` (`admin/projects.go:273`), so empty input is not hit today, but the exported DB method is unsafe for any future caller; case-colliding variable names fail hard rather than being coalesced. +- **Recommendation:** Return early (or error) when `len(vars) == 0`, and de-duplicate keys by lowercased name before building the statement (mirroring the `lower(name)` conflict target). + +**Verification:** CONFIRMED — `UpsertProjectVariable` (`admin/database/postgres/postgres.go:3213-3262`) builds one `VALUES` tuple per map entry with no empty-map guard and no lowercase de-duplication, while the conflict target is `(project_id, environment, lower(name))`. The sibling `DeleteProjectVariables` (line 3264) does guard `len(names) == 0`. The sole caller guards emptiness (`admin/projects.go:273`, `if len(vars) > 0`), so the empty-input half is latent, but the case-collision half is user-reachable via `rill env push` (a `.env` file may legally contain both `FOO` and `foo`). + +**Manual Reproduction Steps (for QA):** +1. In a Rill project deployed to Rill Cloud, create/edit the local `.env` file to contain two variables differing only in case, e.g. `foo=1` and `FOO=2`. +2. Run `rill env push` for the project. +3. Observe the command fails with a Postgres error like "ON CONFLICT DO UPDATE command cannot affect row a second time" instead of a clear validation message (or the last-written value winning). +(Empty-`vars` half: not user-reproducible today because `admin/projects.go:273` guards `len(vars) > 0`; confirm in code at `admin/database/postgres/postgres.go:3228-3247` — no `len(vars) == 0` guard.) + +### admin-database-06 [LOW] Persistence-layer panics can crash the admin service +- **Category:** tech-debt **Confidence:** high **Location:** `admin/database/postgres/postgres.go:3969-3971,3987-3989,2132-2134,2166-2168,1048-1051` +- **Problem:** `checkUpdateRow`/`checkDeleteRow` panic when `RowsAffected() > 1`, `InsertOrganizationMemberUser`/`UpdateOrganizationMemberUserAttributes` panic when more than one row is affected, and `InsertManagedUsergroups` panics when it does not insert exactly 3 rows. These are "should never happen" invariants, but they are enforced with `panic` inside a shared library used by every admin request handler and background job. +- **Failure scenario:** A future schema change, a missing/duplicated unique constraint, or an unexpected data state turns a recoverable data anomaly into a process-wide crash (or a panicking goroutine) in the cloud control plane, rather than a returned error that the caller can log and surface. +- **Recommendation:** Return a descriptive error instead of panicking for data-dependent conditions; reserve `panic` for genuine programmer errors that cannot depend on database contents. + +**Verification:** CONFIRMED — all five panic sites exist in current code: `checkUpdateRow` panics on `n > 1` (`admin/database/postgres/postgres.go:3971`), `checkDeleteRow` likewise (line 3988), `InsertOrganizationMemberUser` panics on `rows > 1` (line 2133), `UpdateOrganizationMemberUserAttributes` panics on `rows > 1` (line 2167), and `InsertManagedUsergroups` panics on `rows != 3` (line 1050). These conditions depend on database state (unique constraints holding), not purely on programmer error. + +**Manual Reproduction Steps (for QA):** +Not user-reproducible — the panics only fire if a unique constraint is missing or violated (e.g. after a faulty schema migration), which cannot be induced through the product. Confirm in code: `admin/database/postgres/postgres.go` — search for `panic(fmt.Errorf("expected to update` and `panic(fmt.Sprintf("expected 3 rows` (lines 3971, 3988, 2133, 2167, 1050). An engineer can demonstrate by dropping the `users_orgs_roles` unique index in a test database and updating a member's role for a user with two membership rows: the admin request crashes with a panic instead of returning an error. + +### admin-database-07 [LOW] `FindProjectAccessRequests` is unused and would return incomplete rows +- **Category:** tech-debt **Confidence:** high **Location:** `admin/database/postgres/postgres.go:2772-2794` +- **Problem:** This pagination method has no caller anywhere in the repository (the singular `FindProjectAccessRequest`, `FindProjectAccessRequestByID`, `Insert…`, and `Delete…` are all used; only the list variant is not). Additionally, it `SELECT`s only `par.user_id` into `*database.ProjectAccessRequest`, so if it were wired up the returned structs would have empty `ID`, `ProjectID`, and zero `CreatedOn`. +- **Failure scenario:** The feature this method implies — an admin listing of pending project access requests — is not exposed, and whoever finally wires it up inherits a query that silently returns partially-populated records. +- **Recommendation:** Either remove the dead method or complete it: select `par.*` and wire it to a server endpoint so admins can list pending access requests. + +**Verification:** CONFIRMED — `FindProjectAccessRequests` (`admin/database/postgres/postgres.go:2772-2794`) selects only `par.user_id` into `*database.ProjectAccessRequest` (which also has `ID`, `ProjectID`, `CreatedOn` fields), and a repo-wide grep finds no callers: the only references are the interface declaration (`admin/database/database.go:296`) and the implementation itself. + +**Manual Reproduction Steps (for QA):** +Not user-reproducible — the method is dead code with no API endpoint or UI exposing it. Confirm in code: `admin/database/postgres/postgres.go:2772-2794` (SELECT lists only `par.user_id`), and grep the repo for `FindProjectAccessRequests(` — only the interface at `admin/database/database.go:296` and the implementation match. + +### admin-database-08 [LOW] `FindVirtualFilesByOwner` is unbounded; `FindUsers` is dead code +- **Category:** performance **Confidence:** high **Location:** `admin/database/postgres/postgres.go:2921` (`FindVirtualFilesByOwner`); `830` (`FindUsers`); TODO at `admin/database/database.go:313` +- **Problem:** `FindVirtualFilesByOwner` (line 2921) returns *all* of an owner's non-deleted virtual files with no `LIMIT` and no keyset cursor; the interface even carries a `// TODO: pagination` note (`database.go:313`). It has a real caller — `admin/server/virtual_file.go:41` — so this is a genuine unbounded-load path. **Correction:** the reviewer also flagged `FindUsers` (line 830) as loading the whole `users` table on a "hot control-plane path," but `FindUsers` has **zero callers anywhere in the repo** (only the interface definition at `database.go:129` references it — the live user lookups all go through the paginated `FindUsersByEmailPattern`). So `FindUsers` is dead code, not a hot path; the unbounded-scan concern applies only to `FindVirtualFilesByOwner`. +- **Failure scenario:** For a prolific owner, `FindVirtualFilesByOwner` allocates and scans the owner's entire virtual-file set on each call, adding latency and memory pressure. `FindUsers`, being uncalled, poses no runtime risk (it is a maintenance/tech-debt item alongside admin-database-07). +- **Recommendation:** Add keyset pagination (`after…`, `limit`) to `FindVirtualFilesByOwner` consistent with the other finders; remove the unused `FindUsers` (and its interface entry) or, if a future admin tool needs it, add an explicit cap. + +**Verification:** CONFIRMED — `FindVirtualFilesByOwner` (`admin/database/postgres/postgres.go:2921-2933`) has no `LIMIT` or cursor, the interface carries `// FindVirtualFilesByOwner TODO: pagination` (`admin/database/database.go:313`), and it has a live caller at `admin/server/virtual_file.go:41`. `FindUsers` (`postgres.go:830`, unbounded `SELECT u.* FROM users`) has zero callers — grep finds only the interface entry at `admin/database/database.go:129` and the implementation — confirming the corrected dead-code characterization. + +**Manual Reproduction Steps (for QA):** +Practically a performance/scale issue rather than a functional bug; observable only at large data volumes: +1. In a Rill Cloud project, create a very large number of virtual files owned by one user (e.g. many alert/report resources created through the dashboard UI by the same user, which are stored as virtual files). +2. Trigger the endpoint that lists that owner's virtual files (served by `admin/server/virtual_file.go:41`; hit by the runtime/UI when loading the user's managed files). +3. Observe response size and latency grow linearly with the file count — there is no page size cap. +For `FindUsers`: not reproducible — dead code; confirm by grepping the repo for `FindUsers(` (only `admin/database/database.go:129` and `postgres.go:830`). + +### admin-database-09 [LOW] Inconsistent error mapping and fragile migration-version detection +- **Category:** readability **Confidence:** high **Location:** `admin/database/postgres/postgres.go:3280` (`DeleteProjectVariables`), `admin/database/postgres/migrate.go:28` (`FindMigrationVersion`) +- **Problem:** `DeleteProjectVariables` returns the raw driver error (`return err`) instead of routing through `parseErr` like every other method, so its errors are not normalized to the `database` error types callers switch on. Separately, `FindMigrationVersion` detects a missing version table with `strings.Contains(err.Error(), "does not exist")`, matching a driver-specific, locale-sensitive substring rather than the Postgres error code (`42P01`, `undefined_table`). +- **Failure scenario:** Callers of `DeleteProjectVariables` cannot reliably `errors.Is(...)`-classify failures; and a driver/version/locale change to the error text would make `FindMigrationVersion` surface a raw error instead of returning version `0`, breaking first-run bootstrap. +- **Recommendation:** Wrap the delete error with `parseErr`, and detect the missing table via the `pgconn.PgError` code (`42P01`) instead of substring matching. + +**Verification:** CONFIRMED — `DeleteProjectVariables` ends with `return err` on the raw `ExecContext` error (`admin/database/postgres/postgres.go:3283-3284`), unlike sibling methods that wrap with `parseErr`; and `FindMigrationVersion` detects the missing version table via `strings.Contains(err.Error(), "does not exist")` (`admin/database/postgres/migrate.go:28`). The latter is exercised on every fresh bootstrap (`FindMigrationVersion` is called from `admin/admin.go` before migrations create the table), so the fragile match genuinely guards first-run. + +**Manual Reproduction Steps (for QA):** +Not user-reproducible under normal conditions — both issues only surface when errors occur (a failed variable delete surfaces an unnormalized driver error; a pgx error-text change would break first-run bootstrap). Confirm in code: `admin/database/postgres/postgres.go:3283-3284` (`return err` without `parseErr`) and `admin/database/postgres/migrate.go:26-31` (substring match on "does not exist" instead of Postgres error code `42P01`). Sanity check that the happy path works: point a fresh (empty) Postgres at the admin service and start it — bootstrap succeeds only because the substring currently matches pgx's error text. + +## Product Improvements + +- **Expose pending project access requests (from admin-database-07).** The DB already stores access requests and `FindProjectAccessRequests` exists but is unused and incomplete. Completing it and wiring a listing endpoint would let project admins see and act on pending requests instead of only handling them one-by-one by ID. +- **Clearer attribute-limit feedback.** `validateAttributes` (`postgres.go:4096`) hard-codes limits (≤50 keys, ≤256-char string values, alphanumeric/underscore keys) and returns ad-hoc `fmt.Errorf` errors that are not the typed `ErrValidation`. Surfacing these as structured validation errors (like `database.Validate`) would give API consumers consistent, actionable messages. + +## New Feature Ideas + +- **Connection-pinned migration runner (S).** Refactor `Migrate` to run on a single dedicated `*sql.Conn` (or use `pg_advisory_xact_lock`), eliminating the pooled-advisory-lock hazard in admin-database-03 and making concurrent-deploy migrations provably safe. +- **A `WithTx(ctx, fn)` helper that forbids raw `c.db` (M).** Provide a single transaction-scoping helper and a small lint/test that asserts implementation methods never touch `c.db` directly. This structurally prevents the entire class of "bypasses the transaction" bugs (admin-database-01). +- **Down-migrations / migration test harness (M).** There are 95 forward-only migrations and no rollback path or automated per-migration up/down test. A lightweight harness that applies each migration against a testcontainer and checks reversibility would catch schema regressions before deploy. +- **Bulk membership operations (M).** Adding N users/usergroups to an org or project currently issues one round-trip per member. Batch insert/update methods (multi-row INSERTs with `ON CONFLICT`) would cut latency for invite acceptance and bulk imports. +- **Slow-query / query-count observability (S).** `otelsql` already instruments the driver; adding per-method query counting and slow-query logging (especially for the correlated-subquery member listings) would make N+1 and hot-path regressions visible in the control plane. +- **Soft-delete + audit trail for orgs/projects/members (L).** Deletes are hard `DELETE`s relying on FK cascades. A soft-delete/audit-log layer would enable recovery of accidentally deleted projects (the code already special-cases this with the 7-day asset/git-repo retention windows) and give a compliance trail for membership changes. + +## Notes & Missing Test Coverage + +- **Untested transactional/concurrency paths.** `TestPostgres` (testcontainers) covers orgs, projects, pagination, members, attributes, and project variables, but there is no test that (a) reads a billing issue inside a transaction (would expose admin-database-01), (b) exercises `InsertOrganizationMemberUser` with `ifNotExists=true` and `nil` attributes (admin-database-02), or (c) runs `Migrate` concurrently (admin-database-03). These are the highest-value gaps to close. +- **`pgx` nil-map encoding for admin-database-02 (resolved by tracing).** A typed-nil `map[string]any` is a non-nil interface, so pgx's `pgtype.JSON.Set` skips its `src == nil` branch and `json.Marshal`s the nil map to `"null"` with `Status: Present` — i.e. JSONB `null`, which satisfies the `NOT NULL` column and is normalized to `{}` on read. The outcome is benign (hence the severity downgrade), and the fix (use `attrs`) is still correct. A test would still be worthwhile to pin the behavior. +- **Secret exposure to verify at the server layer (out of DB scope).** `magicAuthTokenWithUserFromDTO` (`postgres.go:3570`) and thus `FindMagicAuthTokensWithUser`/`FindMagicAuthTokenWithUser` always decrypt and return the token `Secret`, unlike `FindMagicAuthToken(withSecret=false)` which nils it out. This is likely intentional (to render magic-link URLs), but it is worth confirming that the server does not serialize these `Secret` bytes to unauthorized clients when listing tokens. +- **Minor doc bug.** The comment on `encrypt` (`postgres.go:4048`) says it "returns the base64 encoded ciphertext," but it returns raw bytes; base64 is applied by the caller only for project variables (`UpsertProjectVariable`), not for magic-token secrets. Harmless but misleading. +- **Redundant `lower(...) ILIKE`.** `FindOrganizationMemberUsers`/`CountOrganizationMemberUsers` use `lower(u.email) ILIKE $n` (confirmed at `postgres.go:2029`); `ILIKE` is already case-insensitive, so the `lower()` wrapper is redundant (and could defeat a case-sensitive index if one were added). Cosmetic. The dynamic `not`/`ILIKE` construction here uses only constant fragments plus positional `$n` placeholders, so there is no injection risk. + +## Verification Notes + +Every finding was re-checked against the source at the cited `file:line`. All nine survive verification (no finding was a fabrication or fully unreachable), so **`removed_count` = 0** — but three carried inaccuracies that have been corrected, and reachability was pinned down for the latent ones: + +- **admin-database-01 — category corrected, latency confirmed latent.** The `c.db` bypass at lines 3082/3096/3105/3119 is real (verified). I traced every transaction block that touches billing issues (`credit_balance_event_handlers.go:141`, `trial_checks.go:147`, `admin/server/billing.go:832`) and confirmed each only *writes* inside the tx and *reads* before it, so the bug is latent, not active. Recategorized `concurrency` → `correctness` (it is a transaction-read-consistency issue, not a data race). Severity kept at medium as a latent footgun in billing-critical code. +- **admin-database-02 — severity downgraded MEDIUM → LOW.** The `attrs` vs. `attributes` divergence at lines 2106/2124 is real, but I refuted the "at worst the INSERT fails" half of the failure scenario by tracing `pgtype.JSON.Set`: a typed-nil map marshals to JSONB `null` (Present), which satisfies the `NOT NULL` column and is read back as `{}`. The realistic effect is benign, so this is a low-severity consistency issue, not a medium correctness bug. +- **admin-database-08 — false sub-claim removed.** `FindVirtualFilesByOwner` (line 2921) is genuinely unbounded and has a real caller (`admin/server/virtual_file.go:41`), so that half stands. But the reviewer's characterization of `FindUsers` (line 830) as a "hot control-plane path" is wrong: `FindUsers` has **zero callers** (only the interface definition references it) — it is dead code. Title and body rewritten; confidence raised to high for the corrected claim. +- **admin-database-04 — kept, low/medium.** The missing environment filter on the first clause of `FindDeploymentsToStop` (line 653) is confirmed; the asymmetry (prod respects only prod TTL, but dev is subject to both TTLs) supports the reviewer's reading. Reachability requires the unusual `dev_ttl > prod_ttl` config, so low severity / medium confidence is right. +- **admin-database-05 — kept, verified.** Empty-`vars` produces `VALUES ON CONFLICT` (syntax error) and case-colliding keys hit Postgres's "cannot affect row a second time"; both are real. The sole caller guards `len(vars) > 0` (`admin/projects.go:273`), confirming today's safety and the latent risk for future callers. +- **admin-database-06 / 07 / 09 — kept, verified.** All five panic sites (3971, 3989, 2133, 2167, 1050) exist as described. `FindProjectAccessRequests` (2772) has no caller (only the interface def) and selects just `par.user_id` while `ProjectAccessRequest` has four fields — both halves confirmed. `DeleteProjectVariables` returns a raw error (3280) and `FindMigrationVersion` uses a `strings.Contains(..., "does not exist")` substring match (`migrate.go:28`); critically, `FindMigrationVersion` *is* called at bootstrap (`admin/admin.go:80`) before the version table exists, so the fragile substring match genuinely guards first-run, validating that finding. +- **admin-database-03 — kept, verified.** No `SetMaxOpenConns`/pool pinning exists anywhere in `admin/` (grep confirmed), and `Migrate` runs lock/unlock/`migrateSingle` on the shared `c.db` pool, so the session-advisory-lock-over-a-pool hazard is real. Medium/medium retained. diff --git a/audit/admin-projects-deploy.md b/audit/admin-projects-deploy.md new file mode 100644 index 000000000000..8cb046fbf2c2 --- /dev/null +++ b/audit/admin-projects-deploy.md @@ -0,0 +1,209 @@ +# Admin Projects & Deployments — Code Review +**Scope:** `admin/server/{projects,deployment,organizations,github,repos,reports,alerts,bookmarks,provision,virtual_file,assets,telemetry}.go`, `admin/{projects,deployments,provision,github,alerts,reports,canvases,urls}.go` (plus `admin/server/runtime_jwt.go` and the auth redirect path they call into) | **Health:** fair + +## Overview +This area implements project/deployment CRUD, provisioning orchestration, GitHub integration (OAuth, managed repos, webhooks), editable-deployment checkpointing, custom domains, and magic-token issuance for reports/alerts. The permission model is generally applied consistently (every gRPC handler resolves `ProjectPermissions`/`OrganizationPermissions` before acting), the JWT issuance path (`runtime_jwt.go`) is careful, and asset serving deliberately hardens against SVG/script execution. The code openly acknowledges it is not fault tolerant (`admin/projects.go:21`), and that shows up as the biggest structural risk: multi-step external operations (provision → DB update → git push) are not transactional or idempotent, so failures leave orphaned projects and repos. The most important concrete risks are: (1) a cluster of unguarded `*proj.PrimaryDeploymentID` / `depl` dereferences that panic on hibernated or undeployed projects; (2) editable-deployment deletion that wipes the PVC and deletes the branch even when the checkpoint push fails; (3) a broad public-asset fallback that can expose private project archives to anyone who learns the asset UUID; and (4) a dead conditional that silently drops custom-domain propagation to deployments. + +## Findings + +### admin-projects-deploy-04 [MEDIUM] Unguarded `*proj.PrimaryDeploymentID` dereferences panic on hibernated/undeployed projects +- **Category:** bug **Confidence:** high **Location:** `admin/server/reports.go:320` (`UnsubscribeReport`); `admin/server/virtual_file.go:77` (`CreatePersonalFile`), `:177` (`EditPersonalFile`), `:236` (`DeletePersonalFile`) +- **Problem:** These four handlers dereference `*proj.PrimaryDeploymentID` without the `if proj.PrimaryDeploymentID == nil` guard that every sibling handler has. Verified: `CreateReport`/`EditReport` guard at `reports.go:194/255`; all alert handlers guard (`alerts.go:147/211/283/429/503`); the deployment handlers guard (`deployment.go:520/604`). `PrimaryDeploymentID` is nil for hibernated projects (set nil on delete in `hibernate_expired_deployments.go:84` and `admin/projects.go`) and for projects created with `skip_deploy`. +- **Failure scenario:** A user with `ReadProject` opens the personal-canvas UI on a hibernated (or never-deployed) project, or a recipient clicks an unsubscribe link for a report whose project was later hibernated. `*proj.PrimaryDeploymentID` dereferences a nil pointer; the request panics and is converted to a 500 by the gRPC recovery interceptor instead of a clean `FailedPrecondition`. +- **Recommendation:** Add the same `if proj.PrimaryDeploymentID == nil { return FailedPrecondition }` guard used by the other handlers before each deref. + +**Verification:** CONFIRMED — `admin/server/reports.go:320` (`UnsubscribeReport`) and `admin/server/virtual_file.go:77/177/236` (`CreatePersonalFile`/`EditPersonalFile`/`DeletePersonalFile`) all dereference `*proj.PrimaryDeploymentID` with no nil guard, while sibling handlers (`reports.go:194/255`) guard with a clean `FailedPrecondition`. + +**Manual Reproduction Steps (for QA):** +1. Deploy a project to Rill Cloud and create a scheduled report with your email as a recipient; wait for one report email to arrive. +2. Hibernate the project from a terminal: `rill project hibernate `. +3. Open the "Unsubscribe" link from the report email (or call `POST /v1/organizations/{org}/projects/{project}/reports/{name}/unsubscribe`). +4. Observe an internal-error (HTTP 500 / gRPC Internal) response instead of a clean "project does not have a production deployment" message. +5. Alternatively: while the project is hibernated, open one of its dashboards in the Cloud UI and try to create a personal canvas ("+ New canvas" personal file flow); the create call fails with a 500 for the same reason. + +### admin-projects-deploy-01 [MEDIUM] Editable deployment deletion discards uncommitted work when the checkpoint push fails +- **Category:** data-loss **Confidence:** high **Location:** `admin/deployments.go:413-421` (best-effort `GitPush`), `:462-473` (branch delete), `:476` (deployment delete) +- **Problem:** `DeleteDeploymentInner` checkpoints an editable deployment via `rt.GitPush`, but the error is only logged and execution proceeds unconditionally to deprovision the runtime (wiping the PVC), delete the `rill/xxxx` branch, and delete the deployment row. This is asymmetric with `StopDeploymentInner` (`:340-396`), which is also best-effort on the push but *preserves* the PVC via hibernation, so a failed checkpoint there is recoverable. +- **Failure scenario:** The primary realistic path is a **direct** teardown of a running editable deployment — `DeleteDeployment` RPC (`admin/server/deployment.go:498`) or `TeardownProject` (`admin/projects.go:146`) — where `DeleteDeploymentInner` runs the only checkpoint attempt; if `GitPush` fails (runtime briefly unreachable or a transient GitHub 5xx), the un-pushed browser edits on the PVC are permanently lost with no user-visible signal. Note the TTL path is narrower than a naive read suggests: `hibernate_expired_deployments.go` first *stops* (checkpoints + preserves PVC) and only *deletes* after `StoppedDeploymentRetention`, so TTL-driven data loss additionally requires the earlier stop checkpoint to have failed. +- **Recommendation:** At minimum, do not delete the branch or deprovision when the checkpoint push did not succeed for an editable, managed-branch deployment; return the error and let the retryable job re-run, or snapshot the working tree before deprovisioning. + +**Verification:** CONFIRMED — `admin/deployments.go:413-421` logs the `GitPush` error and falls through unconditionally to deprovisioning (`:434-459`), branch deletion (`:462-473`), and deployment deletion (`:476`); by contrast `StopDeploymentInner` (`:340-396`) hibernates (preserving the PVC) after a failed push. + +**Manual Reproduction Steps (for QA):** +1. This requires inducing a transient GitHub/runtime push failure at teardown time, which is not achievable through the product UI alone; treat as fault-injection testing. +2. API/staging-level repro: create an editable (dev) deployment for a GitHub-connected project, make edits in the browser editor, and do not push/save them. +3. Induce a checkpoint push failure (e.g. in a staging environment, temporarily revoke the GitHub App installation token or block egress from the runtime to github.com). +4. Delete the deployment (`DeleteDeployment` RPC) or delete the project (`rill project delete `). +5. Restore GitHub access and inspect the `rill/xxxx` branch: the unsaved edits are gone, the branch is deleted, and no error was surfaced to the user (only a server-side log line "failed to checkpoint repo changes"). + +### admin-projects-deploy-02 [MEDIUM] `assetHandler` serves private assets (including project archives) whenever the org has any public project +- **Category:** security **Confidence:** medium **Location:** `admin/server/assets.go:186-194` +- **Problem:** For a non-public asset, if the caller lacks `ReadOrg` the handler falls back to `CheckOrganizationHasPublicProjects`; if the org has *any* public project, the asset is served. This fallback is asset-type-agnostic, but `deploy` archives (full project source, uploaded with `Public` unset → false, see `cli/pkg/cmdutil/archive.go:39-45`) share the asset namespace with branding images. The route (`server.go:254`) admits anonymous callers, so `claims` may carry no `ReadOrg`. +- **Failure scenario:** Org `acme` has one public dashboard. `acme`'s private project uploaded a `deploy` archive (asset ID is a UUID). Anyone who learns/leaks that UUID (logs, referrer, a former member) can `GET /v1/assets//download` and retrieve the entire private project source with no org membership. This is UUID-gated (the ID is unguessable), so it is a defense-in-depth exposure rather than a directly enumerable one — but the payload (full source) makes it worth closing. +- **Recommendation:** Scope the public-projects fallback to branding image types only, or gate it on `asset.Public`. Private `deploy` archives should never be reachable via the public-projects path. + +**Verification:** CONFIRMED — `admin/server/assets.go:186-194`: for a non-public asset, a caller without `ReadOrg` is allowed through whenever `CheckOrganizationHasPublicProjects` returns true, with no check on the asset type. Deploy archives are created with `Public` unset (false) in `cli/pkg/cmdutil/archive.go:39-45`, and the route (`admin/server/server.go:254`) accepts unauthenticated requests. + +**Manual Reproduction Steps (for QA):** +1. In an org that has at least one public project, deploy a second, private project from a local folder (`rill deploy` without GitHub), so a `deploy` archive asset is uploaded. +2. As an org member, obtain the archive's asset ID (e.g. from the project's `ArchiveAssetID` via the `GetProject` admin API, or from the admin database in a staging environment). +3. Open a private/incognito browser window (not logged in to Rill) and request `https://admin.rilldata.com/v1/assets//download`. +4. The full private project source archive downloads. Expected behavior would be HTTP 403. +5. Control check: repeat in an org with no public projects; the same request correctly returns 403. + +### admin-projects-deploy-06 [MEDIUM] `LookupCanvas` has an inverted state check: returns NotFound when the spec exists and panics when it does not +- **Category:** correctness **Confidence:** high **Location:** `admin/canvases.go:32-36` +- **Problem:** The guard returns `NotFound` when `canvasResource.Canvas.State != nil` (i.e. exactly when a valid spec *is* available), and otherwise falls through to `res.Resource.Resource.(*runtimev1.Resource_Canvas).Canvas.State.ValidSpec`, which nil-derefs when `State == nil`. This is the negation of the alert/report equivalents, which return the spec directly (`admin/reports.go:47`, `admin/alerts.go`). The single-value type assertion at `:36` also panics if the resource is not a canvas. Net effect: the function can never fulfill its stated contract — it either returns `NotFound` or panics. +- **Failure scenario:** The only current caller is `CreatePersonalFile`'s name-availability check (`virtual_file.go:82-85`) via `generateVirtualFileName`. For a *non-existent* canvas the earlier `rt.GetResource` error path returns `NotFound` before this code runs, so the common case happens to work. But if a canvas with the candidate name *exists* and has a state, `LookupCanvas` reports `NotFound`, so the collision check treats a taken name as free (masked in practice by the random UUID suffix on names); if it exists but has not finished reconciling (`State == nil`), the check panics. Any future caller that actually needs the spec is fully broken. +- **Recommendation:** Invert the guard: `if canvasResource == nil || canvasResource.Canvas == nil || canvasResource.Canvas.State == nil { return nil, NotFound }; return canvasResource.Canvas.State.ValidSpec, nil`, and use the comma-ok type assertion. + +**Verification:** CONFIRMED — `admin/canvases.go:33-36`: the guard returns `NotFound` when `State != nil` (i.e. when a valid spec exists) and otherwise dereferences `...Canvas.State.ValidSpec`, which nil-panics when `State == nil`. The single-value type assertion at `:32/:36` also panics on a non-canvas resource. The contract is inverted versus the code. + +**Manual Reproduction Steps (for QA):** +1. Largely masked in production because the sole caller (`CreatePersonalFile` name-availability check) appends a random UUID suffix and the non-existent-canvas case is handled by an earlier `GetResource` error. +2. To exercise the broken path: in a project that already has a canvas dashboard fully reconciled, drive a `CreatePersonalFile` request whose generated candidate name collides with that existing canvas name; the collision check silently treats the taken name as free (functionally harmless due to the UUID suffix). +3. Confirm in code rather than UI: `admin/canvases.go:33-36` — verify the `State != nil` condition returns `NotFound` and that the fallthrough line dereferences `State.ValidSpec`. + +### admin-projects-deploy-03 [MEDIUM] `SudoUpdateOrganizationCustomDomain` never propagates the change to deployments (dead conditional) +- **Category:** correctness **Confidence:** high **Location:** `admin/server/organizations.go:1021` (reassigns `org`), `:1050` (guard) +- **Problem:** `org` is reassigned to the result of `UpdateOrganization` (whose `CustomDomain` now equals `req.CustomDomain`) before the guard `if req.CustomDomain != org.CustomDomain`. The comparison is therefore always false, so `UpdateOrgDeploymentAnnotations` (`admin/projects.go:308`) is never called. `UpdateOrganization` itself computes `nameChanged` correctly *before* its update — this handler got the ordering wrong. +- **Failure scenario:** A superuser sets or changes an org's custom domain. Deployment annotations (`organization_custom_domain`) and the `frontend_url` the runtime uses to build report/alert email links are not refreshed, so those links keep pointing at the old/absent domain until an unrelated deployment update happens to recompute annotations. Superuser-only and eventually self-healing, but user-visibly wrong in the interim. +- **Recommendation:** Capture `oldCustomDomain := org.CustomDomain` before the `UpdateOrganization` call and compare against it. + +**Verification:** CONFIRMED — `admin/server/organizations.go:1021` reassigns `org` to the `UpdateOrganization` result (whose `CustomDomain == req.CustomDomain`) before the guard `if req.CustomDomain != org.CustomDomain` at `:1050`, so the comparison is always false and `UpdateOrgDeploymentAnnotations` is never called. + +**Manual Reproduction Steps (for QA):** +1. As a superuser, set a custom domain on an org: `rill sudo org set-custom-domain ` (or the `SudoUpdateOrganizationCustomDomain` API). +2. Immediately trigger a scheduled report or alert email for a project in that org. +3. Inspect the links in the resulting email: they still point at the old/default `rilldata.com` URL rather than the new custom domain. +4. Confirm in code: `admin/server/organizations.go:1050` — the `if req.CustomDomain != org.CustomDomain` branch is dead because `org` was reassigned at `:1021`, so `UpdateOrgDeploymentAnnotations` never runs. +5. Note it self-heals: any later unrelated deployment update recomputes annotations, after which links become correct. + +### admin-projects-deploy-07 [MEDIUM] GitHub webhook is processed synchronously despite a "moved to background" contract +- **Category:** performance **Confidence:** high **Location:** `admin/server/github.go:905-933` (handler), `admin/github.go:344-346` (docstring), `:362-411` (`processGithubPush`) +- **Problem:** `ProcessGithubEvent` is documented as moving work "to the background and returns a nil error," but `processGithubPush` runs inline: it fans out over every project matching the pushed remote and every prod deployment, calling `TriggerParser` sequentially. `TriggerParser` (`admin/projects.go:452-473`) opens a fresh runtime client (JWT issue + gRPC dial) and makes a `CreateTrigger` RPC per deployment. The webhook handler blocks on all of it and returns `http.StatusBadRequest` on any error (`:928`), which GitHub treats as a delivery failure and redelivers. `context.Background()` also detaches the work from the request lifecycle without actually making the response asynchronous. +- **Failure scenario:** A widely-shared remote maps to many projects/deployments, or one runtime is slow/unreachable. Processing exceeds GitHub's ~10s webhook timeout; GitHub marks it failed and redelivers, re-triggering parsers for all deployments (including ones that already succeeded — harmless per-parse but wasteful). For the common single-project remote this is a non-issue; the docstring is simply wrong. +- **Recommendation:** Enqueue a job (like the reconcile jobs) and return 200 immediately; bound concurrency and per-deployment timeouts; return 2xx for transient per-deployment failures so GitHub does not storm-retry. At minimum, correct the docstring to match the synchronous behavior. + +**Verification:** CONFIRMED — `ProcessGithubEvent`'s docstring (`admin/github.go:344-346`) claims work is moved "to the background," but `processGithubPush` (`admin/github.go:362-411`) runs inline, iterating over all matching projects/deployments and calling `TriggerParser` sequentially; the webhook handler (`admin/server/github.go:926-930`) blocks on it and returns HTTP 400 on any error, prompting GitHub redelivery. `context.Background()` here only detaches cancellation, it does not make the call asynchronous. + +**Manual Reproduction Steps (for QA):** +1. Not user-reproducible through normal single-project flows (the common case completes well within GitHub's ~10s timeout). +2. To exercise the slow path in a staging setup: connect several projects/prod deployments to one shared GitHub remote, make one runtime slow or unreachable, then push a commit to that remote. +3. In the GitHub repo's Settings > Webhooks > Recent Deliveries, observe the delivery time out / show a non-2xx response and get redelivered. +4. Confirm in code: `admin/github.go:344-346` docstring vs the synchronous `processGithubPush` at `:362-411`, and the blocking call at `admin/server/github.go:926`. + +### admin-projects-deploy-08 [MEDIUM] `CreateProject` leaves an orphaned project (and possibly a managed GitHub repo) on partial failure +- **Category:** correctness **Confidence:** high **Location:** `admin/projects.go:24-135` (commit at `:66`, then `CreateDeployment` `:96`, then `UpdateProject` `:108`); handler `admin/server/projects.go:610-613` +- **Problem:** The project row and members are committed (`:66`) before provisioning. If `CreateDeployment` (`:96`) or the subsequent `UpdateProject` that sets `PrimaryDeploymentID` (`:108`) fails, `CreateProject` returns the error but the committed project persists with no primary deployment and no rollback. The handler (`server/projects.go:610`) just returns the error with no compensating cleanup. If the project used a freshly-created managed Git repo, that repo is also orphaned (see finding 11); the `+10` quota slack in `quotaManagedRepos` (`admin/github.go:438-444`) explicitly budgets for these leaks. +- **Failure scenario:** A quota check inside `CreateDeployment` or a transient job-scheduling failure aborts creation. The user is left with a half-created project that blocks re-creating the same name and has no deployment; recovery requires manual/admin intervention. +- **Recommendation:** Make creation idempotent/compensating (the file's own TODO at `:21`): on downstream failure, tear down the deployment and delete the project, or move the whole flow to a retryable reconcile job keyed on project ID. Add a GC job for unreferenced managed repos. + +**Verification:** CONFIRMED — `admin/projects.go`: the project row + members are committed at `:66`, before `CreateDeployment` (`:96`) and the `UpdateProject` that sets `PrimaryDeploymentID` (`:108-124`). If either fails, `CreateProject` returns the error with no rollback of the committed project, leaving it with no primary deployment. The file's own TODO at `:21` acknowledges the lack of fault tolerance. + +**Manual Reproduction Steps (for QA):** +1. Requires forcing provisioning to fail after the project row commits; not directly triggerable from the UI. +2. Staging repro: set the org's deployment/slot quota so that provisioning a new deployment will fail, or make the runtime provisioner temporarily unreachable. +3. Attempt to create + deploy a project (`rill deploy` / the create-project UI flow). +4. Observe the request errors out, then list projects (`rill project list`): the half-created project exists but has no running deployment, and re-creating a project with the same name is blocked by the name collision. +5. Confirm in code: `admin/projects.go:66` (commit) precedes `:96`/`:108` with no compensating cleanup on error. + +### admin-projects-deploy-05 [LOW] `GetRepoMeta` dereferences a nil `depl` for non-deployment callers +- **Category:** bug **Confidence:** medium **Location:** `admin/server/repos.go:58-65` (assigns `depl` only when owner is a deployment), `:92-93` (`depl.Branch`, `depl.Editable`) +- **Problem:** `depl` is only set when `claims.OwnerType() == auth.OwnerTypeDeployment`. For a Git-backed project the handler falls through to build the response using `depl.Branch`/`depl.Editable`, so a non-deployment caller reaches the deref with `depl == nil`. The permission gate (`ReadProdStatus || ReadDevStatus`, `:31`) admits ordinary users. +- **Failure scenario:** The only real caller is the runtime's admin repo driver (`runtime/drivers/admin/repo.go:895`), which always uses a deployment token, so this never fires through normal flows. It is reachable only by a project member with `ReadProdStatus` deliberately calling the exposed gateway RPC (`GET /v1/projects/{project_id}/repo/meta`) for a GitHub-connected project, yielding a panic → 500. Downgraded from the prior report's medium severity because no product surface triggers it. +- **Recommendation:** Guard the two field accesses (only populate `GitBranch`/`Editable` when `depl != nil`, or require a deployment claim for this RPC). + +**Verification:** CONFIRMED — `admin/server/repos.go:58-65` assigns `depl` only when `claims.OwnerType() == auth.OwnerTypeDeployment`; for a GitHub-connected project the handler then builds the response with `depl.Branch`/`depl.Editable` at `:92-93`, so a non-deployment caller reaches a nil dereference. The permission gate at `:31` (`ReadProdStatus || ReadDevStatus`) admits ordinary members. + +**Manual Reproduction Steps (for QA):** +1. Connect a project to GitHub (so it has `GitRemote`/`GithubInstallationID` and no archive asset). +2. As a normal project member (with read access), call the gateway RPC directly: `GET /v1/projects/{project_id}/repo/meta` using your user auth token (not a deployment token). +3. Observe an internal-error (HTTP 500) response caused by the nil `depl` dereference. +4. Note this does not fire in normal product flows because the only real caller (the runtime admin repo driver) always uses a deployment token. + +### admin-projects-deploy-09 [LOW] `GetBookmark` lets any project reader fetch another user's private bookmark +- **Category:** security **Confidence:** high **Location:** `admin/server/bookmarks.go:39-70` +- **Problem:** `GetBookmark` checks only `permissions.ReadProject` and never verifies `bookmark.UserID == claims.OwnerID()` for non-shared/non-default bookmarks. `UpdateBookmark` (`:158`) and `RemoveBookmark` (`:202`) both enforce that ownership check, and `ListBookmarks` (`:23`) filters by owner — so this is an inconsistency, not a deliberate exception. +- **Failure scenario:** User A creates a private bookmark (personal dashboard state/filters). User B, a member of the same project, calls `GetBookmark` with A's bookmark ID (a UUID) and reads A's private view state. Cross-user read, UUID-gated, non-sensitive payload. +- **Recommendation:** Mirror the ownership check from `UpdateBookmark`: reject when the bookmark is neither shared nor default and `bookmark.UserID != claims.OwnerID()`. + +**Verification:** CONFIRMED — `admin/server/bookmarks.go:39-70` (`GetBookmark`) checks only `permissions.ReadProject` and never compares `bookmark.UserID` to `claims.OwnerID()`, whereas `UpdateBookmark` and `RemoveBookmark` both enforce `if !bookmark.Shared && !bookmark.Default && bookmark.UserID != claims.OwnerID()` and `ListBookmarks` (`:23`) filters by owner. + +**Manual Reproduction Steps (for QA):** +1. As User A, open a dashboard in a shared project and create a private (non-shared, non-default) bookmark; capture its bookmark ID. +2. As User B (a different member of the same project), call `GET` bookmark by ID — the `GetBookmark` RPC (e.g. via the API `GET /v1/bookmarks/{bookmark_id}`) with User A's bookmark ID. +3. Observe User B receives User A's private bookmark (its saved filters/view state) instead of a permission-denied error. +4. Control check: attempt the same ID with `RemoveBookmark`/`UpdateBookmark` as User B — those correctly return PermissionDenied. + +### admin-projects-deploy-11 [LOW] Managed GitHub repo is orphaned when its DB row insert fails +- **Category:** correctness **Confidence:** high **Location:** `admin/github.go:263-274` +- **Problem:** `CreateManagedGitRepo` creates the repo on GitHub (`:263`), then inserts the `managed_git_repos` row (`:267`). If the insert fails, the GitHub repo is left behind with no tracking row and is never cleaned up. The `quotaManagedRepos` `+10` buffer (`:438-444`) is an explicit workaround, but repos accumulate against the org's real GitHub org. +- **Failure scenario:** A DB hiccup after `CreateManagedRepo` returns leaves a private repo in the managed GitHub org that Rill no longer references; over time these accumulate. +- **Recommendation:** On insert failure, best-effort delete the just-created repo (`DeleteManagedRepo` already exists), and/or add a reconciliation job that deletes managed-org repos with no corresponding DB row. + +**Verification:** CONFIRMED — `admin/github.go:263-274` (`CreateManagedGitRepo`) creates the GitHub repo (`:263`) then inserts the `managed_git_repos` row (`:267`); on insert failure it returns the error with no cleanup of the just-created repo, and `quotaManagedRepos` (`:438-444`) budgets `+10` slack for exactly these leaks. + +**Manual Reproduction Steps (for QA):** +1. Not user-reproducible through normal flows; requires a DB failure between the GitHub create and the row insert (fault injection). +2. Staging repro: deploy a project using a managed Git repo (the "Rill-managed" GitHub option) and induce a DB error on `InsertManagedGitRepo` (e.g. temporarily break the DB connection right after repo creation). +3. Inspect the managed GitHub org: a new private repo named `-` exists with no corresponding `managed_git_repos` row, and nothing ever deletes it. +4. Confirm in code: `admin/github.go:263-274` — no compensating `DeleteManagedRepo` on the insert-error path. + +### admin-projects-deploy-10 [LOW] `githubAuthCallback` is missing a `return` after the non-collaborator redirect +- **Category:** bug **Confidence:** high **Location:** `admin/server/github.go:885-889` +- **Problem:** When `!ok` (user is not a collaborator), the handler writes a redirect to the retry page but does not `return`. Execution continues to `sess.Save` (`:892`) and a second `http.Redirect` (`:898-902`). The equivalent guard in `githubConnectCallback` (`:711-716`) correctly returns. +- **Failure scenario:** Corrected from the prior report: because `http.Redirect` at `:888` calls `WriteHeader(307)` and writes a body, the response headers (`Location: `) are committed before the fallthrough runs, so the browser *does* land on the retry page — the user is **not** routed past the gate. The observable defects are that the subsequent `sess.Save` cannot persist the cleared session fields (headers already sent) and Go logs a "superfluous response.WriteHeader call". Still a real bug worth the one-line fix. +- **Recommendation:** Add `return` after the retry redirect, matching `githubConnectCallback`. + +**Verification:** CONFIRMED — `admin/server/github.go:885-889`: the `if !ok` (non-collaborator) branch writes the retry redirect but has no `return`, so execution falls through to `sess.Save` (`:892`) and a second `http.Redirect` (`:898-902`). The equivalent guard in `githubConnectCallback` (`:711-716`) correctly returns. As noted, the first `http.Redirect` commits headers so the browser still lands on the retry page; the real defects are a non-persisted session save and a "superfluous WriteHeader" log line. + +**Manual Reproduction Steps (for QA):** +1. Start the GitHub user-auth flow (`/github/auth/login?remote=`) as a user who is NOT a collaborator on the target GitHub repo. +2. Complete the GitHub OAuth authorization. +3. Observe the browser lands on the retry page (correct end state) — the gate is not bypassed. +4. Confirm the underlying bug in server logs: look for a "http: superfluous response.WriteHeader call" warning emitted for this request, indicating the fallthrough. +5. Confirm in code: `admin/server/github.go:889` — missing `return` after the redirect, versus `:715` in `githubConnectCallback`. + +### admin-projects-deploy-12 [LOW] `assetHandler` commits `200 OK` before the object read, so a fetch failure is reported as success +- **Category:** bug **Confidence:** high **Location:** `admin/server/assets.go:227` (`WriteHeader(http.StatusOK)`) vs `:230-236` (object open + error return) +- **Problem:** The handler calls `w.WriteHeader(http.StatusOK)` at `:227`, then opens the GCS object at `:230`. If `NewReader` fails, it returns `httputil.Error(500, ...)` (or 408), but `httputil.WriteError` (`runtime/pkg/httputil/httputil.go:53-70`) then calls `w.WriteHeader(code)` on an already-committed response — a superfluous, ignored write. The client receives `HTTP 200` with the asset's declared `Content-Type` (set at `:213/:219`) and a JSON error body, i.e. a corrupt/empty download reported as success. +- **Failure scenario:** A transient GCS error (or a deleted/misplaced object) on an otherwise-authorized download returns 200 with a mislabeled error body; a client streaming a project archive or image treats it as a successful, valid file. +- **Recommendation:** Move `WriteHeader(http.StatusOK)` to after `NewReader` succeeds (open the object first, then set status and stream). Errors during the subsequent `io.Copy` still cannot change the status, but the pre-stream open failure can and should surface correctly. + +**Verification:** CONFIRMED — `admin/server/assets.go:227` calls `w.WriteHeader(http.StatusOK)` before the object is opened at `:230` (`NewReader`). If `NewReader` fails, the returned `httputil.Error(500, ...)` cannot change the already-committed 200 status, so the client sees HTTP 200 with the asset's declared Content-Type and a JSON error body. + +**Manual Reproduction Steps (for QA):** +1. Requires the GCS object to be missing/unreadable for an otherwise-authorized asset; fault injection in staging. +2. Create/authorize an asset whose DB row exists but delete the backing object from the storage bucket (or point `asset.Path` at a non-existent object). +3. Request `GET /v1/assets//download` as an authorized caller. +4. Observe the response status is `200 OK` (with the asset's Content-Type) but the body is a JSON error, i.e. a corrupt/empty download reported as success. +5. Confirm in code: `admin/server/assets.go:227` `WriteHeader(200)` precedes the `NewReader` open at `:230`. + +## Product Improvements +- **Provisioning failures are invisible to users.** When `CreateProject`/deployment provisioning fails partway (finding 08), the user gets a raw error and a half-created project with no in-product recovery. Surfacing deployment status/last-error and a "retry/repair" action would remove a class of support tickets. +- **No safeguard around editable-deployment teardown data loss.** Editable deployments are torn down with a best-effort checkpoint (finding 01). Users editing dashboards in the browser have no "unsaved changes" indicator or confirmation before teardown/expiry, and no signal when a final checkpoint fails. +- **Custom-domain changes should reconcile immediately and verifiably** (finding 03) — today even the intended propagation is dead code, and there is no status showing whether deployments have picked up the new domain. + +## New Feature Ideas +- **Idempotent project-provisioning saga (L).** Replace the inline `CreateProject`/`RedeployProject` orchestration with a retryable, compensating background job keyed on project ID (the file's own TODO). Eliminates orphaned projects/repos and makes creation resumable. +- **Garbage-collector for orphaned managed repos & assets (M).** Periodic job that deletes managed-org GitHub repos and uploaded assets with no referencing DB row / use case. Directly retires the `+10` quota hack (findings 08, 11) and the asset "background delete" TODO. +- **Job-queue-based webhook ingestion (M).** Accept the GitHub webhook, persist the event, ack 200 immediately, and process reconcile fan-out asynchronously with bounded concurrency and retries. Fixes the 10s-timeout/retry risk (finding 07) and scales to popular shared remotes. +- **Unsaved-changes guard for editable deployments (M).** Track whether the runtime repo has un-pushed changes and (a) block/confirm teardown, (b) show an indicator in the UI, (c) refuse to delete the branch if the final checkpoint failed. Prevents the data loss in finding 01. +- **Scope the public-asset fallback to branding types (S).** Restrict the "org has public projects" download path to image asset types so private `deploy` archives can never be served through it (finding 02); small change, meaningful hardening. +- **Deployment status & provisioner-error surfacing in the UI (M).** Expose `DeploymentStatus`/`StatusMessage` and provisioner-resource errors in the project settings view so users can self-diagnose stuck/errored deployments. + +## Notes & Missing Test Coverage +- **Redirect-domain handling is safe** despite `WithCustomDomainFromRedirectURL` (`admin/urls.go:116`) trusting an arbitrary host: the only caller (`admin/server/auth/handlers.go:321`) operates on a redirect validated by `validateRedirectURL` at login start (which requires `IsSafeRedirectURL` or a known custom domain). No change needed, but the coupling is implicit and worth a comment/test. +- **`UpdateDeploymentsForProject` (`admin/deployments.go:139-175`)** writes `prodErr` from goroutines; this is safe (not a data race) because deployment IDs are unique, so at most one goroutine matches `*p.PrimaryDeploymentID == d.ID` and writes, and the read follows `grp.Wait()`. A test pinning the single-writer intent would help. +- **`GetVirtualFile`/`DeleteVirtualFile` (`admin/server/repos.go:162-241`)** take `req.Environment` from the client and gate only on `ReadProdStatus || ReadDevStatus`, with no per-file owner check (unlike `GetPersonalFile`). Paths carry a random UUID suffix so this is not readily exploitable, but a test/tightening around cross-environment and cross-owner access would be prudent. +- **No tests observed** for: nil `PrimaryDeploymentID` paths in report/personal-file handlers (finding 04); `LookupCanvas` state handling (finding 06); custom-domain propagation (finding 03); partial-failure rollback in `CreateProject` (finding 08); and editable-deployment delete when the checkpoint push fails (finding 01). These are exactly the risky branches and the highest-value additions. + +## Verification Notes +Every one of the 11 original findings was re-checked against the code; all describe behavior that is actually present, so none were removed (`removed_count = 0`). Corrections applied: +- **Finding 01 (delete data-loss): HIGH → MEDIUM.** The behavior is confirmed, but the prior report's headline TTL scenario is imprecise: `hibernate_expired_deployments.go` *stops* (checkpoints + preserves the PVC) before it *deletes*, so the TTL path already attempts a checkpoint and preserves data on the first pass. The genuine loss window is a **direct** teardown of a running editable deployment (`DeleteDeployment` RPC / `TeardownProject`). Reworded the scenario accordingly. +- **Finding 05 (GetRepoMeta nil `depl`): MEDIUM → LOW.** Traced callers: the only real caller is the runtime with a deployment token, so no product surface triggers the nil deref; it is reachable only by a deliberate direct gateway call. Severity lowered, confidence kept medium. +- **Finding 10 (missing `return`): scenario corrected.** The prior claim that the user is "routed past the retry gate" is wrong — the first `http.Redirect` commits the response headers, so the browser lands on the retry page. The real effects are a non-persisted session save and a superfluous-`WriteHeader` log. Kept LOW. +- **Findings 02, 03, 06, 07, 08, 09, 11: confirmed** with locations/line numbers checked (sibling guards for 04 verified at `alerts.go:147/211/283/429/503`, `reports.go:194/255`; `quotaManagedRepos` `+10` verified at `github.go:438-444`; archive `Public` default-false verified at `archive.go:39-45`). Minor wording tightened on 02 (UUID-gated defense-in-depth) and 03 (superuser-only, self-healing). +- **Added finding 12 (assetHandler 200-before-read):** a real correctness bug in scope that the prior pass missed — `WriteHeader(200)` at `assets.go:227` precedes the object open at `:230`, so a fetch failure is delivered as HTTP 200. +- Findings are re-ordered most-significant first. No critical/high items survive verification; health remains **fair**. diff --git a/audit/ai.md b/audit/ai.md new file mode 100644 index 000000000000..09b099f6d060 --- /dev/null +++ b/audit/ai.md @@ -0,0 +1,198 @@ +# AI Assistant / Agents — Code Review + +**Scope:** `runtime/ai/*.go` (router/analyst/developer/feedback agents, orchestration in `ai.go`, tool implementations: file_read/write/search/list, query_sql, metrics_view_*, list_buckets/objects, list_tables, show_table, create_chart, navigate, canvas_get, project_status, develop_file), `runtime/ai/instructions/*`, `mcp.go`, `util.go`. Cross-referenced: `runtime/server/chat.go`, `runtime/server/mcp.go`, `runtime/repos.go`, `runtime/drivers/file/repo.go`, `runtime/drivers/admin/repo.go`, `runtime/resolvers/sql.go`, `runtime/metricsview/executor/*`, `runtime/drivers/claude/claude.go`, `runtime/drivers/sqlite/catalog.go`. | **Health:** needs-attention + +## Overview +This package implements a well-structured, session-based agent framework: a `Runner` registers typed tools, a `Session` records a call-tree of messages, and `Complete` drives an LLM tool-call loop shared by chat, scheduled reports, and the MCP server. Access control is generally applied consistently (per-tool `CheckAccess` + `ApplySecurityPolicy` on metrics resources — verified in `metrics_view_list.go`). Tool outputs are deliberately bounded (row caps, snippet limits, truncation). The biggest risks are on the developer-tool surface, where LLM-generated inputs reach the filesystem and OLAP connectors: file-path arguments are not constrained to the project root (path traversal), and `query_sql` runs arbitrary statements while advertising itself as read-only. There is also a real concurrency defect in the streaming path where the message-subscriber send can strand the producer under the session lock on context cancellation, leaking the request goroutine. Secondary issues involve limit validation, a latent fail-open branch in shared-session access, error/stack-trace handling that leaks into the LLM context, and a latent message-persistence hazard in `Flush`. + +## Findings + +### ai-01 [HIGH] File tools allow path traversal outside the project root +- **Category:** security **Confidence:** high **Location:** `runtime/ai/file_read.go:52`, `runtime/ai/file_write.go:61`, `runtime/ai/develop_file.go:59` +- **Problem:** `ReadFile`/`WriteFile`/`DevelopFile` take an LLM-controlled `args.Path`, prepend `/` if missing, and pass it straight to `Runtime.GetFile/PutFile/DeleteFile`. Those call `repo.Get/Put/Delete`, which in both the local driver (`drivers/file/repo.go:74,128,178`) and the cloud driver (`drivers/admin/repo.go:150,241,…`) do `filepath.Join(root, path)` with **no containment check**. `filepath.Join` cleans `..` segments, so the join escapes `root`. The leading-`/` normalization does not help — verified empirically: `filepath.Join("/srv/rill/projects/abc", "/../../../../etc/passwd")` = `/etc/passwd`, and `"/models/../../../../../etc/passwd"` also resolves to `/etc/passwd`. `runtime/repos.go` performs no validation before delegating to the driver. +- **Failure scenario:** A prompt-injection payload embedded in project data, a bucket object name, a table/column comment, or a shared/forked conversation steers the developer agent to `read_file` `../../.env`, cloud-credential files, or another project's files on the runtime host — then exfiltrate the contents in its reply. `write_file`/`develop_file` with the same traversal can create or overwrite files outside the project where the repo is editable (always in Rill Developer; editable cloud repos). In Rill Cloud this crosses the project sandbox on a shared runtime host. Preconditions: `UseAI` + `EditRepo` claims and the `developer_agent` feature flag; these tools are `internal` (not exposed to external MCP clients), but the path argument is still model-chosen inside the chat agent. +- **Recommendation:** Constrain paths in the AI tools before hitting the repo: reject inputs containing `..` segments and verify the cleaned relative path is local (e.g. `filepath.IsLocal` on the leading-slash-stripped form, or `strings.HasPrefix(filepath.Join(root, clean), root+string(os.PathSeparator))`). Add the same guard in the repo drivers as defense-in-depth, since these APIs now receive untrusted, model-generated paths. +- **Note:** `file_search.go` is **not** a traversal vector (removed from the prior draft's location list): it lists files via `ListGlob`/`os.DirFS`, which rejects `..`, and only reads paths the walk returns (all within root). + +**Verification:** CONFIRMED — `file_read.go:52-56`, `file_write.go:61-85`, and `develop_file.go:59-61` prepend a leading `/` and pass the model-chosen path straight to `Runtime.GetFile/PutFile/DeleteFile`. Those (`runtime/repos.go:21-87`) delegate to `repo.Get/Put/Delete` with no validation, and the local driver does `filepath.Join(c.root, filePath)` with no containment check (`drivers/file/repo.go:74,113,128,178`); the admin driver is identical (`drivers/admin/repo.go:150,221,257`). `filepath.Join` cleans `..`, so a leading-`/` path like `/../../etc/passwd` escapes root. + +**Manual Reproduction Steps (for QA):** +1. In Rill Developer, open a project and start an AI chat with the developer agent enabled (requires the `developer_agent` feature flag, `UseAI` and `EditRepo`). +2. Ask the agent to "read the file at `../../../../etc/passwd`" (or on the write side, "create a file at `../../escaped.txt`"). +3. Observe the agent returns contents of a file outside the project root, or creates a file outside the project directory. +4. If UI phrasing resists, confirm in code: `runtime/ai/file_read.go:52` (no `..` rejection before `GetFile`) and `runtime/drivers/file/repo.go:74` (`filepath.Join(c.root, filePath)` with no prefix check). + +### ai-02 [HIGH] Subscriber send under the session lock can strand the producer on cancellation (goroutine leak / hang) +- **Category:** concurrency **Confidence:** high **Location:** `runtime/ai/ai.go:898-900` (`AddMessage`), unbuffered channel at `runtime/ai/ai.go:656-661` (`Subscribe`), consumed at `runtime/server/chat.go:376-407` +- **Problem:** `AddMessage` holds `s.mu.Lock()` and does a blocking send `sub <- msg` on an **unbuffered** channel (`Subscribe` → `make(chan *Message)`) with no `select` on any cancellation signal. In `CompleteStreaming`, the only reader is a goroutine whose `select` also has a `case <-ctx.Done(): return`. When the context is canceled (client stop, disconnect, or the completion timeout) while a message is in flight, Go may pick the `ctx.Done()` case over the `sub` receive; the reader returns and the producer's `sub <- msg` never rendezvous, blocking permanently while holding `s.mu`. +- **Failure scenario:** During a streaming completion the client disconnects. The agent loop has just received an LLM response and calls `AddMessage` (e.g. `ai.go:1356` for a text block, or `ai.go:964` for a tool-call message) → blocks forever on the send. `session.CallTool`/`Complete` never returns, so `CompleteStreaming` never returns, the deferred `Unsubscribe`/`Flush` never run, the session is never persisted, and the request goroutine (holding `s.mu`) is leaked for the process lifetime. `Unsubscribe` itself would also block trying to acquire `s.mu`. Repeated cancellations accumulate leaked goroutines and permanently wedge each affected session object. +- **Recommendation:** Never block on a channel send while holding a lock, and make the send cancellation-aware. Have the reader close a `done` channel on exit and use `select { case sub <- msg: case <-done: }`, or use buffered channels with a non-blocking send, or notify subscribers outside the critical section. Ensure `Unsubscribe` can always unblock the producer. + +**Verification:** CONFIRMED — `Subscribe` creates an unbuffered `make(chan *Message)` (`ai.go:657`); `AddMessage` holds `s.mu.Lock()` (`ai.go:893-894`) and does a blocking bare `sub <- msg` with no `select` (`ai.go:898-900`). The only reader is the `CompleteStreaming` goroutine whose `select` also has `case <-ctx.Done(): return` (`chat.go:386-388`), so on cancellation the reader can exit while the producer is stranded on the send, holding `s.mu` forever. `Unsubscribe` (`ai.go:664-669`) then blocks on `s.mu` too. + +**Manual Reproduction Steps (for QA):** +1. Start an AI chat completion that streams (e.g. a longer analyst/developer prompt that produces several tool calls and text blocks). +2. While the response is still streaming, abruptly disconnect the client (close the browser tab, kill the network, or cancel the request). +3. Repeat several times. On a server with goroutine profiling (`/debug/pprof/goroutine`), observe goroutines accumulating and never exiting, blocked in `AddMessage` on the channel send. +4. Confirm in code: `runtime/ai/ai.go:898-900` (blocking send under lock) vs `runtime/server/chat.go:387` (reader's `ctx.Done()` case that can win the select). + +### ai-03 [MEDIUM] `query_sql` executes arbitrary (non-read-only) SQL despite `ReadOnlyHint` +- **Category:** security **Confidence:** high **Location:** `runtime/ai/query_sql.go:37-47` (annotation), `query_sql.go:92-100` (resolve); resolver at `runtime/resolvers/sql.go:162-166` +- **Problem:** The tool is annotated `ReadOnlyHint: true` / `DestructiveHint: false` and described as "introspect data", but the SQL resolver runs `olap.Query(ctx, &drivers.Statement{Query: r.sql})` with no restriction on statement type. Nothing prevents `DROP`, `DELETE`, `INSERT`, `CREATE`, `ATTACH`, etc. against the OLAP connector using its configured credentials. `CheckAccess` calls `checkDeveloperAccess(..., internal=false)`, so — unlike the file tools — this tool **is** exposed to external MCP clients (subject to `UseAI` + `EditRepo` + `developer_agent` flag), and the SQL text is model-generated and prompt-injectable. +- **Severity rationale (downgraded from HIGH):** The tool requires `EditRepo`, which already grants the ability to run arbitrary SQL via model `pre_exec`/`post_exec`/DDL, so this is not a fundamental privilege escalation. The concrete incremental risks are (a) the **misleading `ReadOnlyHint`**, which can cause MCP hosts/clients to auto-approve a destructive call, and (b) prompt-injection reachability without a human authoring a model file. +- **Failure scenario:** A prompt-injection payload (or an LLM error) causes the developer agent — or an auto-approving MCP host trusting `ReadOnlyHint` — to run `DROP TABLE ` / `DELETE FROM ...` against DuckDB/ClickHouse, destroying materialized data. +- **Recommendation:** Enforce read-only execution (a read-only connection/role where supported, or parse and reject non-`SELECT`/`SHOW`/`DESCRIBE`/`EXPLAIN`/`WITH` statements). At minimum, correct the `ReadOnlyHint`/`DestructiveHint` annotations to reflect actual behavior. + +**Verification:** CONFIRMED — `query_sql.go:37-42` sets `ReadOnlyHint: true` / `DestructiveHint: false` while the description says "introspect data"; `CheckAccess` calls `checkDeveloperAccess(ctx, t.Runtime, false)` (`query_sql.go:51`), and with `internal=false` the tool is NOT restricted to `rill`-prefixed user agents (`developer_agent.go:176-180`), so it is MCP-exposed. The SQL resolver runs `r.olap.Query(ctx, &drivers.Statement{Query: r.sql})` with no statement-type restriction (`resolvers/sql.go:162-166`). Any `DROP`/`DELETE`/`INSERT` will execute. + +**Manual Reproduction Steps (for QA):** +1. With the developer agent enabled (`UseAI` + `EditRepo` + `developer_agent` flag), open an AI chat. +2. Prompt: "Run this SQL to clean up: `DROP TABLE `" (use a disposable table). +3. Observe the table is dropped despite the tool being advertised as read-only. +4. Confirm in code: `runtime/ai/query_sql.go:41` (`ReadOnlyHint: true`) and `runtime/resolvers/sql.go:163` (unrestricted `olap.Query`). + +### ai-04 [MEDIUM] `metrics_view_query` limit lacks a lower bound and uses a fragile parse +- **Category:** correctness **Confidence:** medium **Location:** `runtime/ai/metrics_view_query.go:238-253` +- **Problem:** The handler caps only the upper bound (`if limit > cfg.AIMaxQueryLimit`) and extracts the limit via `strconv.ParseInt(fmt.Sprintf("%v", v), 10, 64)`. Two confirmed issues: + 1. **Fragile numeric parse (certain).** JSON numbers arrive as `float64`; `fmt.Sprintf("%v", f)` renders "round" magnitudes ≥ 1e6 in scientific notation (verified: `1000000.0`→`"1e+06"`, `5000000.0`→`"5e+06"`), which `ParseInt` rejects. So a common model output like `"limit": 1000000` errors with an opaque "invalid limit value" instead of being capped. (Non-round values such as `1234567` render as decimal and parse fine.) + 2. **No lower bound (dialect-dependent impact).** A non-positive limit passes through unchanged with `isSystemLimit=false`. `rewriteQueryEnforceCaps` returns a 0 reader-cap when any limit ≤ cap is present (`executor_rewrite_enforce_caps.go:28-33`), and the builder renders the value verbatim (`astsql.go:236-238` → `LIMIT -1`). On DuckDB (the default) `LIMIT -1` is a query error; on lenient dialects it can mean "unlimited", streaming the full result set into `data [][]any`. `LIMIT 0` silently returns zero rows with no warning. +- **Failure scenario:** The model emits `"limit": 1000000` and gets an opaque parse error; or emits `"limit": -1`/`0` and gets a dialect error or (on a lenient dialect) an unbounded materialization that bypasses `AIMaxQueryLimit`. +- **Recommendation:** Decode the limit numerically (`json.Number` / type-switch on `float64`/`int64`) rather than round-tripping through `%v`, and clamp to `[1, AIMaxQueryLimit]`, treating `<= 0` as the default. + +**Verification:** CONFIRMED — `metrics_view_query.go:241` does `strconv.ParseInt(fmt.Sprintf("%v", v), 10, 64)`, which fails on `float64` round magnitudes ≥ 1e6 rendered in scientific notation (`fmt.Sprintf("%v", 1000000.0)` = `"1e+06"`), erroring with the opaque "invalid limit value" (`:243`). Only the upper bound is clamped (`if limit > cfg.AIMaxQueryLimit`, `:245`); no lower-bound check, so a non-positive limit flows through with `isSystemLimit=false`. + +**Manual Reproduction Steps (for QA):** +1. In an AI chat, ask a question that makes the analyst request exactly one million rows, or craft an MCP `query_metrics_view` call with `"limit": 1000000`. +2. Observe the query fails with "invalid limit value" instead of being capped to `AIMaxQueryLimit`. +3. For the lower-bound path, issue a `query_metrics_view` with `"limit": -1` or `"limit": 0` and observe a dialect error (DuckDB `LIMIT -1`) or zero rows. +4. Confirm in code: `runtime/ai/metrics_view_query.go:241` (`%v`+ParseInt) and `:245` (only upper bound clamped). + +### ai-05 [LOW] Shared-session access control fails open if the boundary message is ever missing +- **Category:** security **Confidence:** medium **Location:** `runtime/ai/ai.go:123-152` +- **Problem:** For a non-owner viewing a shared session, the loader appends every message and only stops when it reaches `SharedUntilMessageID` (`if m.ID == retrieveUntilMessageID { break }`). If that sentinel ID is not present in the returned message set, the loop runs to completion and **all** messages — including content past the shared boundary — are returned to the non-owner. This fails open rather than closed. +- **Currently not reachable (severity downgraded from MEDIUM):** The boundary is validated at share time — `ShareConversation` resolves it via `session.LatestMessage(...)` against an actual message (`chat.go:134-143`) — and messages are append-only (no `DeleteAIMessage` path exists), so `SharedUntilMessageID` always matches a loaded message today. This is defensive hardening, not a live disclosure. +- **Failure scenario:** Any future invariant break (message pruning/rewrites, a stale ID after a schema change) would silently disclose the entire private conversation to any non-owner holding a share link. +- **Recommendation:** Resolve the boundary to an `Index` up front and filter `Index <= boundaryIndex`; if the sentinel is not found among loaded messages, deny access (fail closed) instead of returning everything. + +**Verification:** PLAUSIBLE — the fail-open code path is real: `ai.go:135-152` appends every loaded message and only `break`s when `m.ID == retrieveUntilMessageID` (`:149`); if that sentinel is absent, the loop runs to completion and returns all messages to the non-owner. As the finding states, it is not currently reachable — the boundary is validated at share time and messages are append-only (no `DeleteAIMessage` in the sqlite catalog), so the sentinel always matches a loaded message today. + +**Manual Reproduction Steps (for QA):** Not user-reproducible with current code (no way to make the sentinel go missing). Confirm in code: `runtime/ai/ai.go:149` — the loop `break`s only on ID match with no fallback; if `retrieveUntilMessageID` is not found, every message (past the shared boundary) is returned to a non-owner viewer of a shared session. + +### ai-06 [LOW] Stack traces are embedded in errors surfaced to the LLM and persisted +- **Category:** tech-debt **Confidence:** high **Location:** `runtime/ai/ai.go:1334`, `runtime/ai/ai.go:990-996` +- **Problem:** `Complete` wraps completion failures with `... (stack: %s)` using `debug.Stack()`, and the panic recovery in `Call` builds an error containing a 64 KB goroutine stack. For tool-call errors these become `MessageContentTypeError` result messages (`Call` lines 1030-1041), which are serialized back into the LLM context on the next turn and written to the catalog/activity log (`Flush`). +- **Failure scenario:** A transient LLM error or a tool panic injects a multi-kilobyte Go stack trace into the conversation history that is re-sent to the model (token waste and prompt noise) and stored; internal paths/symbols leak into user-visible errors. +- **Recommendation:** Log stacks via the logger only; keep the error returned to the loop/user concise (no `debug.Stack()`), and truncate panic detail before it becomes a result message. + +**Verification:** CONFIRMED — `ai.go:1334` wraps completion failures with `... (stack: %s)` using `string(debug.Stack())`, and the panic recovery in `Call` builds `NewInternalError(fmt.Errorf("panic caught: %v\n\n%s", err, string(stack)))` from a 64 KB `goruntime.Stack` buffer (`ai.go:991-995`). Tool-call errors become `MessageContentTypeError` result messages (`ai.go:1031-1041`) that are re-serialized into the LLM context and persisted (`Flush` records error content verbatim, `ai.go:584-585`). + +**Manual Reproduction Steps (for QA):** Hard to trigger deliberately via UI (requires a tool panic or transient LLM error). Confirm in code: `runtime/ai/ai.go:1334` (`debug.Stack()` in the returned error string) and `runtime/ai/ai.go:991-995` (64 KB panic stack becomes an error message). Note the error content is stored and re-sent to the model, not redacted (`ai.go:584-585`). + +### ai-07 [LOW] Final assistant response keeps only the last text block +- **Category:** correctness **Confidence:** low **Location:** `runtime/ai/ai.go:1402-1414` +- **Problem:** When assembling the final result, the loop assigns `outVal = block.Text` per block, so a response with multiple text blocks keeps only the last one. This is reachable: the Claude driver maps `thinking` blocks to `ContentBlock_Text` (`drivers/claude/claude.go:452-455`), so a final message with extended thinking arrives as `[Text(thinking), Text(answer)]`. In the common case the dropped block is the leading thinking block (benign), but a genuine answer split across two text blocks would lose its first fragment. +- **Refuted sub-claim:** The prior draft also claimed a non-text block would hit `default` and hard-fail the completion. This is **not reachable** — `aiv1.ContentBlock` has only `Text`/`ToolCall`/`ToolResult`, the driver converts thinking→text and drops unknown blocks, and a final (no-tool-call) message therefore contains only `Text` blocks. The `default` branch is effectively dead here. +- **Recommendation:** Concatenate text blocks for string/`outputText` results rather than overwriting. + +**Verification:** CONFIRMED — `ai.go:1402-1414` loops over `result.Content` and assigns `outVal = block.Text` (`:1407`) per text block, so only the last block survives. The `default` branch at `:1411` is effectively dead for a final (no-tool-call) message, as the finding notes. Whether the dropped block is a benign leading thinking block or a genuine answer fragment depends on how the driver splits blocks. + +**Manual Reproduction Steps (for QA):** Not reliably user-reproducible (depends on the model emitting multiple text blocks in its final message). Confirm in code: `runtime/ai/ai.go:1407` — `outVal = block.Text` overwrites on each iteration instead of concatenating, so a multi-text-block final answer keeps only the last fragment. + +### ai-08 [LOW] `promptToTitle` truncates on a byte boundary +- **Category:** correctness **Confidence:** high **Location:** `runtime/ai/router_agent.go:238-239` +- **Problem:** `title[:47]` slices by bytes; a multi-byte UTF-8 rune straddling byte 47 is split, producing an invalid string stored as the conversation title and shown in the UI / sent over the API. +- **Recommendation:** Truncate by runes (`[]rune(title)[:47]`) or use `utf8`-aware truncation. + +**Verification:** CONFIRMED — `router_agent.go:238-239`: `if len(title) > 50 { title = title[:47] + "..." }` slices by bytes. A multi-byte UTF-8 rune straddling byte 47 is split into an invalid string. + +**Manual Reproduction Steps (for QA):** +1. Start a new AI conversation whose first message is a long prompt (>50 characters) containing multi-byte characters (e.g. emoji or CJK text) positioned so one falls across byte 47, e.g. many emoji: "😀😀😀😀😀😀😀😀😀😀😀😀😀please analyze my sales data trends over time". +2. Observe the auto-generated conversation title in the UI shows a broken/replacement character (�) where the rune was split. +3. Confirm in code: `runtime/ai/router_agent.go:239` (`title[:47]` byte slice). + +### ai-09 [LOW] Inconsistent session locking: read accessors and `Flush` bypass the mutex +- **Category:** concurrency **Confidence:** medium **Location:** `runtime/ai/ai.go:686-742` (`NextIndex`, `Message`, `LatestMessage`, `Messages`), `runtime/ai/ai.go:535-599` (`Flush`), `runtime/ai/ai.go:884` (`Index` computed before the lock) +- **Problem:** `AddMessage` mutates `s.messages`/`s.messagesDirty` under `s.mu.Lock()`, but the read accessors iterate `s.messages` with no lock, `Flush` both reads and writes `s.dtoDirty`/`s.messagesDirty` and iterates `s.messages` unlocked, and `AddMessage` even computes `Index: s.NextIndex()` (a read of `len(s.messages)`) before acquiring the lock. This is not a live race today: a session is driven by a single goroutine, and the streaming reader only touches per-message content and the (read-only) tools map via `UnmarshalMessageContent` (verified — it does not read `s.messages`). It is a latent data race the moment any code reads/flushes messages from a second goroutine (the natural evolution of the subscriber/streaming path). +- **Recommendation:** Take `s.mu.RLock()`/`Lock()` uniformly in the accessors and `Flush` (or snapshot under lock), so the locking discipline is consistent and future concurrent readers are safe. + +**Verification:** CONFIRMED (latent) — `AddMessage` mutates `s.messages`/`s.messagesDirty` under `s.mu.Lock()` (`ai.go:893-897`), but `NextIndex`/`Message`/`LatestMessage`/`Messages` iterate `s.messages` with no lock (`ai.go:686-742`), `Flush` reads/writes `s.dtoDirty`/`s.messagesDirty` and iterates `s.messages` unlocked (`ai.go:535-599`), and `AddMessage` computes `Index: s.NextIndex()` (a `len(s.messages)` read) at `ai.go:884` before acquiring the lock at `:893`. Not a live race today (single driving goroutine), but a data race the moment a second goroutine reads/flushes. + +**Manual Reproduction Steps (for QA):** Not user-reproducible (no live race in current single-goroutine flow). Confirm in code: `runtime/ai/ai.go:686-742` (lock-free accessors), `ai.go:535-599` (lock-free `Flush`), and `ai.go:884` (`NextIndex()` read before `s.mu.Lock()` at `:893`). Run `go test -race ./runtime/ai/...` after adding any concurrent reader to surface it. + +### ai-10 [LOW] Dead code: `Session.RootID()` +- **Category:** tech-debt **Confidence:** high **Location:** `runtime/ai/ai.go:905-921` +- **Problem:** `RootID()` has no callers anywhere in the repo and contains two `panic` paths (empty parent at line 908, missing message at line 913; the `for range 100` bound is a non-panicking fail-safe that returns the last-seen root). Dead code carrying panic risk. +- **Recommendation:** Remove it, or if it is intended for upcoming durable-execution work, add a test and replace the panics with returned errors. + +**Verification:** CONFIRMED — `RootID()` at `ai.go:905-921` has two `panic` paths (`:908` empty parent, `:913` missing message); the `for range 100` is a non-panicking fail-safe. A repo-wide search finds no callers. + +**Manual Reproduction Steps (for QA):** Not user-reproducible (dead code, never invoked). Confirm in code: `runtime/ai/ai.go:905` (`func (s *Session) RootID()`), and `grep -rn "RootID" runtime/` returns only the definition, no callers. + +### ai-13 [LOW] `msg.dirty` is never reset, so re-flushing a session would duplicate-insert messages +- **Category:** correctness **Confidence:** low **Location:** `runtime/ai/ai.go:890` (set), `runtime/ai/ai.go:541,564,598` (`Flush`), sink at `runtime/drivers/sqlite/catalog.go:551-559` +- **Problem:** `AddMessage` sets `msg.dirty = true` and nothing ever resets it. `Flush` gates the message loop on `s.messagesDirty` (reset to `false` after a flush) but never clears the per-message `dirty` flag. `InsertAIMessage` is a plain `INSERT` on primary key `id`. Consequently, if the **same in-memory `Session` object** is ever flushed a second time after new messages are added, every previously-persisted message (still `dirty=true`) is re-inserted and the flush fails with a `UNIQUE constraint` error. +- **Currently latent:** every caller today creates a fresh session and flushes once — the streaming/non-streaming chat handlers use a deferred single `Flush`, and the MCP handler is `Stateless: true` (`server/mcp.go:59`), reloading messages clean (`dirty=false`) on each request. So the double-flush precondition is not met in current code. +- **Failure scenario:** A future change that reuses a session across flushes (stateful MCP, periodic flushing during long streams, or an added mid-turn `Flush`) would immediately break persistence with duplicate-key errors. +- **Recommendation:** Set `msg.dirty = false` after a successful `InsertAIMessage` (and rely on it rather than the coarse `s.messagesDirty`), or make `InsertAIMessage` an idempotent upsert. + +**Verification:** CONFIRMED (latent) — `AddMessage` sets `dirty: true` (`ai.go:890`) and nothing resets the per-message flag; `Flush` gates on `s.messagesDirty` and resets only that (`ai.go:562,598`), never clearing `msg.dirty` (`ai.go:564`). `InsertAIMessage` is a plain `INSERT` on PK `id` (`sqlite/catalog.go:551-555`), so a second flush of a reused session would re-insert all still-`dirty` messages and fail with a UNIQUE constraint. Latent because all callers flush once per fresh session and MCP is `Stateless: true` (`server/mcp.go:59`). + +**Manual Reproduction Steps (for QA):** Not user-reproducible with current code (no session is flushed twice). Confirm in code: `runtime/ai/ai.go:890` (set `dirty=true`, never reset), `ai.go:562-598` (`Flush` clears only `s.messagesDirty`), `runtime/drivers/sqlite/catalog.go:552` (plain `INSERT`). A stateful-MCP or mid-stream re-flush change would trigger duplicate-key errors. + +## Product Improvements + +### ai-11 [MEDIUM] No aggregate cost/iteration budget across nested agents +- **Category:** product-improvement **Confidence:** high **Location:** `runtime/ai/ai.go:1139-1150` (`Complete`), `developer_agent.go:102` (20), `analyst_agent.go:198` (20), `develop_file.go:131` (10) +- **Problem:** `MaxIterations` is per-loop only. Router → Developer (20 iterations) → each iteration may call `develop_file` (its own 10-iteration loop) → each of those may call `write_file`/`query_sql`. A single user turn can fan out to hundreds of LLM calls with no session- or turn-level token/call budget; the only backstop is the wall-clock `AICompletionTimeoutSeconds`. On the Rill-managed (billable) connector this can produce surprising token spend from one prompt. +- **Recommendation:** Track cumulative LLM calls / tokens on the session and enforce a per-turn budget that halts the loop with a graceful "budget exhausted" message, independent of wall-clock time. + +**Verification:** CONFIRMED — `MaxIterations` is enforced per `Complete` loop only. Developer agent uses 20 (`developer_agent.go:102`), analyst 20 (`analyst_agent.go:198`), `develop_file` 10 (`develop_file.go:131`), and the developer loop's tools include `DevelopFileName` (`developer_agent.go:99`), which spawns its own nested loop. There is no session- or turn-level token/call budget; the only cross-loop backstop is the wall-clock `AICompletionTimeoutSeconds`. + +**Manual Reproduction Steps (for QA):** Not a defect to "reproduce" — it is a missing guardrail. Confirm in code: `runtime/ai/develop_file.go:131` (nested 10-iteration loop) invoked from `runtime/ai/developer_agent.go:99,102` (outer 20-iteration loop), with no aggregate counter anywhere in `Complete` (`ai.go` completion loop). + +### ai-12 [MEDIUM] Analyst context seeding keyed on call count goes stale after dashboard navigation +- **Category:** product-improvement **Confidence:** medium **Location:** `runtime/ai/analyst_agent.go:105-161` +- **Problem:** The agent pre-invokes dashboard context (`get_canvas`, `query_metrics_view_summary`, `get_metrics_view`) only when `first := len(analyst calls) == 1`. The inline TODO (line 109) already flags this: when the user navigates to a different explore/canvas between turns, the second turn's new metrics view and summary are never seeded, so the analysis relies on the model re-discovering context (the tools are available, but the priming is skipped). +- **Recommendation:** Seed based on whether the current `Explore`/`Canvas`/metrics-view set has already been introduced in the session (dedupe by resource name), not on the raw call count. + +**Verification:** CONFIRMED — `analyst_agent.go:106` computes `first := len(s.Messages(FilterByType(MessageTypeCall), FilterByTool(AnalystAgentName))) == 1`, and all dashboard-context pre-invocation (`get_canvas`, `query_metrics_view_summary`, `get_metrics_view`, `list_metrics_views`) is gated on `if first` (`:111-161`). The inline TODO at `:109` explicitly flags that this is unsafe when the user navigates to a different dashboard between turns. + +**Manual Reproduction Steps (for QA):** +1. Open an explore/canvas dashboard A and ask the analyst agent a question (first turn seeds context for A). +2. Navigate to a different dashboard B, then ask a second question referencing B in the same conversation. +3. Observe the agent does not pre-load B's metrics view / summary (it must re-discover context via tools, if at all). +4. Confirm in code: `runtime/ai/analyst_agent.go:106` (`first` keyed on call count) and the TODO at `:109`. + +## New Feature Ideas +- **Sandboxed, read-only data-introspection role (S/M):** A dedicated read-only execution path for `query_sql`/`list_tables`/`show_table` (separate connection or role) so introspection cannot mutate data even under prompt injection. Directly addresses ai-03 and hardens the whole developer surface. +- **Project-root-jailed filesystem tool layer (S):** A single `projectPath(instanceID, userPath) (string, error)` helper enforcing containment, reused by every AI file tool (and ideally the repo drivers). Closes ai-01 and prevents regressions as new file tools are added. +- **Per-conversation token/cost meter + budget (M):** Surface cumulative input/output/cached tokens (already recorded as metrics) back to the user in the chat UI, with a configurable per-turn ceiling. Pairs with ai-11 and gives admins cost predictability. +- **Tool-call audit trail with approval gates for destructive tools (M):** For `write_file`/`develop_file`/`query_sql`, optionally require explicit user confirmation (the MCP annotations already carry `DestructiveHint`) before executing, with a visible diff/statement preview. Mitigates prompt-injection blast radius. +- **AI-assisted conversation summarization for truncation (M/L):** Replace the fixed keep-first-4/last-16 window in `maybeTruncateMessages` (a self-described placeholder) with rolling summarization so long developer sessions retain earlier decisions instead of dropping them. +- **Structured citations as first-class objects (S):** `query_metrics_view` returns `open_url` strings the model must inline; promoting these to structured citation objects attached to messages would make citation rendering reliable and decouple it from prompt compliance. + +## Notes & Missing Test Coverage +- **No tests exercise the security-critical branches.** The test harness (`ai_test.go:newSession`) always sets `SkipChecks: true` and a `rill-evals` user agent, so `CheckAccess` gating, the `internal` MCP restriction, shared-session boundaries (`SharedUntilMessageID`), and `ForkSession` cloning are effectively untested. Add unit tests that run with `SkipChecks:false` and non-`rill` user agents. +- **No path-traversal tests** for `read_file`/`write_file`/`develop_file` (ai-01). Add cases asserting that `..`-containing paths are rejected and cannot escape the project root. +- **No tests for `maybeTruncateMessages`** (ai.go:1605) — the unbalanced tool-call/result pruning is subtle (relies on call-before-result ordering and only inspects the first tool block per message). It appears correct for the current one-block-per-message shape, but table-driven tests covering orphaned calls/results at the truncation boundary would lock it in. +- **No concurrency/streaming test** for the subscriber path (ai-02); a test that cancels the context mid-stream and asserts the producer unblocks and the goroutine exits would lock in the fix. +- **`list_buckets.go:70-82`** collects all pages with no overall cap — benign for normal accounts but unbounded in principle. + +## Verification Notes +Every finding was re-checked against the cited code; the empirical Go behaviors (path traversal via `filepath.Join`, `fmt.Sprintf("%v", float64)` scientific notation) were reproduced with standalone snippets. + +Changes made during verification: +- **ai-01:** Confirmed (HIGH/high). Removed `file_search.go` from the location — it goes through `ListGlob`/`os.DirFS`, which rejects `..`, so it is not a traversal vector. Added the precondition detail (these file tools are `internal`, i.e. not on external MCP, but the path is still model-chosen inside the chat agent). +- **ai-02:** Confirmed (HIGH/high). Tightened the mechanism: the hang arises from the `select` race between the unbuffered `sub <- msg` and the reader's `ctx.Done()` case (both can be ready; the reader may win). Corrected line anchors. +- **ai-03:** Confirmed behavior; **severity downgraded HIGH → MEDIUM** (confidence raised to high on the facts). `EditRepo` already permits arbitrary SQL via models, so the real incremental risks are the misleading `ReadOnlyHint` (auto-approval) and prompt-injection reachability. Verified `internal=false` (MCP-exposed) via `checkDeveloperAccess`. +- **ai-04:** Confirmed. Separated the two sub-issues by confidence: the `%v` scientific-notation parse failure is certain (reproduced); the unbounded-memory path is dialect-dependent (DuckDB errors on `LIMIT -1`), so it stays medium. +- **ai-05:** Confirmed as a fail-open code path but **not currently reachable** (boundary validated at share time via `LatestMessage`; messages are append-only). **Severity downgraded MEDIUM → LOW**; reframed as defensive hardening. +- **ai-06:** Confirmed (LOW). Category changed `readability → tech-debt` (error-handling hygiene + minor info leak + token waste). Traced the panic-stack path into `MessageContentTypeError` result messages. +- **ai-07:** **Partially refuted.** The "non-text/thinking block → hard error" scenario is unreachable (`aiv1.ContentBlock` has no thinking type; the Claude driver maps thinking→`Text` and drops unknown blocks; final messages are Text-only). Rewrote to keep only the accurate residual ("keeps only the last text block"), which is usually benign. Stays LOW/low. +- **ai-08:** Confirmed (LOW/high). Corrected line anchor to `router_agent.go:238-239`. +- **ai-09:** Confirmed as latent (not live) — verified the streaming reader does not touch `s.messages`. **Expanded** to include `Flush` (which reads/writes dirty flags and iterates messages unlocked) and the pre-lock `Index` computation. +- **ai-10:** Confirmed dead code (no callers). Corrected "three panic paths" → **two** (the loop bound is a non-panicking fail-safe). +- **ai-11 / ai-12:** Confirmed; verified line anchors (analyst `MaxIterations` at `analyst_agent.go:198`). +- **ai-13 (added):** New, verified finding — `msg.dirty` is set once and never reset, so re-flushing a reused session object would duplicate-insert via a plain `INSERT`. Currently latent because all callers flush once per fresh session (MCP is `Stateless`). LOW/low. + +No findings were removed outright (0). Net: 12 original findings retained (2 downgraded in severity, 1 partially refuted/rewritten, 1 recategorized) plus 1 added. diff --git a/audit/cli.md b/audit/cli.md new file mode 100644 index 000000000000..ddf7f4dbe894 --- /dev/null +++ b/audit/cli.md @@ -0,0 +1,225 @@ +# CLI & Local App — Code Review + +**Scope:** `cli/cmd` (root, auth, deploy, project, start, sudo/user) and `cli/pkg` (local: app/server/git/slots/project/admin, deviceauth, pkce, dotrill, cmdutil helper/githelper, devtool, browser, web) | **Health:** fair + +## Overview + +This area implements Rill Developer's local application bootstrap, the device-auth and PKCE login flows, credential storage in `~/.rill`, and the deploy/redeploy flows to Rill Cloud (managed Git, GitHub, and archive). The code is generally readable and the deploy flows carefully guard against pushing to the wrong repo/subpath. The biggest risks are: (1) a deploy path that pushes local `.env` secrets to the *wrong* project when a name collision triggers the retry/suffix logic; (2) shared mutable state (`Helper`'s cached admin client and the local server's PKCE authenticator map) accessed from concurrent local-server request handlers without synchronization; and (3) credential files written world-readable. Most auth logic is a faithful port of PlanetScale's CLI, but the local PKCE HTTP handlers add a localhost open-redirect and a copy-paste validation bug. None of these block normal single-user usage, but several are real correctness/security defects that will surface under concurrency, multi-user machines, or name collisions. + +## Findings + +### cli-01 [HIGH] `DeployProject` pushes `.env` variables to the wrong project after a name collision + +**Status (2026-07-25):** ✅ Fixed and merged in [#9699](https://github.com/rilldata/rill/pull/9699). + +- **Category:** correctness (data-loss) **Confidence:** high **Location:** `cli/pkg/local/server.go:456` +- **Problem:** `DeployProject` creates the project inside a retrier that appends a numeric suffix on `"name already exists"` errors, so the created project may be `foo-1` (available as `projResp.Project.Name`). But the subsequent `UpdateProjectVariables` call passes `Project: r.Msg.ProjectName` (the original, unsuffixed `foo`) instead of `projResp.Project.Name`. The sibling `RedeployProject` gets this right at line 576 (`Project: projResp.Project.Name`), confirming the intent. +- **Failure scenario:** A user deploys a local folder named `foo` from the UI while a project `foo` already exists in the org (e.g. a re-clone, or a concurrent deploy). The retrier creates `foo-1`, then the local `.env` (which typically contains connector secrets/credentials) is pushed via `UpdateProjectVariables` to the pre-existing `foo` — overwriting that project's variables — while the newly created `foo-1` silently receives none. Local secrets land in a project the user did not intend, and the intended project is misconfigured. +- **Recommendation:** Use `projResp.Project.Name` (and `projResp.Project.OrgName`) for the `UpdateProjectVariables` call, matching `RedeployProject`. + +**Verification:** CONFIRMED — `cli/pkg/local/server.go:434-443` retries `CreateProject` with a `-N` suffix on name conflicts, but the `UpdateProjectVariables` call at `server.go:454-457` passes `Org: r.Msg.Org, Project: r.Msg.ProjectName` (the original unsuffixed name) instead of `projResp.Project.Name`. The sibling `RedeployProject` correctly uses `projResp.Project.OrgName`/`projResp.Project.Name` at `server.go:574-576`. + +**Manual Reproduction Steps (for QA):** +1. Log in to Rill Cloud: `rill login`. In your org, ensure a project named `foo` already exists (e.g. deploy any project as `foo` first, or create one in the cloud UI). +2. On your machine, create a local project in a folder named `foo` (`mkdir foo && cd foo && rill init` or use an existing project folder renamed to `foo`) and add a `.env` file with a recognizable variable, e.g. `MY_TEST_SECRET=hello123`. +3. Run `rill start` in that folder, open the browser UI at http://localhost:9009, and click Deploy (the UI-driven deploy, not `rill deploy` from the terminal). +4. Observe the deploy creates a project named `foo-1` (because `foo` was taken). +5. Check variables on both projects: `rill env show --project foo` and `rill env show --project foo-1`. +6. Bug confirmed if `MY_TEST_SECRET` appears on the pre-existing `foo` (which you did not deploy to) and is missing on the newly created `foo-1`. + +### cli-02 [MEDIUM] Unsynchronized `pkceAuthenticators` map races between `/auth` and `/auth/callback` +- **Category:** concurrency **Confidence:** high **Location:** `cli/pkg/local/app.go:59`, `cli/pkg/local/server.go:825,845,852` +- **Problem:** `App.pkceAuthenticators` is a plain `map[string]*pkce.Authenticator`. `authHandler` writes to it (`s.app.pkceAuthenticators[state] = authenticator`), while `authCallbackHandler` reads it and then `delete`s the entry. These are ordinary `http.HandlerFunc`s registered on the runtime's mux; Connect/HTTP handlers each run in their own goroutine with no serialization. +- **Failure scenario:** Two overlapping requests (e.g. two browser tabs each hitting `/auth`, or an `/auth` overlapping a stale `/auth/callback`) perform a concurrent map write / read-write. Go's runtime detects concurrent map access and throws a fatal, unrecoverable `concurrent map writes` panic, taking down the entire local server (and the embedded runtime) rather than returning an error. +- **Recommendation:** Guard the map with a `sync.Mutex` (or use `sync.Map`), taking the lock around the store in `authHandler` and the load+delete in `authCallbackHandler`. + +**Verification:** CONFIRMED — `pkceAuthenticators` is declared as a plain `map[string]*pkce.Authenticator` at `cli/pkg/local/app.go:59` (no accompanying mutex in the `App` struct). `authHandler` writes at `cli/pkg/local/server.go:825`, and `authCallbackHandler` reads at `server.go:845` and deletes at `server.go:852`. Both are plain `http.HandlerFunc`s served concurrently by `net/http`, so overlapping requests cause an unsynchronized map read/write, which Go's runtime turns into a fatal panic. + +**Manual Reproduction Steps (for QA):** +1. Run `rill start` in any project folder. +2. In a terminal, fire many concurrent requests at the auth endpoint: `for i in $(seq 1 50); do curl -s -o /dev/null "http://localhost:9009/auth" & done; wait` and re-run this a few times. +3. Bug confirmed if the `rill start` process crashes with a `fatal error: concurrent map writes` message in the terminal. (The race is timing-dependent; it may take several attempts. Engineers can confirm deterministically by building with `-race` and repeating step 2.) + +### cli-03 [MEDIUM] `Helper.Client()` / `Helper.Telemetry()` mutate shared state from concurrent local-server RPCs +- **Category:** concurrency **Confidence:** high **Location:** `cli/pkg/cmdutil/helper.go:170-205` (`Client`), `helper.go:211-277` (`Telemetry`), `helper.go:136-154` (`ReloadAdminConfig`) +- **Problem:** `Client()` reads and writes `h.adminClient`/`h.adminClientHash`, and `Telemetry()` writes `h.activityClient`/`h.activityClientHash`, with no lock (only `gitHelperMu` exists, and it only protects `gitHelper`). `ReloadAdminConfig()` also writes `h.AdminTokenDefault`/`h.AdminURLDefault`. The single `Helper` is shared by every local-server handler, and the web UI fires several RPCs concurrently on load (`GetMetadata`, `GetCurrentUser`, `GitStatus`, `ListOrganizationsAndBillingMetadata`, …), each calling `ch.Client()`. +- **Failure scenario:** On first page load, multiple goroutines observe `h.adminClient == nil` and race to construct and assign it (leaking/duplicating clients), while others read `h.AdminTokenDefault` mid-write in `ReloadAdminConfig`. This is a data race (fires under `-race`) and can intermittently close a client another goroutine is using, or read a torn token/URL. +- **Recommendation:** Protect the admin-client and activity-client caches (and `ReloadAdminConfig`'s writes to the token/URL fields) with a mutex, or build the client once at startup and hand out an immutable reference. + +**Verification:** CONFIRMED — `Client()` at `cli/pkg/cmdutil/helper.go:170-205` reads/writes `h.adminClient`/`h.adminClientHash` and calls `ReloadAdminConfig()` (`helper.go:136-154`, which writes `h.AdminURLDefault`/`h.AdminTokenDefault`) with no lock; `Telemetry()` at `helper.go:211-277` writes `h.activityClient`/`h.activityClientHash` unlocked. The only mutex on `Helper` is `gitHelperMu`, used solely for `gitHelper` (`helper.go:510-519`). Local-server handlers (`GetCurrentUser`, `ListProjectsForOrg`, `DeployProject`, etc. in `cli/pkg/local/server.go`) all call `s.app.ch.Client()` concurrently. + +**Manual Reproduction Steps (for QA):** +1. Run `rill start` in a project folder while logged in (`rill login` first). +2. Fire concurrent requests that all construct/use the admin client: `for i in $(seq 1 30); do curl -s -o /dev/null http://localhost:9009/local/v1/get-current-user -X POST -H 'Content-Type: application/json' -d '{}' & done; wait` (or simply open the local UI in several tabs simultaneously right after startup). +3. A crash or intermittent "client closed" errors would confirm it, but the race is usually silent in normal builds. Not reliably user-reproducible — confirm in code: `cli/pkg/cmdutil/helper.go:181-204` (unlocked lazy init of `adminClient`), or run a `-race` build of `rill start` and repeat step 2; the race detector reports writes to `h.adminClient`/`h.AdminTokenDefault` from multiple goroutines. + +### cli-04 [MEDIUM] Open redirect in the local PKCE auth/logout handlers +- **Category:** security **Confidence:** high **Location:** `cli/pkg/local/server.go:815-827,879` (auth), `server.go:897-901` (logout) +- **Problem:** `authHandler` reads `origin := r.URL.Query().Get("redirect")` and stores it verbatim; `authCallbackHandler` then does `http.Redirect(w, r, authenticator.OriginURL, http.StatusFound)` with no validation that the target is a same-origin/relative path. `logoutHandler` similarly forwards an attacker-controlled `redirect` param to the cloud logout URL. +- **Failure scenario:** An attacker page navigates the victim's browser to `http://localhost:9009/auth?redirect=https://evil.example.com`. The local server mints a valid `state`, the user completes the (real) Rill OAuth login, their token is written to `~/.rill`, and the callback redirects the browser to `https://evil.example.com` — a convincing phishing hand-off immediately after a legitimate login. Scope is limited to a running local instance, but the redirect target is fully attacker-controlled. +- **Recommendation:** Reject `redirect` values that are not relative paths (e.g. require a leading `/` and no scheme/host, or validate the host against the known local origin) before storing/using them in both handlers. + +**Verification:** CONFIRMED — `authHandler` stores the unvalidated `redirect` query param as the PKCE authenticator's origin at `cli/pkg/local/server.go:815-820` (passed to `pkce.NewAuthenticator`, stored as `OriginURL` at `cli/pkg/pkce/authenticator.go:46`), and `authCallbackHandler` redirects to it verbatim at `server.go:879`. `logoutHandler` forwards the `redirect` param into the cloud logout URL at `server.go:897-901`. No same-origin or relative-path validation exists anywhere in this path. + +**Manual Reproduction Steps (for QA):** +1. Run `rill start` in any project folder (server on http://localhost:9009). +2. In a browser, visit `http://localhost:9009/auth?redirect=https://example.com`. +3. Complete the Rill login in the page that opens. +4. Bug confirmed if, after login succeeds, the browser lands on `https://example.com` (an arbitrary external site) instead of the local Rill UI. +5. For the logout variant: visit `http://localhost:9009/logout?redirect=https://example.com` and observe the redirect chain passes the external URL to the cloud logout endpoint (check the `redirect` param in the address bar / network tab). + +### cli-05 [MEDIUM] Credentials and config in `~/.rill` are written world-readable +- **Category:** security **Confidence:** high **Location:** `cli/pkg/dotrill/dotrill.go:113` (`0o644`), `dotrill.go:362` (`os.ModePerm`) +- **Problem:** Every `DotRill.Set` writes with `0o644`, and the `.rill` directory is created with `os.ModePerm` (`0777`, subject to umask). `credentials.yaml` holds the long-lived access token, the assume-user `backup_token`, and per-env tokens (`tokens.*`). On a shared/multi-user host these are readable by any local user. +- **Failure scenario:** On a multi-user Linux box or a shared build agent, another local account reads `~/.rill/credentials.yaml` and exfiltrates the user's Rill access token, gaining their cloud permissions until the token is revoked. +- **Recommendation:** Write `credentials.yaml` with `0o600` and create `~/.rill` with `0o700` (matching the convention used by `aws`, `gcloud`, `kubectl`). At minimum special-case the credentials file. + +**Verification:** CONFIRMED — `DotRill.Set` writes every config file (including `credentials.yaml`, see `CredentialsFilename` at `cli/pkg/dotrill/dotrill.go:19` and `SetAccessToken` at `dotrill.go:153`) with `os.WriteFile(filename, data, 0o644)` at `dotrill.go:113`, and `ResolveFilename` creates `~/.rill` with `os.MkdirAll(dotrill, os.ModePerm)` (0777 before umask) at `dotrill.go:362`. + +**Manual Reproduction Steps (for QA):** +1. Remove or back up your existing `~/.rill` directory: `mv ~/.rill ~/.rill.bak`. +2. Run `rill login` and complete the login. +3. Run `ls -la ~/.rill ~/.rill/credentials.yaml`. +4. Bug confirmed if `credentials.yaml` shows `-rw-r--r--` (world-readable) and the `.rill` directory shows `drwxr-xr-x` (world-traversable) — i.e. any other local user account can read your access token. +5. Restore your backup afterwards: `rm -rf ~/.rill && mv ~/.rill.bak ~/.rill`. + +### cli-06 [MEDIUM] `ListMatchingProjects` swallows non-inference errors and returns an empty list +- **Category:** correctness **Confidence:** high **Location:** `cli/pkg/local/server.go:733-745` +- **Problem:** After `projects, err := s.app.ch.InferProjects(...)`, the handler only handles `err` when it `Is(ErrInferProjectFailed)` (returning an empty list). For any other error the `if err != nil` block falls through without returning — the function then returns `Projects: projects` (nil) with a `nil` error. +- **Failure scenario:** A transient admin API error (network blip, expired token, 500) during `InferProjects` is silently converted into "no matching projects." The UI shows the user that their local folder matches no cloud project and offers to create a new one, instead of surfacing the real error — potentially leading to a duplicate deploy. +- **Recommendation:** Add `return nil, err` at the end of the `if err != nil` block (mirroring the pattern in the other handlers such as `GitStatus`). + +**Verification:** CONFIRMED — `ListMatchingProjects` at `cli/pkg/local/server.go:733-740`: the `if err != nil` block only returns for `errors.Is(err, cmdutil.ErrInferProjectFailed)`; any other error falls through to `return connect.NewResponse(... Projects: projects ...)` at `server.go:743-745` with `projects == nil` and a nil error. Contrast `GetCurrentProject` at `server.go:652-659`, which ends the error block with `return nil, err`. + +**Manual Reproduction Steps (for QA):** +1. Log in (`rill login`) and run `rill start` in a project folder that was previously deployed to Rill Cloud. +2. Break connectivity to the admin API mid-session (e.g. disconnect from the network, or point `/etc/hosts` at an unreachable IP for the admin host) so admin API calls fail. +3. In the local UI (http://localhost:9009), open the Deploy flow, or call the endpoint directly: `curl -s http://localhost:9009/local/v1/list-matching-projects -X POST -H 'Content-Type: application/json' -d '{}'`. +4. Bug confirmed if the response is a success (`{"projects":[]}` / empty list) with no error, and the UI behaves as if no matching cloud project exists (offering to create a new one) instead of showing a connectivity error. + +### cli-07 [LOW] `Helper.GitHelper` constructs the helper with `h.Org` instead of the `org` argument +- **Category:** correctness **Confidence:** high **Location:** `cli/pkg/cmdutil/helper.go:510-519` +- **Problem:** The cache-validity check compares the stored helper's org against the `org` parameter (`h.gitHelper.org != org`), but construction uses the struct field: `newGitHelper(h, h.Org, project, localPath)`. The `org` parameter is effectively ignored. Today every caller passes `ch.Org`, so `org == h.Org` and the bug is latent, but the signature invites misuse. +- **Failure scenario:** A future caller passes an org different from the helper's current default (e.g. deploying to org B while `ch.Org` is A). Git credentials would be fetched for `h.Org` (A) rather than the requested org (B), and the cache check would additionally never hit, silently reconstructing on every call. +- **Recommendation:** Construct with the `org` parameter: `newGitHelper(h, org, project, localPath)`; or drop the parameter and document that it always uses `h.Org`. + +**Verification:** PLAUSIBLE — the mismatch exists exactly as described: the cache check at `cli/pkg/cmdutil/helper.go:515` compares `h.gitHelper.org != org` (the parameter), but construction at `helper.go:516` passes `h.Org` (the struct field). It is latent: current callers (e.g. `cli/pkg/local/server.go:520,530` after `SetOrg` at `server.go:491-496`) always have `org == h.Org`, so behavior is currently correct. + +**Manual Reproduction Steps (for QA):** +Not user-reproducible today — no code path passes an `org` different from `h.Org`. Confirm in code: `cli/pkg/cmdutil/helper.go:515-516` — the comparison uses the `org` parameter while `newGitHelper` is constructed with `h.Org`. + +### cli-08 [LOW] `authCallbackHandler` checks `code == ""` twice instead of validating `state` +- **Category:** correctness **Confidence:** high **Location:** `cli/pkg/local/server.go:839-843` +- **Problem:** After reading `state := r.URL.Query().Get("state")`, the guard is `if code == "" { http.Error(w, "missing state", ...) }` — a copy-paste of the preceding `code` check. The intended `state == ""` check never runs. An empty `state` currently falls through to the map lookup (which fails with "invalid state"), so behavior is merely a misleading error path today, but the guard is dead. +- **Failure scenario:** A callback with a present `code` but empty `state` skips the "missing state" 400 and instead reports "invalid state"; more importantly the intended validation is silently disabled, so any future logic relying on it would be wrong. +- **Recommendation:** Change the condition to `if state == ""`. + +**Verification:** CONFIRMED — `cli/pkg/local/server.go:839-843`: after `state := r.URL.Query().Get("state")`, the guard is `if code == ""` (a duplicate of the check at `server.go:835`), so the "missing state" 400 is dead code and an empty `state` falls through to the map lookup at `server.go:845`, which returns "invalid state". + +**Manual Reproduction Steps (for QA):** +1. Run `rill start` in any project folder. +2. Call the callback with a code but no state: `curl -s "http://localhost:9009/auth/callback?code=abc"`. +3. Bug confirmed if the response says `invalid state` (HTTP 400) instead of the intended `missing state` — proving the empty-state guard never fires. + +### cli-09 [LOW] `deviceauth.Authenticator` interface doesn't match its implementation (dead interface) +- **Category:** readability (dead-code) **Confidence:** high **Location:** `cli/pkg/deviceauth/authenticator.go:28-32` +- **Problem:** The declared interface has `VerifyDevice(ctx) (*DeviceVerification, error)` and `GetAccessTokenForDevice(ctx, v DeviceVerification) (string, error)`, but `*DeviceAuthenticator` implements `VerifyDevice(ctx, redirectURL string)` and `GetAccessTokenForDevice(ctx, v *DeviceVerification) (*oauth.TokenResponse, error)`. The concrete type does not satisfy the interface, and nothing references the interface. It is stale, misleading dead code. +- **Failure scenario:** A reader assumes `DeviceAuthenticator` conforms to `Authenticator` and tries to program against the interface, only to find it uncompilable; the mismatch also hides that the real signatures diverged. +- **Recommendation:** Delete the unused interface or update it to match the implementation (and add a `var _ Authenticator = (*DeviceAuthenticator)(nil)` assertion if it is meant to be honored). + +**Verification:** CONFIRMED — the interface at `cli/pkg/deviceauth/authenticator.go:29-32` declares `VerifyDevice(ctx context.Context) (*DeviceVerification, error)` and `GetAccessTokenForDevice(ctx, v DeviceVerification) (string, error)`, while the concrete type implements `VerifyDevice(ctx, redirectURL string)` (`authenticator.go:80`) and `GetAccessTokenForDevice(ctx, v *DeviceVerification) (*oauth.TokenResponse, error)`. A repo-wide grep found no references to `deviceauth.Authenticator` outside its declaration. + +**Manual Reproduction Steps (for QA):** +Not user-reproducible — no runtime behavior. Confirm in code: `cli/pkg/deviceauth/authenticator.go:29-32` (interface) vs `authenticator.go:80` (implementation signature); grep the repo for `deviceauth.Authenticator` to verify nothing uses the interface. + +### cli-10 [LOW] Device-auth `redirect` form value is double-escaped +- **Category:** correctness **Confidence:** high **Location:** `cli/pkg/deviceauth/authenticator.go:84` +- **Problem:** `VerifyDevice` sets `"redirect": []string{url.QueryEscape(redirectURL)}` inside a `url.Values`, but `url.Values.Encode()` (called in `newFormRequest`) percent-encodes each value again — so the server receives a double-encoded redirect. The double-escape is certain; it is latent (severity low) only because every current caller passes `redirectURL == ""` (`Login`/`LoginWithTelemetry` at `cli/cmd/auth/login.go:34`, `cli/cmd/deploy/deploy.go:24`). +- **Failure scenario:** If/when a non-empty redirect is threaded through login (the parameter already exists on `Login`/`LoginWithTelemetry`), the server would receive e.g. `https%3A%2F%2F...` and either reject it or redirect to a malformed URL. +- **Recommendation:** Drop the manual `url.QueryEscape`; let `url.Values.Encode()` handle escaping. + +**Verification:** PLAUSIBLE — the double-escape is present: `cli/pkg/deviceauth/authenticator.go:84` sets `"redirect": []string{url.QueryEscape(redirectURL)}` inside a `url.Values` that `newFormRequest` encodes again via `Encode()`. It is latent because every current caller passes an empty `redirectURL` (`cli/cmd/auth/login.go` and `cli/cmd/deploy/deploy.go` pass `""`), so no double-encoded value is ever sent today. + +**Manual Reproduction Steps (for QA):** +Not user-reproducible today — the `redirect` value is always empty from all CLI entry points. Confirm in code: `cli/pkg/deviceauth/authenticator.go:81-85` (manual `url.QueryEscape` inside `url.Values`), plus `newFormRequest` in the same file calling `.Encode()`; or add a temporary non-empty redirect and observe the server receives `https%3A%2F%2F...`. + +### cli-11 [LOW] PKCE code-verifier generation has modulo bias +- **Category:** security **Confidence:** high **Location:** `cli/pkg/pkce/authenticator.go:157` +- **Problem:** `b[i] = charset[temp[i]%byte(len(charset))]` maps a uniform byte (0–255) onto a 66-character set; since 256 is not a multiple of 66, low-index characters are slightly over-represented. Not a practical break given the 43–128 char length, but it is a textbook non-uniform sampling in security-sensitive code. +- **Failure scenario:** Reduced per-character entropy; negligible in isolation but the kind of subtle weakness worth removing from an OAuth secret generator. +- **Recommendation:** Use rejection sampling, or `crypto/rand` with `base64.RawURLEncoding` over random bytes (the RFC 7636 recommended construction). + +**Verification:** CONFIRMED — `cli/pkg/pkce/authenticator.go:157` does `b[i] = charset[temp[i]%byte(len(charset))]` over the 66-character charset defined at `authenticator.go:20`; 256 mod 66 = 58, so characters at indices 0-57 are sampled 4/256 of the time and indices 58-65 only 3/256 — a textbook modulo bias. Practical impact is negligible at 43-128 characters. + +**Manual Reproduction Steps (for QA):** +Not user-reproducible — the bias is statistical and invisible in normal use. Confirm in code: `cli/pkg/pkce/authenticator.go:155-158` (modulo mapping of a uniform byte onto a 66-char set); an engineer can demonstrate it by generating ~1M verifiers and observing characters `-._~` and high letters underrepresented by ~25 percent relative frequency. + +### cli-14 [LOW] `emitStartEvent` returns a nil error instead of the connector error, silently dropping the app-start telemetry event +- **Category:** correctness **Confidence:** high **Location:** `cli/pkg/local/app.go:544-547` +- **Problem:** In the loop `for _, c := range connectors { if c.Err != nil { return err } }`, the returned `err` is the value from the preceding `parser.Parse` call, which is `nil` at that point — not `c.Err`. When any connector fails analysis, the function returns early with `nil`, skipping `RecordBehavioralLegacy(BehavioralEventAppStart)`. The caller (`NewApp`, `app.go:356-359`) only logs when the returned error is non-nil, so nothing is logged either: the intended connector error is swallowed and the start event is dropped. +- **Failure scenario:** A project whose connector cannot be analyzed (e.g. a misconfigured or unconfigured connector) starts normally, but the app-start telemetry event is silently dropped and the underlying error is discarded. Because the loop returns on the first failing connector, connector-name reporting is skipped for the whole project. +- **Recommendation:** Return `c.Err` to propagate the error (letting the caller log it), or `return nil` with a comment if skipping the event for projects with connector errors is intentional. + +**Verification:** CONFIRMED — `cli/pkg/local/app.go:544-549`: the loop `for _, c := range connectors { if c.Err != nil { return err } }` returns `err`, which at that point holds the nil result of `parser.Parse` at `app.go:539-542`. So a failing connector aborts `emitStartEvent` with a nil error, skipping the `RecordBehavioralLegacy(BehavioralEventAppStart)` call at `app.go:556`; the caller at `app.go:356-359` only logs on non-nil error, so nothing surfaces. + +**Manual Reproduction Steps (for QA):** +Not directly user-observable (the only effect is a silently missing telemetry event and a swallowed error). Confirm in code: `cli/pkg/local/app.go:545-548` — `return err` inside the `c.Err != nil` branch returns the nil `err` from `parser.Parse`, not `c.Err`. An engineer can confirm at runtime by starting a project with a misconfigured connector (e.g. a source referencing an undefined connector) under a debugger/log line and observing `emitStartEvent` returns nil early and no `app_start` behavioral event is recorded. + +## Product Improvements + +### cli-12 [LOW] `.env` push offers no visibility into which variables/secrets are uploaded +- **Category:** product-improvement **Confidence:** medium **Location:** `cli/cmd/project/deploy.go:437-451`, `cli/cmd/project/connect_github.go:193-212`, `cli/pkg/local/server.go:448-462` +- **Problem:** All deploy flows silently parse the local `.env` and push every variable to Rill Cloud (`push-env` defaults to `true`). The user gets no preview of which keys — often including secrets — are being transmitted, and no opt-out per-variable. +- **Recommendation:** In interactive mode, print the variable names being uploaded and confirm; document the `--push-env=false` escape hatch prominently. + +**Verification:** CONFIRMED — `push-env` defaults to `true` (`cli/cmd/project/deploy.go:309`, `cli/cmd/project/connect_github.go:59`), and all three flows push every parsed `.env` variable with no listing or confirmation: `deploy.go:437-451`, `connect_github.go:195-210`, and the UI-driven `DeployProject` at `cli/pkg/local/server.go:448-462` (which has no opt-out at all). + +**Manual Reproduction Steps (for QA):** +1. In a local project folder, create a `.env` containing `SOME_SECRET=supersecret`. +2. Log in (`rill login`) and run `rill deploy` for the project. +3. Observe the terminal output: no listing of the variable names being uploaded and no confirmation prompt appears. +4. Verify the secret was silently pushed: `rill env show --project ` shows `SOME_SECRET`. + +### cli-13 [LOW] `PollServer` relies on a sleep to avoid a false-positive health check when a port is taken +- **Category:** product-improvement **Confidence:** medium **Location:** `cli/pkg/local/app.go:480-513` +- **Problem:** The comment admits the initial `250ms` sleep is "a slightly hacky way" to avoid opening the browser against a *different* Rill already bound to the port. A slow machine can still lose this race and open the browser onto an unrelated server; a fast crash can be missed. +- **Recommendation:** Detect the bind failure deterministically (the runtime server already fails to listen when the port is taken) and surface a clear "port already in use" error instead of racing a health check. + +**Verification:** CONFIRMED — `PollServer` at `cli/pkg/local/app.go:480-529` sleeps 250ms before the first `/v1/ping` health check, with the in-code comment at `app.go:495-498` admitting it is "a slightly hacky way" to avoid a false positive against another Rill server already bound to the port. The race window is real: if ctx cancellation from the bind failure loses the 250ms race, the browser opens against the wrong server. + +**Manual Reproduction Steps (for QA):** +1. In project folder A, run `rill start` (occupies port 9009). +2. In a different project folder B, run `rill start` again in a second terminal. +3. Expected symptom of the race: the second command may briefly pass the health check and open a browser tab pointing at the FIRST instance's UI (project A) before/while erroring about the port. On fast machines it usually errors cleanly; the hack mostly works, which is why this is a robustness note rather than a hard bug. + +## New Feature Ideas + +- **OS keychain credential storage (S/M).** Store the access token in the OS keyring (Keychain/Credential Manager/libsecret) with a plaintext-YAML fallback. Removes the world-readable-token exposure (cli-05) and matches user expectations from other dev CLIs. Value: security. Effort: M. +- **Named profiles / multi-account support (M).** Let `~/.rill` hold multiple named credential+org profiles (`rill --profile work deploy`), instead of a single global token that assume/unassume juggles via backup keys. Value: users working across orgs/tenants. Effort: M. +- **`rill deploy --dry-run` (S/M).** Print the resolved plan — target org/project, deploy mode (managed/github/archive), git remote/subpath, and the list of `.env` keys to push — without mutating anything. Value: confidence before a destructive/first deploy; also mitigates cli-01/cli-12 surprises. Effort: S–M. +- **Deterministic local-server port handling (S).** On `rill start`, if the port is in use, either fail fast with a clear message or auto-select the next free port and print the chosen URL, replacing the health-check race in `PollServer`. Value: fewer "opened the wrong app" confusions. Effort: S. +- **`rill login --token`/stdin for CI (S).** A first-class non-interactive login that accepts a service token via flag/stdin/env and validates it, instead of relying solely on `--api-token` per-invocation. Value: smoother CI/automation. Effort: S. + +## Notes & Missing Test Coverage + +- **No tests for the local PKCE HTTP handlers.** `authHandler`/`authCallbackHandler`/`logoutHandler` have no coverage; the open redirect (cli-04), the `state` validation bug (cli-08), and the map race (cli-02) would all be caught by handler tests, including a `-race` test that fires two `/auth` requests concurrently. +- **No coverage for the deploy name-collision path.** The retrier/suffix branch in `DeployProject`/`RedeployProject` is exercised by neither unit nor e2e tests, which is why cli-01 (wrong project for `UpdateProjectVariables`) went unnoticed. A test that forces a `"name already exists"` error and asserts the variables target the created (suffixed) project would lock this down. +- **No concurrency test for `Helper`.** `Client()`/`Telemetry()`/`ReloadAdminConfig()` are only invoked serially in CLI usage; there is no test that exercises them from concurrent goroutines the way the local server does (cli-03). +- **`deviceauth` has only a verifier-charset test.** `VerifyDevice`/`GetAccessTokenForDevice` polling, retry classification, and the `redirect` encoding (cli-10) are untested. +- **Could not fully verify** the admin-server side of the open-redirect (cli-04) and double-escaped redirect (cli-10) — the assessment is based on the CLI side only, since the `redirect` parameter is currently always empty from CLI callers and its server-side contract was out of scope. + +## Verification Notes + +All 13 original findings were independently re-verified against the code; every one survives and none were removed (`removed_count = 0`). One high-signal miss was added (cli-14). Details: + +- **cli-01 (confirmed reachable).** The retrier's `nameConflictRetryErrClassifier` (`server.go:1017`) matches the substring `"name already exists"`, and the admin database returns `"a project with that name already exists in the org"` (`admin/database/postgres/postgres.go:4013`), so the suffix branch is genuinely reachable. `DeployProject` pushes variables to `r.Msg.ProjectName` (`server.go:456`) while the created project may be the suffixed `projResp.Project.Name`; the sibling `RedeployProject` correctly uses `projResp.Project.Name` (`server.go:576`). Scope note: the CLI `rill deploy` path (`cmd/project/deploy.go:424`) creates the project without a suffix retrier, so it is unaffected — the defect is specific to the UI-driven local server. +- **cli-02 (confirmed).** `pkceAuthenticators` is a plain map (`app.go:59`) written by `authHandler` (`server.go:825`) and read/deleted by `authCallbackHandler` (`server.go:845,852`); these run as independent `net/http` handler goroutines, so overlapping requests can trigger Go's fatal `concurrent map writes`. +- **cli-03 (confirmed).** `Client()`, `Telemetry()`, and `ReloadAdminConfig()` mutate `adminClient`/`activityClient`/`AdminTokenDefault`/`AdminURLDefault` with no mutex (only `gitHelperMu` exists, guarding `gitHelper`). Concurrent local-server RPC handlers (and the `trackingHandler` telemetry proxy) call these, so it is a real data race. +- **cli-06 (confirmed).** `ListMatchingProjects` (`server.go:733-745`) only special-cases `ErrInferProjectFailed`; any other error falls through to `return ... Projects: projects` with `projects == nil` and a nil error, silently swallowing the real failure. Contrast `GetCurrentProject` (`server.go:659`) and `GitStatus` (`git.go:38`), which `return nil, err`. +- **cli-07 (confirmed latent).** Every current caller passes `ch.Org`/`s.app.ch.Org`, or calls `SetOrg` immediately before (`server.go:297-303,491-496`), so `org == h.Org` always holds and the wrong-field construction (`helper.go:516`) has no present effect. +- **cli-09 (confirmed dead).** Grep found no references to the `deviceauth.Authenticator` interface anywhere in the tree; callers use `*DeviceAuthenticator` directly (`cli/cmd/auth/login.go:60,74`), and the concrete method signatures do not satisfy the interface. +- **cli-10 (confirmed, confidence raised to high).** The double-escape mechanism is certain; impact remains latent because all `Login`/`LoginWithTelemetry` callers pass an empty `redirectURL`. +- **cli-04 severity (kept medium).** The open redirect is real and the target fully attacker-controlled, but it is scoped to a running localhost instance and requires the victim to complete the full OAuth login; medium reflects that constraint. +- **cli-14 (added, missed by the reviewer).** `emitStartEvent` (`app.go:544-547`) returns the nil `err` from `parser.Parse` instead of `c.Err`, silently dropping the app-start telemetry event (and swallowing the error) whenever a connector fails analysis. Verified that `parser.AnalyzeConnectors` returns `[]*Connector` with an `Err error` field (`runtime/parser/connectors.go:17-24`). + +Also examined but intentionally not flagged: `initLocalAdminService` registers the `local_admin` driver into the global `drivers.Drivers` map via `drivers.Register`, which panics on re-registration and is an unsynchronized global write — a genuine fragility for in-process double-init (e.g. tests running two apps), but not reachable in normal single-invocation CLI usage (`rill start` and `rill project validate` each construct one `App` per process), so it was left as a note rather than a finding. diff --git a/audit/cube/README.md b/audit/cube/README.md new file mode 100644 index 000000000000..251454832390 --- /dev/null +++ b/audit/cube/README.md @@ -0,0 +1,13 @@ +# Cube Competitive Analysis (Aug 2026) + +Research basis: cube.dev blog (full dated post index), docs.cube.dev (llms.txt + pages), cube.dev/pricing, github.com/cube-js/cube, press/analyst coverage, HN/G2/third-party comparisons, and the Rill codebase + docs.rilldata.com. Structure mirrors [`../omni/`](../omni/). + +**TL;DR:** Cube pivoted from headless semantic layer to "agentic analytics platform" (D3 launch Jun 2025 → GA + rebrand Oct 2025) and has shipped an AI/agent feature roughly every two weeks since — skills, rules, certified queries, evals-in-CI, AI Studio, Slack agent, outbound MCP connectors, scheduled tasks, Python analysis, embedded agentic analytics. Its cracks: no data plane (pre-aggregation engineering is its performance tax and top user complaint), a 100% Cloud-gated AI platform (MCP at $80/dev/mo Premium; OSS "falling behind"), and a middleware position being commoditized by Snowflake/Databricks/dbt. Rill's counter: agents that are fast by default (managed OLAP), open all the way down (whole product OSS incl. local write-capable MCP), and able to *build* projects, not just query them. Biggest Rill gaps to close: AI operationalization packaging (skills/rules/evals/Slack/admin), Postgres-wire SQL API, semantic joins, SCIM/audit. + +| File | Contents | +|---|---| +| [`cube-features-core.md`](cube-features-core.md) | Cube's semantic layer (cubes/views, joins, multi-fact, Tesseract multi-stage calcs, calendar cubes), APIs (Semantic SQL/Postgres wire, DAX/MDX, Semantic Layer Sync, Control Plane, Rust CLI), caching (pre-aggregations, Cube Store, lambda), data sources, Cube Cloud (deployment types, BYOC, observability, SSO/SCIM, pricing), embedded suite, OSS/commercial split, company facts, 12-month ship log | +| [`cube-ai-and-market.md`](cube-ai-and-market.md) | Deep dive on D3 → Cube Agentic Analytics (architecture, agents, governance constructs, pricing, reception), Rill's public positioning/pricing as marketed, head-to-head perception (categorization gap, Luzmo framing), the 2025–26 AI-BI landscape (dbt, Snowflake, Databricks, Looker, ThoughtSpot, Omni, Hex, AtScale, OSI), and 2026 buyer criteria | +| [`rill-feature-inventory.md`](rill-feature-inventory.md) | Honest current-state Rill inventory from the codebase, Cube-focused: the full AI subsystem (agents, tools, MCP + OAuth, AI reports, evals harness, billing), semantic layer, APIs, connectors, cloud platform — plus verified gaps (no SQL API/JDBC, no pre-agg layer, no Power BI/Excel, no dbt, no SCIM/audit). Broader BI-surface inventory in [`../omni/rill-feature-inventory.md`](../omni/rill-feature-inventory.md) | +| [`comparison.md`](comparison.md) | Feature-by-feature Cube vs Rill matrix (✅/🟡/❌/➕) across 6 domains — AI/agentic first — plus "where Rill is structurally ahead" and Cube's structural advantages | +| [`roadmap.md`](roadmap.md) | Phased competitive roadmap: Phase 1 AI-operationalization parity (skills, rules/certified queries, customer evals, Slack agent, AI admin), Phase 2 interop & semantic depth (Postgres-wire Metrics SQL, joins, Sheets/Excel, outbound MCP, dbt, OSI), Phase 3 structural offense (benchmarks, embedded v2, self-healing background agent loops), GTM moves, deliberate non-goals. Items shared with the Omni roadmap marked ♻ | diff --git a/audit/cube/comparison.md b/audit/cube/comparison.md new file mode 100644 index 000000000000..3b0478bae5e5 --- /dev/null +++ b/audit/cube/comparison.md @@ -0,0 +1,117 @@ +# Cube vs Rill — Feature-by-Feature Comparison + +Legend: ✅ Rill has it (rough parity or better) · 🟡 partial/different equivalent · ❌ Rill does not have it · ➕ Rill advantage Cube lacks. Detail on the Cube side in `cube-features-core.md` and `cube-ai-and-market.md`; Rill side in `rill-feature-inventory.md`. + +**Framing:** Cube and Rill converged on the same pitch from opposite ends. Cube: headless semantic layer → added a first-party BI surface + agents (Oct 2025 GA). Rill: full-stack BI-as-code → marketing its metrics layer + MCP to agents. The battleground categories are (1) AI/agentic features, (2) semantic-layer depth, (3) external interoperability (SQL API, BI tools), (4) embedded analytics, (5) performance economics. + +--- + +## 1. AI & agentic features (the main event) + +| Feature | How it works in Cube | Rill status | Notes | +|---|---|---|---| +| Conversational analytics chat | Analytics Chat: multi-query analyses, summaries, links to semantic model; stateless "Explore" mode; admin prompt suggestions | ✅ | Rill: ProjectChat/DashboardChat/DeveloperChat; dashboard-context-aware (knows filters/time range); in-chat charts; URL citations to live dashboards — arguably better grounding UX | +| AI writes governed queries | **Semantic SQL**: AI authors SQL over semantic definitions; ad-hoc calcs allowed; every query reviewable as SQL or visually | ✅🟡 | Rill's analyst agent queries via structured metrics tools (safer, less expressive); Metrics SQL exists but is not the agent's primary interface and rejects JOINs. Cube's "reviewable Semantic SQL" is a stronger transparency artifact | +| AI model authoring ("AI data engineer") | Semantic Model Agent: bootstraps model from warehouse schema, **converts LookML**, adds measures/joins/views conversationally; AI-assisted onboarding auto-generates a starter model with reviewable diffs | ✅🟡 | Rill's developer agent + `init_project` + `develop_file` covers scaffolding/editing incl. whole projects; no LookML converter, no query-pattern-driven model optimization | +| Agent skills | `agents/skills/*.md` in repo (frontmatter + instructions), chat buttons/slash menu/auto-match, versioned like code; **plus open-source Claude Code skills repo** (`cube-agent-skills`, 9 skills, plugin marketplace) | ❌ | Rill ships internal agent instructions and `rill init --agent claude/cursor` exports, but no user-defined skills surfaced in chat | +| Agent rules / certified queries | **Rules** (always + agent-requested markdown), **Certified Queries** (admin-approved SQL agents reuse), **Memories** (tenant/space/user isolation), **Agent Spaces** (RBAC groupings), multi-agent per deployment | 🟡 | Rill has `ai_instructions` (project + metrics view) — rules-lite. No certified-query library, no memories, no multi-agent config, no agent spaces | +| Customer-facing AI evals | **Cube Evals** (`agents/eval_questions.yml`: NL question + ground-truth SQL; sort-invariant numeric-tolerant comparison; per-branch; CI-gateable; AI Studio UI) | ❌ | Rill has an internal eval harness (`runtime/ai/evals/`, golden transcripts) — raw material exists, not productized | +| AI observability/admin | AI Studio (tune/observe/eval/ship), Chats History (admin view), Usage Analytics incl. AI usage, per-seat AI token grants + packages | 🟡 | Rill meters AI tokens for billing and has feedback attribution (unique!), but no admin AI-quality/usage surface | +| Scheduled AI tasks | **Scheduled Tasks**: NL prompt + cadence, headless under creator's security context; can query, search web, build/update reports & dashboards, email members | ✅ | Rill: AI-powered scheduled reports (`resolver: ai`) run the analyst agent per recipient **with each recipient's security policies** — per-recipient RLS is ahead of Cube; but can't build dashboards or search web | +| Slack agent | Cube Slack Agent (May 2026): DM the app, threads = chat sessions, email-matched identity, user's own RLS applies (Premium+) | ❌ | Rill's Slack driver is notifier-only. High-visibility gap | +| MCP server (inbound) | Hosted `cubecloud.dev/mcp`, OAuth+PKCE, role-scoped tools, **Premium/Enterprise only**; Claude Connectors Directory listing (Aug 2026) | ✅➕ | Rill: MCP per project incl. **free local product**, full OAuth stack, and **write tools** (file read/write with edit access) — agents can *build* in Rill, not just query. Cube gates MCP behind $80/dev/mo | +| MCP connectors (outbound) | Agent consumes external MCP tools (Notion, Linear, Sentry, Attio + custom); used for context, model metadata, and write-back (file a ticket, write a recap) | ❌ | Rill agents cannot reach external tools | +| A2A / agent-to-agent | Analytics Chat API wrappable as a tool for external agents; A2A protocol marketed | 🟡 | Rill's MCP serves the same job for MCP-speaking agents; no streaming chat API productized for embedding in other agents' loops | +| Python / advanced analytics | Sandboxed Python on workbook tabs (Prophet, stats/ML preinstalled); agent auto-invokes for forecasting/regression/clustering/anomaly questions | ❌🟡 | Rill has AI anomaly "Explain" (root-cause narratives on metric shifts — marketed, well received) but no general Python/forecasting execution | +| AI anomaly explanation | AI Widget (narrative summaries on dashboards, custom prompts) | ✅➕ | Rill's "Explain" (click a spike → root-cause summary + charts + drill links + synced dashboard) is more interactive than Cube's static AI Widget | +| BYO LLM | BYOM incl. Snowflake Cortex; Enterprise tier; pinnable model list; `runtime: plain|reasoning` | ✅ | Rill: `ai_connector` (OpenAI/Azure, Claude, Gemini) from Growth tier — more accessible than Cube's Enterprise gating | +| AI in embeds | Embedded Analytics Chat (iframe + Chat API), white-labeled agent name/branding | ✅🟡 | Rill embeds chat with per-end-user history (`external_user_id`) + postMessage AI pane control; no chat-only API, no agent white-labeling | +| Coding-agent DX | Rust CLI designed as agent interface; open-source Claude Code skills; dashboards-as-code API | ✅➕ | Rill: everything already YAML/SQL in git + `rill init --agent` + local MCP — "Claude Code builds your whole project" is Rill's best story; Cube is now investing here fast | +| Eval/accuracy marketing | LLM benchmark content, "3x more accurate" research, Gartner Agentic Analytics Market Guide listing | 🟡 | Rill blogs "golden completions, not vibes" but publishes no benchmark, no analyst listings | + +**Net:** Rill's agent *architecture* (multi-agent runtime, MCP-native, write-capable, per-recipient-security AI reports, feedback attribution) is competitive or ahead. Cube's agent *operationalization* (skills, rules, certified queries, memories, evals, AI Studio, Slack, outbound MCP, Python) and *packaging/marketing* are well ahead — Cube productized the loop Rill only runs internally. + +## 2. Semantic layer + +| Feature | Cube | Rill status | Notes | +|---|---|---|---| +| Joins / relationship graph | Cubes declare joins (cardinality-aware, Dijkstra path resolution); views pin join paths | ❌ | **Rill's #1 structural gap** (same vs Omni): metrics views bind to one model/table; Metrics SQL rejects JOINs; escape valves = lookup dims, upstream models | +| Multi-fact analysis | Multi-fact views on shared dimensions, fan-out-safe (Tesseract, GA v1.7) | ❌ | No cross-metrics-view stitching | +| Multi-stage calcs | PoP, % of total, running, YTD/QTD via Tesseract `grain`/`filter` directives | ✅ | Rill: derived/window/time-comparison measures — near parity, arguably cleaner YAML | +| Custom calendars | **Calendar cubes** (4-5-4 retail, fiscal, time shifts) | ❌ | Rill: `first_month_of_year` only; no fiscal calendar (also flagged vs Omni) | +| Modeling languages | YAML **+ Jinja/Python**, or JavaScript; dynamic per-tenant model generation | 🟡 | Rill: YAML + Go templating (`.env`, user attrs, dev/prod) — no programmatic model generation, no per-tenant dynamic models | +| Security | Data Access Policies: row-level, member-level, **masking**; user attributes/groups | ✅🟡 | Rill: access/row filters/field access, templated on JWT attrs — parity except **no masking mode** | +| Organization | Views, view groups, hierarchies, nested folders, links in model | 🟡 | Rill: explores select fields; no folders/hierarchies metadata for large models | +| Drill members | `drill_members` + client `drillDown()` | ❌ | No drill-to-records path (same gap vs Omni) | +| Catalog / lineage | **Semantic Catalog**: search across model + upstream warehouse + downstream BI content; Data Graph lineage | 🟡 | Rill has project DAG + resource lineage UI in Developer, not a catalog product | +| dbt integration | One-way dbt→Cube sync with CI/webhooks + review branches; `cube_dbt` | ❌ | None | +| Ingestion/transformation | **None — Cube models over existing warehouse tables** | ➕➕ | Rill's full ELT: sources, SQL models, **incremental + partitioned models**, staging cross-connector flows, data-quality tests. Cube depends on warehouse + dbt | +| Consistency guarantee | Model compiled per request over live warehouse | ➕ | Rill reconciler continuously validates whole project DAG; parse errors surface immediately | + +## 3. Performance & caching + +| Feature | Cube | Rill status | Notes | +|---|---|---|---| +| Pre-aggregations | Declared in model, **aggregate awareness** matching, refresh workers, partitioned/incremental builds, lambda (streaming merge), Cube Store (distributed Rust/Parquet store) | 🟡 | Rill's answer is architectural: queries hit a real OLAP engine (DuckDB/ClickHouse/Druid/Pinot/StarRocks). New metrics-view `rollup:` is early. Different philosophy: Cube accelerates a slow warehouse; Rill replaces it | +| Result caching | In-memory + `cache` control per query | ✅ | Runtime LRU + `cache.key_sql`/`key_ttl` | +| Sub-second at scale | Only via pre-aggs (build/refresh complexity is Cube's #1 user complaint) | ➕➕ | Rill's core wedge: managed OLAP, no pre-agg modeling burden, real-time-ish via live ClickHouse | +| Streaming | ksqlDB/Materialize/RisingWave sources + lambda pre-aggs | 🟡 | Rill: no Kafka connector; Kafka via ClickHouse only | +| Warehouse-direct | The default mode (Snowflake, BigQuery, Databricks, Fabric, 20+ engines) | 🟡 | Rill has warehouse-direct OLAP mode (BigQuery/Snowflake/Databricks) but it's secondary and less battle-tested | + +## 4. APIs & interoperability + +| Feature | Cube | Rill status | Notes | +|---|---|---|---| +| SQL API (Postgres wire) | **Semantic SQL over Postgres protocol** — any BI tool/psql client connects; pushdown GA; declared the primary API | ❌ | **Rill's #1 interop gap.** No Postgres wire endpoint; REST/gRPC/custom APIs/MCP only | +| Power BI / Excel | **DAX API** (native Power BI), **MDX API** (Excel pivots), Excel + Sheets add-ins | ❌ | Nothing. Blocks every Microsoft-estate deal | +| BI tool sync | Semantic Layer Sync (Superset/Preset/Metabase/Tableau) | ❌ | None — deliberate historically ("Rill is the BI tool"), but now blocks "semantic layer for your existing stack" deals | +| GraphQL | Yes | ❌ | Low priority; REST/OpenAPI covers embedded devs | +| REST APIs | JSON API + Control Plane API (deployments, users, dashboards-as-code, SCIM, embed sessions; OpenAPI) | ✅ | Runtime + admin APIs (168 RPCs) + custom APIs w/ OpenAPI; parity in capability | +| Custom API endpoints | Not a feature (you build an app on the APIs) | ➕ | Rill custom APIs: YAML endpoint + resolver + security + OpenAPI — nice embedded/back-end story | +| Orchestration hooks | Airflow/Dagster/Prefect providers for refresh | 🟡 | Rill: refresh via CLI/API cron; no orchestrator provider packages | +| CLI | New Rust `cube` CLI, full API coverage, agent-oriented | ✅ | `rill` CLI mature and broader (local dev server included) | + +## 5. Consumption surfaces & embedded + +| Feature | Cube | Rill status | Notes | +|---|---|---|---| +| Dashboards | First-party dashboards (GA Oct 2025): tables/charts/KPI/custom HTML/markdown; dashboards-as-code API | ✅➕ | Rill explore + canvas are years more mature (TDD, pivots, bookmarks, public URLs, themes, dark mode) | +| Slice-and-dice explore | Workbooks (point-and-click + calcs + SQL + Python) | ✅➕ | Rill Explore is best-in-class for speed; but workbooks include ad-hoc calcs/SQL/Python that Rill viewers lack | +| Viz breadth | bar/line/area/scatter/pie/heatmap/boxplot/table/KPI/**maps (point+choropleth)**/custom HTML/Vega-Lite; small multiples, dual axes, reference lines | 🟡 | Rill lacks maps, boxplot, small multiples, reference lines (same gaps vs Omni); has funnel/donut/stacked-100% Cube lacks natively | +| Embedded dashboards/chat | iframes (theming, SSO, signed auth, postMessage, localization), **Creator Mode**, Chat API, React Embed SDK (preview) | ✅🟡 | Rill embed (iframe + postMessage + RLS + per-user state + AI history) is strong; **no creator mode, no React SDK, no chat-only API, no localization** | +| Alerts / reports | Scheduled Tasks (AI) + reports; no classic threshold alerting found | ➕ | Rill: full alerting (criteria, per-user RLS eval, email/Slack) + scheduled exports (CSV/XLSX/Parquet) + AI reports | +| Excel/Sheets consumption | Native add-ins + MDX pivots | ❌ | None | + +## 6. Cloud platform & enterprise + +| Feature | Cube | Rill status | Notes | +|---|---|---|---| +| SSO / SCIM | SAML (Google/Entra/Okta) + SCIM 2.0 + LDAP (Enterprise) | 🟡 | Rill: OIDC/Auth0 SSO; **no SCIM** (also flagged vs Omni) | +| Audit log | Enterprise audit log + Chats History | ❌ | None | +| Custom roles | Enterprise | 🟡 | Fixed org/project roles + groups | +| BYOC / private networking | **BYOC on AWS/Azure/GCP**; VPC peering/PrivateLink/PSC | 🟡 | Rill: VPC peering (Enterprise); no BYOC data plane | +| Multi-tenant infra | Multi-cluster routing by tenant (>100 tenants), per-tenant models/data sources | 🟡 | Rill: org/project isolation + provisioner (k8s runtimes, managed ClickHouse); no per-tenant dynamic model story | +| Observability for admins | Query History, Performance Insights, usage analytics, monitoring integrations | 🟡 | Project logs/status + billing usage; no customer-facing query-history/BI-usage analytics | +| Git workflow | IDE branch dev mode, GitHub/GitLab/Bitbucket, staging envs | ✅➕ | Rill: git **is** the source of truth; branch deployments; cloud edit sessions; local single binary — better DX | +| Open source | Cube Core 20.7k stars, Apache/MIT; but the entire AI/BI frontend is Cloud-only | ✅➕ | Rill OSS includes the full product (dashboards, AI chat with BYO key, MCP) locally — stronger OSS story where it counts | +| Pricing transparency | $40–$80/dev + $20–$40 consumer seats + compute; MCP Premium+; DAX/BYOM/SSO Enterprise | ➕ | Rill $20–$30/seat + usage; embedded flat $500/mo per 100 seats; BYO DB + BYO LLM at Growth. Simpler, cheaper story | + +## 7. Where Rill is structurally ahead + +1. **Full data plane**: ingestion → incremental/partitioned models → OLAP → dashboards in one binary/platform. Cube has no ingestion or transformation; it inherits warehouse cost and latency. +2. **Speed economics**: sub-second interactivity without pre-aggregation engineering (Cube's most complained-about surface). At event scale, Rill's cost/latency floor is Cube's ceiling. +3. **Finished BI surface**: mature explore/canvas/alerts/reports/public URLs vs Cube's one-year-old dashboards. Luzmo's framing: Rill "ships an interface rather than expecting you to build one." +4. **MCP + write-capable agents everywhere, including free/local**: Cube gates MCP at Premium and its agents can't edit the model from scheduled runs; Rill's developer agent writes project files, and coding agents build whole projects via `rill init --agent`. +5. **Per-recipient security on AI reports** and feedback attribution — governance depth Cube doesn't match. +6. **Pricing simplicity** and BYO-infrastructure (DB + LLM) below enterprise tier. +7. **OSS completeness**: Rill's open-source product is the whole product; Cube's AI platform is 100% Cloud-gated. + +## 8. Cube's structural advantages + +1. **Universal interoperability**: Postgres-wire Semantic SQL + DAX/MDX/Sheets/Excel + Semantic Layer Sync — Cube plugs into every existing BI estate; Rill requires adopting Rill's UI. +2. **Joins/multi-fact semantic model** — models real enterprise schemas; Rill's single-table metrics views can't. +3. **AI operationalization suite**: skills, rules, certified queries, memories, evals-in-CI, AI Studio, Slack agent, outbound MCP connectors, Python analysis — a productized trust/tuning loop. +4. **Install base + analyst mindshare**: 20.7k stars, "20% of F1000," Dresner #1, GigaOm Leader, Gartner Agentic Analytics listing, OSI founding member. Rill is absent from all these lists. +5. **Warehouse-native credibility**: 20+ engines incl. Fabric/streaming DBs; per-user warehouse OAuth; BYOC. +6. **Embedded agentic breadth**: Chat API + Creator Mode + React SDK + localization. +7. **Ship velocity + narrative ownership**: a launch every ~2 weeks and the "agentic analytics" category name (they coined it and got Gartner to bless it). diff --git a/audit/cube/cube-ai-and-market.md b/audit/cube/cube-ai-and-market.md new file mode 100644 index 000000000000..dceadeab4045 --- /dev/null +++ b/audit/cube/cube-ai-and-market.md @@ -0,0 +1,98 @@ +# Cube — AI Platform ("Agentic Analytics"), Market Position & Landscape + +> Researched Aug 2026 from public web sources (cube.dev blog/docs/pricing, press, G2, third-party comparisons). Note: "Cube" (cube.dev, semantic layer) is often conflated with "Cube Software" (FP&A tool); the latter is excluded. Companion file `cube-features-core.md` covers the semantic layer/API/caching platform. + +## 1. Cube D3 → "Cube Agentic Analytics" + +### Timeline & framing +- **June 2, 2025**: "Cube Launches D3: The First Agentic Analytics Platform Built on a Universal Semantic Layer" (D3 = "data in cube"). Gradual access through summer 2025. +- **October 29, 2025**: GA — the "D3" name is dropped; semantic layer + agentic products unified under one UI and brand: **"Cube Agentic Analytics."** +- Homepage tagline (Aug 2026): *"The agentic analytics platform built on a semantic layer. AI answers your team — and your customers — can trust. Grounded in your semantic model, governed end to end."* +- Launch coverage was trade press (BigDATAwire, DBTA, insideAI News) + wire pickup; no dedicated TechCrunch/VentureBeat story found. + +### Architecture +- Core thesis: LLMs over raw tables hallucinate; grounding in a governed semantic layer fixes it ("Without this governed, business-friendly layer, AI agents querying raw data directly are prone to errors, miscalculations, and 'hallucinations'"). +- Analytics decomposed into **three AI-safeguarded layers** (compilation checks, linters, best-practice prompts, documentation, memory retrieval): (1) building the semantic layer; (2) building **Semantic SQL** queries on it; (3) creating visualizations from Semantic SQL results. +- **Semantic SQL** is the pivotal mechanism: the AI writes SQL against semantic definitions (not raw tables), can add ad-hoc calculations, and every query is reviewable/editable visually or as SQL. +- Governance constructs: **Agent Spaces** (agent groupings with role-based permissions), **Rules** (always-rules + agent-requested rules), **Certified Queries** (admin-approved SQL agents may reuse), **BYOM** (bring-your-own LLM, multi-LLM). Marketed "**AI Context Layer**" = semantic layer + business context + adaptive learning. +- Agent access protocols: **MCP** and **A2A** (agent-to-agent), incl. an "agent-to-agent capable via MCP" Analytics Chat API. + +### Product surfaces at GA +1. **Analytics Chat** — conversational interface; multi-query analyses with summaries and links back to the semantic model. +2. **Workbooks** — AI-assisted exploration combining point-and-click, calculations, SQL, and **Python**. +3. **Dashboards** — presentation layer (tables, charts, KPI cards, custom HTML/markdown); added at GA. +4. **Semantic Model Agent ("AI Data Engineer")** — auto-builds/improves models from warehouse tables, **converts LookML projects**, manages measures/dimensions/joins/SQL transforms. +5. **AI Data Analyst** — NL querying producing Semantic SQL, visualizations, "data apps." +6. **Embedded Agentic Analytics** — chat, workbooks, dashboards embeddable via iframes; **Analytics Chat API**; **Creator Mode** (customers build their own workbooks/dashboards inside your app); white-labeled ("your colors, your branding, your agent name"). + +Demos: full-platform demo (youtube gvDy37p7AZ0), Dec 2025 walkthrough (n-U1FvHqE2Q), "warehouse to embedded AI in 39 minutes" founders demo (7ZQGGepDjUQ). + +### Reception & reported limitations +- G2 snippet: "the AI analyst can be a little slow when retrieving information," though "the MCP makes up for it." +- Marquee proof point: **"Brex chose Cube over dbt Semantic Layer and LookML — the semantic layer is what makes the AI useful at scale."** +- Mitzu critique: models are hand-authored and need ongoing maintenance; because the LLM authors SQL, "methodology errors on funnels, retention and journeys are still possible"; semantic shape doesn't natively express product-analytics primitives. +- Luzmo (Aug 2026): Cube "sits firmly in the headless camp and has been adding pieces" of embedded analytics; flags the buyer risk of the semantic layer "becoming a separate platform project." +- Cube's own "Cube Cloud, Headless No More?" post (June 2025) pre-empts channel conflict with its BI partners (Tableau, Power BI, Superset…) — an acknowledged tension of shipping a first-party BI surface. +- Little organic Reddit/HN discussion of D3; reception evidence is mostly vendor-published + trade press + G2. + +## 2. Pricing & packaging (cube.dev/pricing, Aug 2026) + +- **Free**: forever-free; ≤5 workbooks; 1,000 daily queries; limited agent requests with full feature access. +- **Starter**: **$40/developer/mo**; unlimited workbooks; 10K–50K daily queries; extended agent limits + premium LLM access; Cube Store caching; Semantic Layer Sync. +- **Premium**: **$80/developer/mo** + consumer seats — **Explorer $40/user/mo**, **Viewer $20/user/mo**; unlimited queries; embedded dashboards + analytics chat; multi-cluster $1.20/hr/cluster; 99.95% SLA. +- **Enterprise**: custom; 99.99% SLA; single-tenant/BYOC; custom LLM; SAML SSO; **DAX API for Power BI**. +- Principle stated at GA: seat-based for direct access; **embedded stays compute-based**; AI/agent usage bundled into tiers (no separate credits). + +## 3. Company scale & funding + +- Launch-PR metrics: installed on **90,000 servers**, **~5M users**, **20% of the Fortune 1000** as customers. +- Funding: $6.2M seed (2020) → $15.5M Series A (2021, Decibel) → **$25M (June 2024, Databricks Ventures joining)** = **$48M total**. 4x new-customer growth, 3x bookings 2023→2024. No 2025–2026 raise found. +- Contrast: Rill has raised ~$13.8M (seed-stage, latest Seed II July 2025). + +## 4. Rill's public positioning (for reference) + +- Homepage: **"The fastest business intelligence tool for humans and agents"**; banner "Build fast agentic analytics with Claude Code and Rill." +- Pillars: define-once semantic layer; branded embedded analytics; NL Q&A with "visual, verifiable" answers (URL citations — "the URL an agent cites is the same URL a human opens"); **AI anomaly detection / "Explain"** (root-cause summaries on metric shifts); BI-as-code with Claude/Cursor; Canvas dashboards. +- Pricing (Aug 2026): Starter **$20/seat/mo** (≤20 seats, 3 projects, embed previews only, 1M AI tokens/seat/mo, ≤10GB managed DB, $0.15/CU-hr) · Growth **$30/seat/mo** (≤100 seats, 10 projects, **embedded $500/mo up to 100 active embedded seats**, 2M tokens/seat + 200k/embedded seat, BYO AI model, ≤1TB, $0.20/CU-hr) · Enterprise custom (unlimited embedded seats, VPC peering). $250 starting usage credit on all plans. +- Packaging contrast vs Cube: Rill meters **AI as token quotas per seat**; lets customers **BYO database (ClickHouse, MotherDuck, Snowflake…) and BYO AI model** below enterprise tier; flat embedded pricing vs Cube's compute-based embedded. +- 2025 ships (year-in-review): AI anomaly detection, AI Chat + MCP, Canvas, BYO ClickHouse/MotherDuck (zero-copy), embed iframe API, public API docs. Agentic-architecture blog (May 2026) describes the router/analyst/developer agent design, "golden completions, not vibes" evals, MCP-native runtime. +- ClickHouse relationship: no formal partnership found, but deep co-marketing (ClickHouse's own "Rill and ClickHouse: real-time operational BI for a metered world" post, joint meetups, dlt+ClickHouse+Rill content). Similar with MotherDuck. +- Heritage: founded 2020 by Michael Driscoll; team previously built Metamarkets (→ Snap; database open-sourced as Apache Druid). + +## 5. Head-to-head perception + +- **Categorization gap**: Cube appears in essentially every 2026 semantic-layer roundup (Bruin, Holistics, Atlan, Promethium, Dawiso). **Rill is absent from most of them**, categorized instead as BI / operational BI / BI-as-code. +- Clearest third-party framing (Luzmo, Aug 2026): Rill is the middle path — "BI-as-code… keeps the code-first workflow that draws people to Cube, **but ships an interface rather than expecting you to build one**." +- **Cube does not acknowledge Rill**: its "Best BI Tools 2026" article lists Looker, Power BI, Tableau, Sigma, ThoughtSpot, Hex, Metabase, Sisense, GoodData, Databricks, Snowflake — no Rill. +- Convergence: since GA, Cube ships chat/workbooks/dashboards/embedded — a direct competitor for the analytics *surface* including embedded (Rill's commercial wedge); Rill markets its metrics layer + MCP as a semantic layer for agents — entering Cube's narrative from the other side. Near-identical language on both sites. +- Sharpest technical contrast in public materials: Cube = warehouse-agnostic middleware with caching/pre-aggregations (Cube Store); Rill = semantic layer coupled to a fast OLAP engine (DuckDB embedded, live ClickHouse/MotherDuck/Druid/Pinot) for sub-second dashboards. +- Community signal: Rill praise centers on speed ("even though we have Looker, analysts prefer to do everything in Rill because it's fast" — Liftoff); Cube's on AI grounding (Brex; Delphi's 100%-accuracy runs over Cube's layer). Cube has substantial G2 presence; Rill's is thin (named testimonials/case studies: Emodo, Liftoff, Angel Studios, Syft, NOCD, Sabio). + +## 6. Broader AI-BI landscape (pressure on both) + +- **dbt Labs**: Coalesce Oct 2025 — Fusion engine, four AI agents (incl. Analyst agent in now-GA **dbt Insights**), MCP server, **MetricFlow open-sourced (Apache 2.0)** co-maintained with Snowflake/Salesforce; **dbt + Fivetran merger** bundles semantic layer + consumption into the default pipeline tool. +- **Snowflake**: **Semantic Views as native DB objects** (SQL querying GA Mar 2026), Cortex Analyst (~90%+ claimed accuracy), Snowflake Intelligence, verified queries. Makes third-party semantic layers look redundant for Snowflake-committed shops — existential squeeze on Cube's middleware position. +- **Databricks**: AI/BI Genie (84.67% in runQL's 2025 benchmark), **Metric Views GA early 2026**. (Databricks Ventures is a Cube investor — hedged.) +- **Google Looker**: Conversational Analytics GA grounded in LookML + a **Conversational Analytics API** (GA for BigQuery/Looker) aimed at embedding governed NL agents — attacks both Cube's Analytics Chat API and Rill's embed story. +- **ThoughtSpot Spotter**: strong brand; scored **54.67%** in runQL's benchmark — the proof point both Cube and Rill use that a chat UI ≠ trustworthy answers. +- **Omni**: BI + built-in semantic layer + AI; **acquired Explo (embedded) Oct 2025**; **$120M Series C at $1.5B (April 2026)** on ~$30M ARR. Packages Cube's governance story + Rill's finished-interface story + embedded, with far more capital. +- **Hex**: $70M Series C (May 2025); notebook-first AI workspace (Reddit, Anthropic, Figma, NBA). +- **AtScale**: the other pure universal semantic layer; 2025 GigaOm Radar Leader; strong in Power BI/Excel/DAX estates. +- **Select Star**: catalog repositioning as "context for AI agents"; OSI co-leader. +- **Startups**: Zenlytic, TextQL, Dot, Querio, Honeydew, Mitzu, runQL, Promethium — collectively commoditizing the "chat with governed data" pitch. +- **Open Semantic Interchange (OSI / "Apache Ossie")**: launched Sept 2025 by Snowflake, Salesforce, dbt + **Cube, Omni, Hex, Sigma, ThoughtSpot, Select Star, Alation, Atlan, BlackRock, Mistral AI**; v0.1 spec, incubating at Apache. **Rill is not a listed member** — a standards-visibility gap. + +## 7. What buyers care about (2026 evaluation criteria) + +1. **AI grounding/governance** — #1 criterion: do AI answers rest on governed metrics or raw tables (Luzmo; Gartner Agentic Analytics Market Guide: guardrails now "explicit requirements"). +2. **NL accuracy with evidence** — cited numbers: raw text-to-SQL ~16.7% vs ~83% with a semantic layer (Cube-commissioned research); Delphi 100%-accuracy runs; runQL 2025 (Cortex 88.67%, Genie 84.67%, Spotter 54.67%). Buyers increasingly ask for **eval harnesses**. +3. **Cost legibility** — dev vs viewer vs consumption seats; AI metering (Rill tokens vs Cube bundling); embedded per-tenant economics; warehouse compute generated by agents. +4. **Latency/interactivity** — caching/pre-agg strategy "makes or breaks an embedded experience"; Rill's founding pitch; the one recurring Cube AI complaint (slow AI analyst). +5. **Embedding & frontend ownership** — build vs configure; multi-tenant RLS; white-label; embeddable chat/agents. +6. **Self-hosting/BYO/data gravity** — OSS core (both), BYOC (Cube Enterprise), BYO DB + LLM (Rill Growth+), zero-copy vs data movement. +7. **Interoperability/lock-in** — OSI membership, MetricFlow Apache 2.0, LookML conversion, MCP support (now table stakes). + +## 8. Bottom line + +- **Cube** converted semantic-layer credibility into a full-stack agentic analytics platform (Oct 2025 GA), accepting collision with its former BI partners. Moats: install base (90k servers, 20% of F1000, Brex), Semantic SQL governance machinery. Exposure: platform-native semantics (Snowflake/Databricks), dbt+Fivetran bundling, and better-funded surface rivals (Omni). +- **Rill** attacks from the opposite end: open-source, OLAP-fast, BI-as-code "for humans and agents," MCP-native multi-agent runtime, transparent pricing, ClickHouse/MotherDuck alignment. Weaknesses: ~$13.8M funding, thin analyst/review presence, absence from semantic-layer roundups and OSI, and now direct overlap with a larger Cube in embedded, chat, and agent access. diff --git a/audit/cube/cube-features-core.md b/audit/cube/cube-features-core.md new file mode 100644 index 000000000000..5f699742f091 --- /dev/null +++ b/audit/cube/cube-features-core.md @@ -0,0 +1,97 @@ +# Cube — Core Platform Inventory (semantic layer, APIs, caching, cloud) + +> Researched Aug 2026 from cube.dev blog (dated post index), docs.cube.dev (llms.txt + pages), cube.dev/pricing, GitHub, press, HN/G2. Companion file `cube-ai-and-market.md` covers the AI platform and market landscape in depth. + +## 0. Positioning snapshot (mid-2026) + +- Homepage: **"The agentic analytics platform built on a semantic layer."** GitHub: "Cube Core is open-source semantic layer for AI, BI and embedded analytics." +- 2025–2026 pivot: "universal/headless semantic layer" → **full agentic BI platform** with a first-party frontend (chat, workbooks, dashboards), with open-source **Cube Core** as the foundation. Definitive framing: CEO post "The Future of Cube Core and Cube" (May 14, 2026). "D3" brand introduced June 2025, retired Oct 2025. +- Cube Dev, Inc.: founded 2019 by Artyom Keydunov (CEO) + Pavel Tiunov (CTO), spun out of Statsbot. + +## 1. Semantic layer / modeling + +- Models in **YAML or JavaScript**; YAML supports **Jinja + Python**; JS runs in a Node VM. Git-managed (branches, dev mode, CI). +- **Cubes** (tables/SQL queries; measures, dimensions, joins, segments, pre-aggregations, access policies) + **views** (curated facades with explicit join paths — what consumers and AI agents query). **View groups** (v1.7, Jul 2026). **Hierarchies and folders** (v1.2, Feb 2025), nested folders (v1.5). +- **Joins**: many_to_one/one_to_many/one_to_one; automatic join-path resolution (Dijkstra over the join graph); views pin explicit paths; strict validation since v1.6. +- **Multi-fact views**: cross-fact analysis on shared dimensions without fan-out (Tesseract-powered, GA v1.7). +- **Tesseract**: Rust rewrite of the query/modeling engine, announced Oct 2024, **GA and default in Core v1.7 (Jul 8, 2026)**. Powers **multi-stage calculations** (period-over-period, percent-of-total, running aggregates, YTD/QTD), `grain`/`filter` directives, `switch` dimensions, `case` measures, XIRR, conditional data masking, number formatting, links in the model. +- **Custom granularities** (v0.36, Sept 2024); **calendar cubes** (custom 4-5-4 retail/fiscal calendars, time shifts — v1.5, Oct 2025). +- Segments, drill members (`drill_members` + `ResultSet.drillDown()`), proxy/subquery dimensions, `extends` inheritance, polymorphic cubes, data blending. +- **Dynamic data models**: programmatic generation via Jinja/Python or JS (`COMPILE_CONTEXT`, `FILTER_PARAMS`, per-tenant models/data sources). +- **Data Access Policies** (row-level, member-level, **member masking**) — GA Feb 2025, in Core; user attributes, groups, `context_to_groups`; policy viewer UI in Cloud. +- Migration tooling: **`lkml2cube`** (LookML→Cube), **`cube_dbt`**; sustained SSAS-displacement campaign; **dbt integration** shipped Jul 16, 2026 (one-way dbt→Cube with CI/webhook sync + review branches; Snowflake/Redshift/Postgres/BigQuery). + +## 2. APIs & integrations + +- **SQL API ("Semantic SQL")** — **Postgres-wire-compatible**; extends SQL with `MEASURE()`; any Postgres client/BI tool connects; query pushdown GA; HTTP transport (`/v1/cubesql`, NDJSON streaming) since v1.5; window functions (v1.7). Declared "**the primary Cube Core API going forward**" (May 2026) — JSON REST API de-prioritized. +- **REST (JSON) API** (`/v1/load`, `/v1/meta`, WebSocket subscriptions), **GraphQL API**. +- **DAX API** — native **Power BI** connectivity (Feb 2025, Enterprise). **MDX API** — native **Excel pivot tables** (Jul 2024, Cloud). **Cube Cloud for Excel** add-in (Feb 2025); **Cube Cloud for Sheets** (Sept 2024). +- **Semantic Layer Sync** — pushes the model into BI tools: Superset/Preset + Metabase (paid plans), Tableau (Enterprise). +- **Orchestration API** — pre-aggregation refresh from Airflow (`airflow-provider-cube`), Dagster, Prefect. +- **Control Plane / Platform API** — REST automation of deployments, env vars, tokens, model files/branches, dbt sync, workbooks/reports/**dashboards-as-code**, users/groups/policies, SCIM 2.0, OIDC, embed sessions/tenants; OpenAPI published. +- **Chat API (Embed API)** — streaming conversational-agent API; supports agent-to-agent wrapping. +- **AI API** (May 2024; value search + BYOLLM + Slack app Mar 2025; Snowflake Cortex LLM Apr 2025). +- **MCP server** — hosted `https://cubecloud.dev/mcp` (OAuth + PKCE); Premium/Enterprise; role-scoped tools; **official Claude Connectors Directory listing (Aug 20, 2026)**. +- **Rust CLI** (`cube`, Jul 21, 2026, open source): OAuth device flow, `--json` everywhere, covers the entire REST API — explicitly designed as an **agent interface**. +- JS SDKs (`@cubejs-client/core`, react, vue3, ngx, ws). No native JDBC/ODBC — Postgres wire compat is the interop path. +- Accumulated tool integrations: Tableau, Power BI, Excel, Sheets, Superset/Preset, Metabase, Hex, Retool, Streamlit, Observable, Deepnote, Klipfolio, Hashboard, Embeddable, Budibase, Appsmith, Bubble. + +## 3. Caching & performance + +- **Two-level caching**: in-memory result cache + **pre-aggregations** declared in the model, background-refreshed, matched via **aggregate awareness**. +- **Cube Store**: purpose-built distributed OLAP store for pre-aggregations (Rust; Parquet + Arrow + DataFusion; router/worker architecture; sub-second, high concurrency). v1.6 (Dec 2025) upgraded DataFusion 4→46: DECIMAL(38), CTE planning, **pre-aggregation acceleration of multi-stage calculations**. +- **Refresh workers** (scheduled `refresh_key`, partitioning, incremental builds); **lambda pre-aggregations** (merge historical rollups with fresh/streaming data for near-real-time). +- v1.7: pre-aggs with multiple time dimensions, per-subquery matching, pre-agg-specific data sources; columnar JS↔Rust transport (~5–20x faster result handling). v1.5: 2–3x model-compilation speedup OSS ("up to 30x" in Cloud). +- Cloud extras: export buckets (S3/GCS), customer-managed keys for Cube Store, BYO pre-agg storage bucket, deployment warm-up. + +## 4. Data sources + +Vendor-supported: Snowflake, BigQuery, Databricks (OAuth service principals), Redshift, Microsoft Fabric, ClickHouse, SingleStore, Pinot, Firebolt, Vertica; Athena, DuckDB/MotherDuck, Presto, Trino; Postgres, SQL Server, MySQL, Oracle (community), SQLite (community); **QuestDB, ksqlDB, Materialize, RisingWave** (streaming/real-time); MongoDB (BI Connector), Druid (community); Parquet/CSV/JSON via DuckDB. Community drivers: ArangoDB, CosmosDB, CrateDB, Dremio, SAP Hana, etc. Multiple simultaneous data sources per deployment; per-user warehouse OAuth passthrough; cross-database rollup joins. + +## 5. Cube Cloud platform + +- **Dev workflow**: browser Data Model IDE (branch dev mode, branch-scoped API endpoints, staging envs), **Visual Modeler** (no-code, Mar 2025), Playground 2.0 (chart prototyping), **Content Validator**, git integrations (GitHub app, GitLab/Bitbucket/SSH), continuous deployment. +- **Deployment types**: Shared (free, dev-only, auto-suspend, 1,000 queries/day, no refresh workers) · Dedicated (2 API instances + refresh worker + 2 Cube Store routers, autoscaling) · **Multi-cluster** (Premium+; up to 10 deployments/100 API instances routed by `context_to_app_id` for >100-tenant multi-tenancy). +- **Infra options**: SaaS; single-tenant dedicated with VPC peering / PrivateLink / Private Service Connect; **BYOC on AWS, Azure, GCP** (data plane in customer account); OIDC workload identity (keyless federation incl. Bedrock). +- **Observability**: Usage Analytics (incl. AI usage), Query History (1-day Free → 7-day Premium → custom Enterprise; export to S3), pre-agg console, Performance Insights, **Audit Log** (Enterprise), **Chats History** (admin view of AI chats), Datadog/Grafana/New Relic/CloudWatch integrations. +- **Auth**: SAML SSO (Google/Entra/Okta) + **SCIM** (Enterprise), LDAP (Feb 2025), roles Admin/Developer/Explorer/Viewer + **custom roles** (Enterprise), user groups/attributes, data access policies, JWT security context for API consumers. SOC 2. +- **Pricing** (Oct 2025 model): Free (5 workbooks, 1k queries/day, limited agent requests) · Starter $40/dev/mo (Dedicated $0.60/hr) · Premium $80/dev/mo + Explorer $40 + Viewer $20 seats, embedded dashboards/chat, 99.95% SLA, multi-cluster $1.20/hr · Enterprise custom (99.99% SLA, BYOC, BYOLLM, SSO/SCIM, custom roles, audit, DAX API, dbt integration). Embedded stays **compute-priced**. AI tokens: per-seat grants + token packages. + +## 6. Embedded analytics + +Four embedding options (expanded as **Embedded Agentic Analytics**, June 11, 2026): +1. **Analytics Chat API** (custom chat UX; agent-to-agent capable) +2. **Chat & Dashboard iframes** (theming, SSO, private + signed auth, postMessage events, localization, per-embed time zones) +3. **Creator Mode** (end customers build their own workbooks/dashboards in-product) +4. **Core Data APIs** (classic headless: JSON/GraphQL/SQL) + +**React Embed SDK** in public preview. White-labeling: app theming (colors/logo/fonts), chart palettes, dashboard themes. Native viz layer: bar/line/area/scatter/pie/heatmap/boxplot/table (pivots, conditional formatting)/KPI (progress, sparklines, rich text)/**maps (point + choropleth)**/custom HTML (Handlebars+JS)/raw Vega-Lite; small multiples, dual axes, reference lines. Flagship embedded customers: **Brex "Spaces"**, Webflow, Deel; claims "thousands of organizations." + +## 7. Open source vs commercial + +- **Cube Core** (github.com/cube-js/cube): **20.7k stars**, ~1.1k open issues, actively developed. Dual **Apache 2.0/MIT** per package. Includes Cube Store, all drivers, Rust CLI, cubesql. LTS program since Oct 2024. +- **In Core**: full modeling (Tesseract, hierarchies/folders, calendar cubes, granularities), access policies, pre-aggregations + Cube Store, SQL/REST/GraphQL APIs, Playground, multi-tenancy primitives, all drivers. +- **Cloud-only**: the entire agentic frontend (chat, workbooks, dashboards, agents, skills, scheduled tasks, evals, Python analysis, MCP server + connectors, Slack agent), Semantic Catalog, Visual Modeler, IDE, Semantic Layer Sync, MDX/DAX, Excel/Sheets add-ins, embed iframe/SDK/Creator Mode, SSO/SCIM/custom roles/audit, managed infra/BYOC. +- HN commentary (2025): "a lot of the work being done has been for the cloud service so some parts of the OSS version are starting to fall behind." + +## 8. Company & market + +- Funding ~**$49M** total: seed (~$6.5M, 2019) → Series A $15.5M (2021, Decibel) → **Series B $25M (June 2024, Databricks Ventures)**. No 2025–2026 round found. **Narrative BI acqui-hire Sept 2025** (founder Michael Rumiantsau → VP Product). Headcount ~72 (2026, third-party estimate); ~$7.9M ARR (Getlatka 2025 estimate, low confidence). +- Scale claims (own PR): 90k server installs, 5M+ users, 20% of Fortune 1000. +- Analyst recognition: #1 Dresner 2025 Semantic Layer study; Leader & Outperformer, GigaOm Radar 2025; **Gartner 2026 Market Guide for Agentic Analytics**; Snowflake OSI founding participant. +- Positions against: dbt Semantic Layer/MetricFlow, AtScale, Looker/LookML ("Open-Source Looker Alternative for the AI Era," Jul 2026), Microsoft SSAS, legacy semantic layers. +- Common criticisms (HN/G2/StackShare): caching complexity in multi-tenant setups; generated SQL "could be better optimized"; docs gaps; OSS lagging Cloud; upgrade regressions; BI integrations "not totally straightforward"; steep initial learning curve; opt-out telemetry. Praise: best-in-class pre-aggregation/aggregate awareness, saves building an analytics API, strong embedded multi-tenant story. + +## 9. Ship cadence mid-2025 → mid-2026 (chronological) + +D3 launch (Jun 2, 2025) → Narrative BI team (Sep 9) → OSI (Sep 23) → native AI/BI frontend manifesto (Oct 1) → **Agentic Analytics GA + seat pricing** (Oct 29) → Core v1.5 (calendar cubes, SQL-over-HTTP, nested folders) (Oct 29) → AI Widget + dashboard iframes + map/KPI/custom-HTML charts (Nov 14) → **Core v1.6** (DataFusion-46 Cube Store, multi-stage pre-aggs, pushdown GA) (Dec 18) → AI-assisted onboarding + stateless Explore + prompt suggestions (Jan 12, 2026) → Gartner recognition (Mar 3) → LLM reliability benchmark (Apr 28) → **Slack Agent** (May 7) → Core/Cloud strategy (May 14) → **Agent Skills** (Jun 2) → **Embedded Agentic Analytics** (Jun 11) → **MCP Connectors** (outbound; Notion/Linear/Sentry/Attio) (Jun 15) → **Cube Evals + AI Studio** (Jun 25) → **Core v1.7: Tesseract GA** (Jul 8) → **Scheduled Tasks** (Jul 9) → **dbt integration** (Jul 16) → **Rust CLI** (Jul 21) → **Python analysis** (Jul 30) → agentic-loops roadmap (Aug 13) → **Claude Connector + open-source `cube-agent-skills`** (9 Claude Code skills, Apache 2.0) (Aug 20). Roughly one substantive launch every two weeks, nearly all AI/agent-centric. + +Announced-not-shipped (Aug 2026 roadmap): agent session environments (sandboxed parallel agents proposing merges), model unit tests/artifact checks, event-triggered background agent loops (dbt changes, dashboard errors, query-history signals), Cube→dbt write-back, in-channel Slack mentions, model-graded evals. + +## 10. AI agent configuration surface (docs, mid-2026) + +Code-first config in `agents/` in the model repo (default since Apr 30, 2026; UI config deprecated): +- `config.yml`: `llm` (default `auto`; pinnable — list includes `claude_4_6_opus`…`claude_5_opus`, `gpt_5_4`, `o3`), `embedding_llm`, `runtime: plain|reasoning`, `accessible_views`, `memory_mode: space|user|disabled`. +- **Rules** (markdown instructions: always + agent-requested), **Certified Queries** (trusted SQL example library), **Skills** (`agents/skills/*.md`, frontmatter + instructions; run via chat buttons, slash menu, or auto-matching; versioned/reviewed like code), **Memories** (tenant/space/user isolation), **Multi-agent** (multiple agents per deployment, each with own model/views/rules), **BYOM** (Enterprise), **MCP Connectors**, **Evals** (`agents/eval_questions.yml`: NL question + ground truth SQL/certified query; sort-invariant, numeric-tolerant result comparison; per-branch runs; CI-gateable; surfaced in AI Studio). +- **Scheduled Tasks** (NL prompt + cadence; runs headless under creator's security context; can query, search web, build/update reports & dashboards, email members; cannot yet edit the model). +- **Python analysis** (sandboxed Python attached to workbook tabs; input = tab's Semantic SQL result; stats/ML libs preinstalled; agent auto-invokes for forecasting/regression/clustering/anomaly asks). diff --git a/audit/cube/rill-feature-inventory.md b/audit/cube/rill-feature-inventory.md new file mode 100644 index 000000000000..a7367775cb27 --- /dev/null +++ b/audit/cube/rill-feature-inventory.md @@ -0,0 +1,88 @@ +# Rill Feature Inventory (current state, Cube-focused) + +> Basis for the Cube vs Rill comparison. Derived from the codebase (this repo, Aug 2026) and docs.rilldata.com. Emphasis on the surfaces where Cube competes: semantic layer, APIs, caching, AI. A broader BI-surface inventory (viz types, dashboards, alerts) lives in [`../omni/rill-feature-inventory.md`](../omni/rill-feature-inventory.md) and still applies. + +## 1. AI features (exhaustive) + +### 1.1 Agent architecture (`runtime/ai/`) + +Multi-agent AI subsystem built into the runtime (`runtime/ai/ai.go`), with typed Go tools implementing MCP-native specs (`modelcontextprotocol/go-sdk`), auto-generated JSON schemas, and per-tool access control (`CheckAccess`) driven by runtime security claims. + +**Agents:** +- **Router Agent** (`router_agent.go`): entrypoint for chat; LLM-routes to candidate agents. +- **Analyst Agent** (`analyst_agent.go`): data Q&A over metrics views; accepts rich context (explore dashboard, canvas + component, dimension/measure allowlists, filters, time + comparison range, `is_report` flag); pre-invokes `get_metrics_view`/`query_metrics_view_summary` for dashboard context. +- **Developer Agent** (`developer_agent.go`): edits the project — 20-iteration tool loop over file tools, SQL tools, bucket introspection, `develop_file`; supports `init_project` (whole-project scaffolding from a prompt). +- **Feedback Agent** (`feedback_agent.go`): records thumbs up/down; on negative feedback runs an LLM **attribution** step (Rill's fault vs project's vs user's, with suggested action) for triage. + +**Worker tools:** `list_metrics_views`, `get_metrics_view`, `get_canvas`, `query_metrics_view_summary` (time range + sample values), `query_metrics_view`, `create_chart` (in-chat charts, `chat_charts` flag), `develop_file` (sub-agent: create/edit/delete one YAML/SQL file, returns post-reconcile status), `list_files`, `search_files`, `read_file`, `write_file`, `project_status`, `query_sql` (raw OLAP SQL), `list_tables`, `show_table`, `list_buckets`, `list_bucket_objects` (S3/GCS discovery), `navigate` (drives the Rill UI). + +Completion loop (`Session.Complete`): multi-iteration tool-calling (default 10, developer 20), context truncation, structured outputs, OTel tracing, token/tool-call telemetry. + +### 1.2 Conversations +Persisted sessions/messages in the per-instance catalog store as a call tree (user input, tool calls/results, thinking). **Sharing** with partial visibility (`SharedUntilMessageID`), **forking** (`ForkSession`), anonymous sessions for public projects. Runtime RPCs: `Complete`, `CompleteStreaming`, `ListConversations`, `GetConversation`, `ShareConversation`, `ForkConversation`, `ListTools`, `GetAIMessage`. + +### 1.3 LLM providers +AI is a connector driver (`drivers.AIService`): **OpenAI** (incl. Azure OpenAI), **Anthropic Claude** (default `claude-opus-4-5`), **Google Gemini**, plus the **admin proxy** (Rill-managed AI: runtime proxies completions through the admin service holding the provider key). BYO model via `ai_connector` in `rill.yaml`; `managedAI` flag distinguishes billable vs BYO tokens. + +### 1.4 Context injection +`ai_instructions` at project level (`rill.yaml`) and metrics-view level, surfaced in MCP responses; `@`-context picker in the chat UI (`web-common/src/features/chat/core/context/`). + +### 1.5 MCP server +- Session-scoped MCP server (`runtime/ai/mcp.go`) exposing exactly the tools the caller's claims permit: metrics tools for readers; file read/**write** tools with edit access. Mounted at `/v1/instances/{id}/mcp` and local `/mcp` (`runtime/server/mcp.go`), stateless streamable HTTP. +- **Full MCP OAuth**: RFC 9728 + RFC 8414 + PKCE + device-code flows (`admin/server/auth/mcp_oauth.go`) so Claude/Cursor/ChatGPT can OAuth into Rill Cloud. MCP connect page in web-admin (`web-admin/src/features/ai/mcp`) and "Connect client" popover in chat. + +### 1.6 Chat surfaces +`web-common/src/features/chat/`: **DashboardChat** (context-aware side pane on explore/canvas — knows current filters/time range), **DeveloperChat** (Rill Developer workspace), **ProjectChat** (full page at `/-/ai` in cloud). Renders thinking, tool calls, in-chat charts, file diffs; "Explain and fix error" button. Feature flags: `chat`, `dashboard_chat`, `developer_chat`, `chat_charts`. + +**AI in embeds:** `GetIFrame` takes `external_user_id` for per-end-user AI chat history inside embedded dashboards; postMessage API can open/close the AI pane. + +### 1.7 AI-powered scheduled reports +Reports support `resolver: ai` (`runtime/reconcilers/report.go`, `runtime/resolvers/ai.go`): a scheduled report runs the Analyst Agent with a prompt + explore/filter context per recipient (respecting their security policies) and emails the generated narrative, linking to a shared AI session. + +### 1.8 AI scaffolding / code generation +`GenerateMetricsViewFile` (AI with non-AI fallback), `GenerateCanvasFile`, developer-agent `init_project`, AI canvas generation and Vega-Lite chart generation in the frontend. + +### 1.9 Instructions for external coding agents +`runtime/ai/instructions/` ships per-resource authoring guides and exports them: `rill init --agent claude|cursor|agentsmd` writes `CLAUDE.md`/`.claude` skills, `.cursor` rules, or `AGENTS.md` + `.mcp.json` pointed at Rill's MCP server. + +### 1.10 AI billing, telemetry, evals +Billable metrics per completion (input/output/cached tokens tagged provider + `managed_ai`; tool-call counts). Internal eval/transcript harness (`runtime/ai/evals/`, ~18 recorded scenarios) — **not customer-facing**. + +### 1.11 Other +CLI `rill chat`; `ai` resolver usable in any `data:` block (AI output as a data source for reports/components). + +## 2. Semantic layer + +- **Metrics views** (`runtime/parser/parse_metrics_view.go`, `MetricsViewSpec` proto): bound to exactly one model/table. Dimensions typed categorical/time/geo, expression or column, unnest, URI, lookup dimensions. Measures: simple, **derived** (`per`/`requires`), **time_comparison**, **window** (partition/order/frame); format presets/d3. Security: templated `access`, row filters, per-field include/exclude with conditions, evaluated against JWT user attributes. `ai_instructions`, watermarks, time-grain controls, rollups (pre-aggregated tables with automatic routing), cache key controls, derived metrics views (`parent:` subset). +- **Query engine** (`runtime/metricsview/`): comparisons (value/delta/ratio), percent-of-total, pivots, spine densification, having, search, annotations; AST → dialect SQL per OLAP engine. **Metrics SQL** dialect (JOINs rejected). Rill time DSL. Column/table profiling APIs. +- **Caching**: in-memory LRU result cache keyed by query + state version (`runtime/query.go`). No pre-aggregation *scheduling/matching* layer comparable to Cube's (Rill's answer is the OLAP engine itself + new metrics-view `rollup:`). +- **Explore spec**: field selection, time ranges + comparison offsets, defaults, theme, security. + +## 3. APIs + +- **Runtime APIs**: gRPC + REST (gRPC-Gateway) — resources, files (+watch), queries (Aggregation, Toplist, Comparison, TimeSeries, Totals, Rows, Search, TimeRanges, Annotations, profiling), git ops (powers cloud editing), AI/conversations. +- **Custom APIs** (`parse_api.go`): YAML endpoints over resolvers (`sql`, `metrics_sql`, `api`, `glob`, `resource_status`, `union`, `text`, `ai`), per-API security, generated **OpenAPI** spec per project. +- **Auth**: admin-issued ephemeral JWTs with granular permissions + user attributes; iframe tokens (`GetIFrame`) with attributes/`external_user_id`/theme/navigation; magic auth tokens (public URLs) with filters + field allowlists. + +## 4. Connectors / OLAP + +Drivers: athena, azure, bigquery, clickhouse, databricks, druid, duckdb (+MotherDuck, DuckLake), file, gcs, https, mysql, pinot, postgres, redshift, s3, salesforce, slack (notifier), snowflake, sqlite, starrocks, supabase + AI drivers (openai, claude, gemini). +- **OLAP engines**: DuckDB (embedded default), ClickHouse (incl. Rill-managed), Druid, Pinot, StarRocks; warehouse-direct OLAP mode documented for BigQuery/Snowflake/Databricks. +- **Models**: SQL models, incremental + partitioned models (state resolvers, partition retry/skip), staging cross-connector flows, data-quality `tests:`, cron refresh, dev/prod templating. + +## 5. Cloud platform + +Orgs/projects, org+project roles, user groups, whitelisted domains, access requests, view-as-user; OIDC SSO (Auth0-pattern), PATs, service accounts; billing = Orb + Stripe (usage-based incl. AI tokens); provisioner (static slots, Kubernetes runtimes, managed ClickHouse); GitHub integration + Rill-managed repos; **branch deployments**; **cloud edit mode** (edit-session with commit/branch/merge); custom domains. + +## 6. Explicit gaps vs Cube (verified absent in codebase) + +- **No SQL API for external BI tools**: no Postgres wire protocol, no JDBC/ODBC. Query surfaces are REST/gRPC, custom APIs, MCP. (Cube's SQL API is its Tableau/PowerBI/Superset/Metabase story.) +- **No GraphQL API.** +- **No pre-aggregation build/match layer**: no equivalent of Cube Store + refresh workers; acceleration is the OLAP engine + in-memory result LRU + metrics-view `rollup:` (early). +- **No Tableau / Power BI / Excel / Looker Studio integrations** (no DAX/MDX/XMLA endpoints, no connector code). +- **No dbt integration** (no manifest/exposure reading). +- **No Kafka/streaming ingestion connector** (Kafka only via ClickHouse per docs). +- **No standalone catalog/discovery product**; discovery = project resource listing + MCP `list_metrics_views`. +- Semantic layer is **YAML-only** (no programmatic Python/JS model definitions like Cube's) and per-project (no cross-project federated semantic graph). + +Key files: `runtime/ai/ai.go`, `runtime/ai/mcp.go`, `admin/server/auth/mcp_oauth.go`, `runtime/metricsview/query.go`, `runtime/parser/parse_metrics_view.go`, `runtime/parser/parse_api.go`, `runtime/reconcilers/report.go`, `runtime/resolvers/ai.go`, `proto/rill/runtime/v1/api.proto`, `admin/billing/`, `admin/provisioner/`. diff --git a/audit/cube/roadmap.md b/audit/cube/roadmap.md new file mode 100644 index 000000000000..d7cefcdcb9eb --- /dev/null +++ b/audit/cube/roadmap.md @@ -0,0 +1,154 @@ +# Roadmap: Competing with (and beating) Cube + +Companion to `comparison.md`. Effort sizes: S (≤1 eng-month), M (1–3), L (3–6), XL (6+ across teams). Items shared with the Omni roadmap (`../omni/roadmap.md`) are marked ♻ — build once, win both fights. + +## 1. Strategic frame + +### Where the fight actually is + +Cube spent 2025–26 converting semantic-layer credibility into "agentic analytics" — and it now owns that category's narrative (coined the term, got the Gartner Market Guide listing, ships an AI/agent feature every ~2 weeks). But its position has three structural cracks Rill is built to exploit: + +1. **Cube has no data plane.** No ingestion, no transformation, no storage. Every un-pre-aggregated query hits the customer's warehouse; its performance answer is pre-aggregations — the single most complained-about surface in Cube's own community (build/refresh complexity, multi-tenant cache headaches, "slow AI analyst" on G2). Rill's managed OLAP makes speed the default, not an engineering project. +2. **Cube's AI platform is 100% Cloud-gated and seat-priced.** MCP requires Premium ($80/dev/mo); BYOM, SSO, DAX are Enterprise; the OSS project explicitly gets none of the agentic frontend (and HN already notices Core "falling behind"). Rill's OSS product is the whole product — local AI chat, write-capable MCP, dashboards — free on a laptop. +3. **Cube is squeezed from above.** Snowflake Semantic Views, Databricks Metric Views, dbt+Fivetran/MetricFlow-OSS, and Looker's Conversational Analytics API all commoditize "semantic layer middleware." Cube must defend the middleware position while pivoting to BI. Rill never depended on that position: its wedge is the full stack (data → OLAP → BI → agents). + +Cube's real strengths to respect: Semantic SQL over Postgres wire (universal interop), joins/multi-fact modeling, the AI operationalization suite (skills/rules/certified queries/evals/AI Studio), embedded breadth (Chat API, Creator Mode), and install-base/analyst mindshare. + +**Positioning: "The agentic BI platform that's fast by default and open all the way down."** Cube grounds agents in a semantic layer over your slow warehouse; Rill grounds agents in a semantic layer over a sub-second OLAP engine it also manages — so both humans *and agents* get instant answers, and agents can *build*, not just ask. Win operational/embedded/event-scale deals outright; achieve sufficient AI-ops and interop parity so Rill stops losing "agentic analytics" evaluations on checklists. + +### The four deal-loss categories to eliminate +1. **"Cube plugs into my existing BI stack; Rill doesn't."** (SQL API, Power BI/Excel, BI sync) +2. **"Cube's agents are tunable, testable, and everywhere; Rill's chat is a black box."** (skills, rules, evals, Slack, outbound tools) +3. **"Rill can't model my schema."** (joins/multi-fact — same as Omni loss #1) +4. **"It's missing enterprise table stakes."** (SCIM, audit logs, BYOC, custom roles) + +### Deliberate non-goals (§7) +Warehouse-agnostic middleware play, 20-engine live-query breadth, DAX/MDX full fidelity, workbook/Python document paradigm, Cube Store-style pre-agg infrastructure. + +--- + +## 2. Phase 1 — AI operationalization parity (0–3 months) — THE PRIORITY + +Cube's biggest genuine lead is that it productized the agent trust/tuning loop. Rill's `runtime/ai/` architecture already contains most of the raw material; this phase is packaging, not research. This is also the phase that feeds the "agentic analytics" evaluation checklists Gartner just legitimized. + +### 2.1 Agent Skills (S–M) ♻ +**Cube:** markdown skills in `agents/skills/` in the repo — chat buttons, slash menu, auto-matching; versioned/reviewed like code; plus an open-source Claude Code skills repo. +**Plan:** Rill is *better* positioned here — projects are already git repos parsed by `runtime/parser`: +- New resource kind `skill` (`skills/*.md` or YAML frontmatter + markdown body): name, description, inputs, instructions. Parser + reconciler are trivial; skills surface as (a) one-click buttons/slash commands in all three chat surfaces (`web-common/src/features/chat/`), (b) **MCP prompts** (the MCP spec has prompts; almost nobody ships them — instant differentiation for Claude/Cursor users), (c) invocable by the router agent via auto-matching. +- Ship a starter skill library in `rill init` templates + docs gallery. +- **Mirror Cube's Aug 2026 move**: publish `rilldata/rill-agent-skills` for Claude Code (explore-metrics, build-model, build-dashboard, deploy, configure-embed…) installable via the plugin marketplace. Rill already ships `rill init --agent claude` (`cli/cmd/initialize/init.go`) — extract + publicize. + +### 2.2 Rules, certified queries, and memories (M) +**Cube:** Rules (always/agent-requested markdown), Certified Queries (admin-approved SQL agents reuse as trusted examples), Memories (space/user isolation), multi-agent config in `agents/config.yml`. +**Plan:** generalize `ai_instructions` into a first-class AI config block (project-level `ai:` in `rill.yaml` + per-metrics-view): +- `rules:` list (markdown files or inline; always vs on-request) injected into agent prompts (`runtime/ai/instructions/` already does templated prompt assembly). +- `certified_queries:` named metrics queries / Metrics SQL with NL descriptions — served to the analyst agent as few-shot examples and exposed via MCP as example resources; doubles as the eval ground truth (§2.3). +- `memory:` opt-in conversation-derived memory per user/project (catalog store already persists sessions; add a distillation step in the completion loop). Scope: user-level only at first; skip Cube's space isolation until multi-agent exists. +- BYO model config already exists (`ai_connector`) — advertise it against Cube's Enterprise-gated BYOM. + +### 2.3 Customer-facing evals, CI-gateable (M) ♻ — highest leverage/effort ratio +**Cube:** `agents/eval_questions.yml` (NL question + ground-truth SQL), sort-invariant numeric-tolerant result comparison, per-branch runs, AI Studio UI. +**Plan:** productize `runtime/ai/evals/`: +- `evals:` resource: prompt + expected result (certified query ref, Metrics SQL, or golden values). Runner executes the real analyst agent against any branch deployment (branch-scoped deployments + MCP already exist) and compares result sets (reuse Cube's tolerant-comparison semantics — they're right). +- Surfaces: `rill ai eval` CLI (CI-gateable — beat Cube to "evals in GitHub Actions" as the default workflow, it fits Rill's git-first story better than their IDE), plus a simple results page in web-admin. +- Marketing: "golden completions, not vibes" is already Rill's blog line — make it a product screenshot and publish accuracy numbers (buyers now cite runQL/Delphi benchmarks; absence of numbers reads as weakness). + +### 2.4 Slack agent (M) ♻ +**Cube:** DM the Cube app; threads = chat sessions; email-matched identity; user's own RLS applies. Premium+. +**Plan:** extend the `slack` driver beyond notifier: Slack app with DM + @mention → router/analyst agent, thread = conversation (persistence exists), email→user mapping → JWT attributes so **security policies apply per asker**, chart images in replies (needs PNG render — §4.3), link back to explore with filters applied. This is the highest-visibility AI demo feature in every 2026 eval; Rill's per-user security story makes its version *more* enterprise-credible than Cube's. + +### 2.5 Scheduled agent tasks, loudly (S) +**Cube:** Scheduled Tasks (NL prompt + cadence, can build dashboards + email members) — shipped Jul 2026 as a headline feature. +**Rill already has this** (`resolver: ai` reports with per-recipient security — ahead of Cube on governance). Gaps to close: let the scheduled agent optionally use developer tools on a branch (create/update a canvas, open a PR — never direct-to-prod), add Slack delivery of narrative + chart, and **name it** ("AI Reports" → productized "Routines/Tasks" page in web-admin). Mostly packaging + docs + a launch post. + +### 2.6 AI admin & usage surface (M) +**Cube:** AI Studio, Chats History (admin), usage analytics incl. AI, per-seat token grants. +**Plan:** web-admin org/project **AI page**: conversations volume, thumbs up/down rates, **feedback-attribution breakdown** (the `feedback_agent` already classifies failures as Rill's/project's/user's fault — no competitor has this; make it a dashboard), token spend per user/embed org, per-org and per-embed AI caps (billing already meters tokens). Admin conversation browser gated by an org setting (privacy-flagged). + +**Phase 1 exit criteria:** In an "agentic analytics" bake-off, Rill demonstrates skills, rules, certified queries, evals-in-CI, Slack agent, scheduled AI tasks, and an AI admin console — while being the only vendor whose agent also *builds* the project and runs free locally. + +--- + +## 3. Phase 2 — Interop & semantic depth (3–6 months) + +### 3.1 Postgres-wire SQL API over metrics views (L) — the big interop bet +**Cube:** Semantic SQL over Postgres protocol is its most-used API and now "the primary API going forward"; it is how Tableau/Metabase/Superset/psql/pandas/every LLM tool connect. +**Plan:** a `pgwire` endpoint on the runtime speaking Postgres protocol, translating to **Metrics SQL** (parser exists: `runtime/metricsview/metricssql/`) with metrics views exposed as tables and measures as `MEASURE()`-style columns (adopt Cube's convention — it's becoming a de-facto standard and eases migration *from* Cube). Read-only, JWT/service-token auth mapped to existing security claims so RLS holds. Scope v1 to the aggregation-query shape Metrics SQL supports; punt full pushdown. +Payoff: every "can my analysts use their existing tools" objection dies; Rill becomes usable as a *semantic layer* by teams not ready to switch BI — Cube's own wedge, reversed. Also instantly makes Rill consumable from any tool that speaks Postgres, including AI notebooks and LLM data tools. + +### 3.2 Semantic joins: shared dimensions → composite metrics views (XL) ♻ +Identical to the Omni roadmap §4.1 (shared/conformed dimensions → composite metrics views stitched by FULL OUTER JOIN post-aggregation → many-to-one dimension-table joins later). Against Cube specifically, the pitch is stronger: Cube joins tables and needs Tesseract machinery to avoid fan-out; Rill joins *after aggregation*, correct by construction. Required to stop losing enterprise-schema deals; also unlocks §3.1's usefulness on real schemas. Includes fiscal/custom calendars (Cube's calendar cubes) as part of the time-model work (S once designed) ♻. + +### 3.3 Excel + Google Sheets, the pragmatic slice (M) +**Cube:** MDX API + native add-ins (Cloud), DAX API (Enterprise). +**Plan:** do NOT build MDX/DAX. Ship (a) **Google Sheets add-on** ("connected metrics": pick metrics view/measures/dims/time range → live-refreshing range; reuse existing REST APIs + OAuth), and (b) **Excel via the Postgres SQL API** (§3.1) with a documented ODBC path + templates. Covers ~80% of "get governed numbers into a spreadsheet" at ~20% of the cost. Power BI stays a documented SQL-API connection, not a DAX endpoint (revisit only on repeated enterprise loss evidence). + +### 3.4 Outbound MCP connectors for Rill agents (M) +**Cube:** agent consumes Notion/Linear/Sentry/Attio + custom MCP tools for context and write-back. +**Plan:** `runtime/ai` already speaks MCP natively (go-sdk) — add client-side support: project-level `ai.connectors:` (remote MCP endpoints + allowed tools + per-user OAuth where needed), tools surfaced to analyst/developer agents behind admin enablement, nothing on by default. The approved external-MCP-connector design on branch `mcp_external` (see memory) is the starting point. Differentiator to market: Rill agents can pull a Linear ticket for context *and* open a PR on your metrics repo — a full loop Cube's model-frozen scheduled tasks can't do. + +### 3.5 dbt read-integration (S–M) +**Cube:** one-way dbt→Cube sync with CI/webhooks, `cube_dbt`. +**Plan:** read dbt `manifest.json`/`semantic_manifest.json`: import models as external tables/sources with lineage + docs; optional MetricFlow-metric → metrics-view conversion (MetricFlow is now Apache 2.0 — legally clean). Positions Rill as complementary to the dbt-standard stack instead of ignoring it. + +### 3.6 Standards & catalog visibility (S, non-eng-heavy) +- **Join OSI / Apache Ossie.** Cube, Omni, Hex, Sigma, ThoughtSpot are members; Rill's absence reads as irrelevance in every analyst deck. Implement OSI import/export for metrics views when the v0.x spec stabilizes; being the "OSI + open source + fast engine" vendor is cheap, on-brand positioning. +- **Model organization metadata** (S): `folder:`/`group:` + synonyms on metrics-view fields ♻ — feeds search, MCP tool descriptions, and any future catalog surface. A full Semantic-Catalog product is deliberately deferred (§7). + +--- + +## 4. Phase 3 — Press the structural advantages (6–12 months) + +### 4.1 Own "fast agentic analytics" with proof (M, ongoing) +- **Publish the benchmark Cube can't**: agent-answer latency + cost on a 1–10B-row event dataset, Rill (managed ClickHouse/DuckDB) vs Cube-over-Snowflake with and without pre-aggs. Include the pre-agg engineering time as a cost line. Cube's G2 complaint ("AI analyst can be a little slow") is the opening; agents make latency *worse* for Cube (multi-query plans × warehouse latency), *better* for Rill. +- **Accuracy benchmark** on the runQL pattern using the §2.3 eval harness, published with methodology. + +### 4.2 Embedded agentic analytics v2 (L) +Cube's embedded suite (Chat API, Creator Mode, React SDK) targets Rill's core commercial wedge; respond on Rill's terms: +- **Chat API** (M): streaming HTTP conversational endpoint (thin productization of `CompleteStreaming`) with embed-token auth (`external_user_id` history + per-user security already work) → customers build fully custom chat UX; also wrappable agent-to-agent. +- **Agent white-labeling** (S): name/avatar/intro/suggested prompts per embed org. +- **Embed creator mode, Rill-shape** (L) ♻: scoped canvas-composition for embed users over allowed metrics views (no SQL, no model editing, RLS always on) — matches Omni roadmap §3.4; sell against Cube's Creator Mode with "governed by construction." +- **React embed SDK** (S–M): typed wrapper over iframe + postMessage APIs; npm package. Cheap, removes a checklist line. +- Keep the pricing story loud: flat $500/mo embedded vs Cube's compute-priced embeds. + +### 4.3 Platform table stakes (M each) ♻ +Same list as Omni roadmap Phase 1/2 — they close Cube checklists too: **SCIM v2 + audit logs + custom-roles review**, **PNG rendering** (prereq for Slack agent charts + email bodies), drill-to-records, maps + reference lines + small multiples in canvas, delivery destinations (webhook/S3/Sheets). Add Cube-specific: **query history / usage analytics surface** for customer admins (Rill has the telemetry; expose it), and evaluate **BYOC** demand before building (single-tenant + VPC peering may suffice; BYOC is XL and only Enterprise-deal-gated). + +### 4.4 Background agent loops — beat Cube to its own roadmap (L) +Cube's Aug 2026 roadmap post telegraphs: sandboxed agent session environments, model unit tests, event-triggered background loops (dbt changes, dashboard errors, query signals). Rill can ship this *first* because the primitives exist: branch deployments = sandboxed environments; the reconciler emits resource-error events = triggers; the developer agent writes files = the actor; PRs = the merge gate. Ship: "on model error / on parse failure / on upstream schema change → developer agent proposes a fix PR (with eval run attached)." This is the "self-healing BI project" demo — a category-defining move that leverages exactly the full-stack + git-first advantages Cube lacks. + +--- + +## 5. GTM moves (parallel, not eng-gated) + +1. **Publish a Rill vs Cube page**: fast-by-default vs pre-agg engineering; open-source-complete vs Cloud-gated AI; agents that build vs agents that ask; flat embedded pricing vs compute-priced; free local MCP vs Premium-gated MCP. Cube ignores Rill publicly — force the comparison where Rill wins. +2. **Cube-migration play** (S eng): importer from Cube YAML models (cubes/views → models + metrics views; joins flagged until §3.2 lands; `MEASURE()` SQL-API compat from §3.1 eases client cutover). Target Cube OSS users watching the AI platform stay Cloud-only, and Cube Cloud customers hit by the Oct 2025 seat-pricing shift. +3. **Ride the squeeze**: for Snowflake/Databricks-committed shops choosing native semantic views, position Rill as the *consumption + agent* layer on top (warehouse-direct OLAP mode + §3.5 dbt read), not competing middleware. Cube must fight the platforms; Rill can partner-position. +4. **Analyst & standards presence**: brief for the next Gartner Agentic Analytics Market Guide cycle and GigaOm semantic-layer radar; join OSI (§3.6); get Rill into the 2027 semantic-layer roundups it's currently absent from. +5. **Keep maxing the ClickHouse/MotherDuck co-marketing lane** — "real-time operational BI for a metered world" is a category Cube structurally can't enter, and ClickHouse's own blog is already selling it. +6. **Lead AI messaging with what's unique**: write-capable agents + per-recipient-security AI reports + failure attribution + evals-in-CI + free local MCP. "Your agents can build in Rill, not just ask." + +--- + +## 6. Sequencing summary + +| Phase | Theme | Items | +|---|---|---| +| 1 (0–3 mo) | AI-ops parity | Skills (+ Claude Code skills repo), rules/certified queries/memories, customer evals + CI, Slack agent, scheduled-tasks packaging, AI admin console | +| 2 (3–6 mo) | Interop & semantics | Postgres-wire Metrics SQL API, joins/composite metrics views (start), Sheets add-on + Excel-via-SQL, outbound MCP connectors, dbt read, OSI membership, field metadata | +| 3 (6–12 mo) | Structural offense | Latency + accuracy benchmarks, embedded chat API/white-label/creator-mode/React SDK, SCIM/audit/PNG/maps/drill ♻, background agent loops ("self-healing BI") | +| GTM (now) | Positioning | vs-Cube page, Cube importer, platform-squeeze partnering, analyst/OSI presence, ClickHouse lane, "agents that build" messaging | + +## 7. Deliberate non-goals (and why) + +| Cube feature | Why we skip it | +|---|---| +| Warehouse-agnostic middleware breadth (20+ live engines, Fabric, per-user warehouse OAuth) | Rill's story is "bring data to a fast engine"; invest connector breadth in *ingestion*. The middleware position is the one being commoditized by Snowflake/Databricks/dbt | +| Cube Store-style pre-aggregation infrastructure | Rill's OLAP engines are the acceleration layer; metrics-view `rollup:` covers the residual need | +| Full DAX/MDX APIs | Multi-year fidelity chase; §3.3's Sheets add-on + Postgres SQL API captures most demand. Revisit on enterprise loss evidence only | +| Workbooks/Python document paradigm | Same stance as vs Omni: ad-hoc calcs in explore (♻ Omni §3.1) + AI chat cover the jobs; a sandboxed-Python *agent tool* for forecasting is a cheaper future add than a document surface | +| Semantic Catalog as a product | Field metadata + search + MCP discovery (§3.6) capture the AI-grounding value; a standalone catalog fights Atlan/Select Star, not Cube | +| GraphQL API | No demand signal; REST/OpenAPI + SQL API suffice | +| Coining a counter-category | Don't fight "agentic analytics" as a term — win it: Gartner blessed the category, Rill should be listed in it | + +**The one-line strategy:** match Cube's AI operationalization fast (Phase 1 — it's packaging work on an agent runtime Rill already has), open the interop doors Cube walks through today (Phase 2 — SQL API, spreadsheets, joins), then press the three advantages Cube cannot copy — a data plane that makes agents fast, an open-source product that includes the whole platform, and agents that build and repair projects instead of only querying them (Phase 3 + GTM). diff --git a/audit/deep-ai-performance.md b/audit/deep-ai-performance.md new file mode 100644 index 000000000000..da8b2fc40a13 --- /dev/null +++ b/audit/deep-ai-performance.md @@ -0,0 +1,112 @@ +# AI Layer (performance & speed vs. direct Claude) — Deep-Dive Audit + +**Focus:** AI response latency — why Rill AI feels slower than running the same analysis directly in Claude | **Scope:** `runtime/ai/*` (orchestration, agents, tools), `runtime/server/chat.go`, `runtime/drivers/{openai,gemini,claude}`, `runtime/drivers/admin/ai.go`, `admin/server/ai.go`, supporting paths (`runtime/connections.go`, `runtime/resolvers/metricsview_summary.go`, `runtime/metricsview/executor/executor_summary.go`, `cli/pkg/local/app.go`, `cli/cmd/admin/start.go`, `web-common/src/features/chat/core/*`) | **Health:** needs-attention + +## Overview + +I traced a user turn end-to-end: SSE handler (`chat.go:464` → `CompleteStreaming:325`) → `router_agent` → `analyst_agent`/`developer_agent` → `Session.Complete` tool loop (`ai.go:1279-1396`) → `drivers.AIService.Complete` (unary) → provider SDK, plus the tool implementations each iteration invokes (metrics queries, summary, file writes). Two hypotheses from the brief are **refuted**: (1) there is **no router-classification LLM call on the web hot path** — all frontends always send an explicit `agent` (`conversation.ts:116,361-365`; developer surfaces pass it via `chat-utils.ts:10`, `generateCanvas.ts:191`), and the router only invokes the LLM when `agent` is empty *and* ≥2 agents pass access checks (`router_agent.go:102-142`); (2) there is **no per-message DB persistence blocking the stream** — messages are flushed once per turn in a deferred `Flush` (`chat.go:366-371`), and the feedback agent only runs on explicit user feedback. + +Where the time actually goes, in order: (a) **the entire LLM path is non-streaming** — all three provider drivers use blocking, full-generation APIs and `drivers.AIService` has no streaming method, so the user sees each LLM response (including the long final answer) only after it is fully generated; (b) **no prompt caching** — the Claude driver never sets `cache_control` (required for Anthropic caching), and the message-truncation marker rewrites the prompt prefix every iteration for long loops, defeating even the automatic caching OpenAI/Gemini provide, while ~55-60 KB of tool schemas + system prompt are re-processed on every one of up to 20 iterations; (c) **everything is serial** — multiple tool calls returned in one LLM response execute one at a time, and context seeding runs 3-6 dependent-free calls sequentially; (d) **the analyst prompt mandates a minimum of 4-6 queries plus a chart after each**, structurally multiplying LLM round-trips versus what direct Claude would choose to do; (e) **managed AI adds a unary WAN proxy hop through the admin service per LLM call** (also for local Rill Developer) and pins deployments to top-tier default models (Claude → Opus 4.5) with no tuning knobs. A typical first analyst turn is 2-4 serial OLAP seed queries + 6-13 serial LLM round-trips (each blocking, each re-processing an uncached, growing prompt) + 5-12 serial OLAP/chart tool executions — commonly 30 s to 3 min of wall clock with long dead-air windows, versus direct Claude which streams tokens immediately, caches the prefix, parallelizes tool calls, and stops when it has enough data. Verification also surfaced one outright bug on the developer path: `develop_file` executes its context-seeding tool calls but drops their results before the LLM sees them due to a wrong parent filter (finding 10). + +## Findings + +### deep-ai-performance-01 [HIGH] No token-level streaming anywhere in the LLM path; the final answer arrives only after full generation +- **Category:** performance **Confidence:** high **Novelty:** new **Must-fix:** no **Location:** `runtime/drivers/ai.go:10-12`, `runtime/drivers/claude/claude.go:295`, `runtime/drivers/openai/openai.go:343`, `runtime/drivers/gemini/gemini.go:318`, `runtime/ai/ai.go:1302-1308`, `runtime/server/chat.go:376-407` +- **Problem:** `drivers.AIService` exposes only a unary `Complete` (`ai.go:10-12`). All three drivers call the blocking, non-streaming provider APIs: Claude `h.client.Beta.Messages.New` (claude.go:295), OpenAI `Chat.Completions.New` (openai.go:343), Gemini `Models.GenerateContent` (gemini.go:318). The client-facing "streaming" (`CompleteStreaming` → SSE) is message-granular: a message is only published via `AddMessage` after a full LLM response has returned (`ai.go:1353-1366` for intermediate text; the final answer is only published as the analyst/router *result* message after the whole loop finishes — the no-tool-call final response breaks the loop at `ai.go:1345-1348` without emitting any progress message). Anthropic's own guidance (and the SDK defaults) is to stream any request with long output/high `max_tokens`; `max_tokens` here is 8192 (claude.go:141). +- **Failure scenario / perf impact:** The final analyst answer ("3-5 key insights" with headers and citations, typically 500-1500+ tokens, worst-case 8192) is the longest generation of the turn — 10-45+ s on Opus-tier models — during which the UI shows nothing new. The same dead-air occurs during every intermediate iteration (2-8 s each). Direct Claude shows first tokens in ~1-2 s. This is the single largest *perceived* latency difference and it compounds with finding 02 (uncached prompt processing extends time-to-first-token of every generation). +- **Recommendation:** Add a streaming variant to `drivers.AIService` (e.g. `CompleteStream(ctx, opts, fn func(delta))`), implement it with the providers' SSE APIs, and forward text deltas through the session subscriber as partial-message events (the SSE plumbing in `chat.go` and the frontend `sse-*` stack already exist). For the managed path this also requires a streaming admin RPC (see finding 05). An incremental first step with most of the win: stream only the *final* (no-tool-call) generation to the client. + +### deep-ai-performance-02 [HIGH] No prompt caching: Claude driver never sets `cache_control`, and truncation rewrites the prompt prefix for all providers; ~55-60 KB of prompt is re-processed every iteration +- **Category:** performance **Confidence:** high **Novelty:** new **Must-fix:** no **Location:** `runtime/drivers/claude/claude.go:317-342` (no `cache_control` anywhere), `claude.go:310` (reads `CacheReadInputTokens`), `runtime/ai/ai.go:1290,1605-1661` (`maybeTruncateMessages`; marker at `:1628`, sliding keep-last window at `:1635-1636`), sizes (measured): `runtime/ai/create_chart.go:418` (24.8 KB description) + `runtime/metricsview/charts_json_schema.go` (~12.6 KB schema), `runtime/metricsview/query.go:496` (11.6 KB schema), `runtime/ai/metrics_view_query.go:40` (~6 KB description), `runtime/ai/instructions/data/development.md` (26.2 KB), `resources/canvas.md` (32.6 KB), `resources/model.md` (23.8 KB) +- **Problem:** Anthropic prompt caching is opt-in via explicit `cache_control` breakpoints (block-level or the top-level parameter); `convertMessages`/`convertTools` set neither, so `usage.cache_read_input_tokens` — which the driver dutifully reports at claude.go:310 — is always 0. Every iteration of a tool loop therefore re-processes the full prompt at full price and full time-to-first-token: for the analyst loop that is the ~8 KB system prompt + ~55 KB of tool definitions (`create_chart` alone contributes ~37 KB; `query_metrics_view` ~18 KB) + the growing history including up-to-100 KB tool results (`maxMessageSizeBytes`, `ai.go:37`), ~15-20 K tokens minimum per iteration before history. Additionally, once a loop exceeds 20 messages, `maybeTruncateMessages` rewrites the prefix on *every* subsequent iteration in two ways: the marker text embeds the changing skipped-count (`"... [%d messages omitted for brevity] ..."`, `ai.go:1628`) at position 5, and — more fundamentally — the kept tail is a *sliding* window (`messages[len-16:]`, `ai.go:1635-1636`), so everything after message 4 changes each iteration regardless of the marker. Since caching is prefix-based, this defeats even OpenAI's and Gemini's automatic caching, which otherwise benefit from the append-only message pattern below 20 messages. +- **Failure scenario / perf impact:** A 10-iteration analyst loop processes on the order of 150-400 K cumulative input tokens with 0% cache hits on Claude (and 0% past 20 messages on all providers). Cached input is roughly an order of magnitude cheaper and substantially faster to prefill; uncached prefill of 20-40 K tokens adds ~1-3 s to every iteration's TTFT on top of generation time. Direct claude.ai caches the system prompt/tools automatically across its agent loop. This is also a direct cost issue for the Rill-managed (billable) connector. +- **Recommendation:** In the Claude driver, set `cache_control` breakpoints on (a) the last tool definition, (b) the last system block, and (c) the last message of the previous turn (max 4 breakpoints; the SDK supports block-level `CacheControl`). Make `maybeTruncateMessages` cache-stable: freeze the marker text (drop the count, or bucket it) *and* truncate at stable boundaries (e.g. drop in chunks so the kept prefix only changes every N iterations) — fixing the marker alone is not sufficient because of the sliding tail window. Verify with the already-collected `cached_input_tokens` metric — it should become non-zero. + +### deep-ai-performance-03 [MEDIUM] Tool calls execute strictly sequentially — both within an LLM response and in agent context seeding +- **Category:** performance **Confidence:** high **Novelty:** new **Must-fix:** no **Location:** `runtime/ai/ai.go:1353-1395` (serial block loop), `runtime/ai/analyst_agent.go:111-161` (serial seeding), `runtime/metricsview/executor/executor_summary.go:91-112` (serial per-time-dimension `Timestamps` queries), `runtime/ai/develop_file.go:92-107` and `runtime/ai/developer_agent.go:60-77` (serial pre-invokes) +- **Problem:** (1) When the model returns multiple `tool_use` blocks in one response — which the Claude driver explicitly permits by using `ToolChoice: auto` without `disable_parallel_tool_use` (claude.go:276-280) — the completion loop executes them one at a time via blocking `CallToolWithOptions` (`ai.go:1367-1391`). Each `query_metrics_view` is an OLAP round-trip taking 0.1-5 s (2-minute timeout, `metrics_view_query.go:260`). (2) The analyst agent's first-turn seeding runs `get_canvas` → per-metrics-view `query_metrics_view_summary` → `get_metrics_view` strictly serially (`analyst_agent.go:111-152`); a canvas with 3 metrics views is 7 sequential calls before the first LLM token. (3) Inside each summary, `e.Timestamps` runs once per time dimension (≤2) sequentially before the combined dimension query (`executor_summary.go:91-112`) — up to 3 serial OLAP queries per summary. (4) `develop_file` and `developer_agent` pre-invoke `list_files` → `project_status` → `read_file` serially. +- **Failure scenario / perf impact:** A model that batches 3 queries (as Claude does natively when tools are independent) pays 3× OLAP latency serially instead of ~1×. Canvas seeding with 3 metrics views at ~0.5-2 s per summary adds 2-6 s of serial pre-LLM latency. Direct Claude executes independent tool calls concurrently (the documented pattern is to run parallel `tool_use` blocks concurrently and return all results in one message). +- **Recommendation:** Execute the `tool_use` blocks of a single LLM response concurrently (errgroup; append results in block order to keep the transcript deterministic — note `AddMessage` is already mutex-guarded). Parallelize the analyst seeding fan-out per metrics view, and the two `Timestamps` calls inside `Summary`. Keep dependent sequences (parser wait → status) serial. + +### deep-ai-performance-04 [MEDIUM] The analyst prompt mandates a 4-6-query minimum plus a chart after every query — a structural round-trip multiplier +- **Category:** performance **Confidence:** high **Novelty:** new **Must-fix:** no **Location:** `runtime/ai/analyst_agent.go:357-358` ("Execute a MINIMUM of 4-6 distinct analytical queries... Some analyses may require up to 20 queries"), `:400-414` ("After running `query_metrics_view` create a chart using `create_chart` unless...", gated on the `chat_charts` feature flag), `:198` (`MaxIterations: 20`) +- **Problem:** Each mandated query is one full LLM round-trip (blocking, uncached — findings 01/02) plus one OLAP query; the chart-per-query rule roughly doubles the tool-call count (each `create_chart` is cheap to execute but costs another LLM iteration to emit). A simple question ("what was revenue last week?") that direct Claude over the same MCP tools would answer with 1-2 queries is steered into 4-6+ queries and 4-6 charts, i.e. typically 8-13 LLM iterations. With ~3-8 s per iteration (generation + uncached prefill) and ~0.1-5 s per OLAP query, the floor for any analyst turn is tens of seconds regardless of question complexity. +- **Failure scenario / perf impact:** This is the main *structural* reason a Rill analyst turn takes minutes where claude.ai takes 15-30 s: the loop count is prompt-forced, and every extra iteration compounds the per-iteration costs from findings 01-03. It is a deliberate quality/latency trade-off, but it is currently unconditional — trivial questions pay the full research protocol. +- **Recommendation:** Make query depth adaptive: instruct the model to scale query count to question complexity (e.g. "answer directly when one query suffices; use the full OODA protocol for open-ended analysis"), or split into a fast path (single-question) and a deep-analysis path (report mode keeps the 4-6 minimum). Allow charts to be emitted in the same iteration as the query they visualize (parallel tool calls, finding 03) so the chart rule stops doubling iterations. + +### deep-ai-performance-05 [MEDIUM] Managed AI routes every LLM call through a unary admin-service proxy (also from local Rill Developer) and pins deployments to top-tier default models with no tuning knobs +- **Category:** performance **Confidence:** high **Novelty:** new **Must-fix:** no **Location:** `runtime/drivers/admin/ai.go:11-37`, `admin/server/ai.go:19-87`, `cli/pkg/local/app.go:281-293,324` (local AI connector = `admin`), `cli/cmd/admin/start.go:246-284` (api-key-only config), `runtime/drivers/claude/claude.go:134` (default `claude-opus-4-5-20251101`), `runtime/drivers/openai/openai.go:168` (default `gpt-5.2`) +- **Problem:** With the default (Rill-managed) AI connector — which is also what local Rill Developer uses (`app.go:281-293`: the `admin` connector pointed at Rill's cloud admin URL) — every LLM call in a 10-20-iteration loop travels runtime → admin service (WAN, unary gRPC `admin.Complete`) → provider, and back. The unary hop (a) adds a WAN round-trip plus admin-side marshalling per call (the full message history is re-serialized over the wire every iteration — tens to hundreds of KB by late iterations), and (b) makes token streaming impossible end-to-end until the admin RPC becomes a stream (blocks finding 01 for all managed deployments). Separately, the admin bootstrap passes *only* `api_key` to the driver (`start.go:250-264`), so managed deployments are pinned to driver defaults: Claude → **Opus-tier** (`claude-opus-4-5`, the slowest model class, claude.go:134), OpenAI → `gpt-5.2` with no `reasoning_effort` set, Gemini → `gemini-3-flash-preview`; no model, max-tokens, effort, or speed configuration is reachable from deployment config. +- **Failure scenario / perf impact:** 10 iterations × (1 extra WAN RTT + admin processing) adds seconds per turn even before provider time; running a 10-20-iteration *tool loop* on an Opus-tier model (vs. e.g. a Sonnet/Haiku-tier model for intermediate iterations) multiplies per-iteration generation time 2-4×. Direct claude.ai users choose their model and talk to the API with one hop. +- **Recommendation:** Add model/max-tokens/effort passthrough to the admin AI config (env + per-org override), default the agent loop to a faster model tier (optionally escalating for the final synthesis), and add a streaming `Complete` RPC to the admin proto so the proxy stops blocking finding 01. Longer term, consider issuing scoped provider credentials to runtimes so the proxy hop is only on the billing/audit path, not the data path. + +### deep-ai-performance-06 [MEDIUM] `write_file` blocks on a full-project reconcile (plus a fixed 500 ms sleep) on every write +- **Category:** performance **Confidence:** high **Novelty:** new **Must-fix:** no **Location:** `runtime/ai/file_write.go:117-152` (`Reconcile` at `:123`, fixed sleep at `:128-132`, `WaitUntilIdle` at `:149`) +- **Problem:** Every `write_file` in the developer/develop_file loops forces a project-parser reconcile, sleeps a hard-coded 500 ms, then calls `ctrl.WaitUntilIdle(ctx, true)` — which waits for **all** resources in the instance to finish reconciling, not just the resources declared in the written file. (The `// TODO: Only if not streaming` at `:123` shows this is known to be unrefined.) Writing a small YAML file therefore waits on any unrelated in-flight work (e.g. a big model materialization triggered earlier in the same loop or by the user), and writing a model file waits for its full materialization — potentially minutes for a large source — before the LLM gets its tool result and can proceed. +- **Failure scenario / perf impact:** A multi-file developer task ("add a source + model + metrics view + dashboard") issues 4+ writes; each pays parser reconcile + 500 ms + whole-DAG idle. If step 2 kicked off a slow ingest, steps 3-4's writes stall behind it even when they don't depend on it. This is the dominant latency term for the developer agent on real projects, ahead of LLM time. +- **Recommendation:** Wait only on the resources declared in the written file (and their upstream refs), e.g. via `ctrl.List(ctx, "", path)` + targeted waits, instead of global `WaitUntilIdle`; replace the fixed 500 ms sleep with an event-driven wait on the parser resource version; and consider returning early with "reconciliation in progress" plus letting the model poll `project_status` (which already supports `wait_until_idle`) only when it needs confirmation. + +### deep-ai-performance-10 [MEDIUM] `develop_file` seeds its sub-agent with `FilterByParent(s.ID())` — a filter that can never match — so the pre-invoked discovery results are executed but silently dropped from the LLM context +- **Category:** bug **Confidence:** high **Novelty:** new (found during adversarial verification; root-causes part of finding 07) **Must-fix:** no **Location:** `runtime/ai/develop_file.go:115` (the bug), `runtime/ai/developer_agent.go:83` (the correct pattern: `FilterByParent(s.ParentID)`), supporting trace: `runtime/ai/ai.go:210-212` (root session `ParentID` is `""`), `ai.go:881` (`AddMessage` sets `ParentID: s.ParentID`), `ai.go:971` (`WithParent(callMsg.ID)` — the only `WithParent` call site, always a *message* ID) +- **Problem:** `develop_file.Handler` pre-invokes `list_files`, `project_status`, and `read_file(path)` (`develop_file.go:92-107`) and then tries to seed their results into the sub-agent's messages via `s.MessagesWithResults(FilterByParent(s.ID()))` (`:115`). `s.ID()` is the **AI session UUID** (`BaseSession.ID()`), but message `ParentID`s are only ever `""` (root) or *message* UUIDs — no code path ever sets a message's parent to the session ID (verified across all `ParentID` assignments and both `FilterByParent` producers). The filter therefore always returns an empty set, and the sub-agent's LLM receives only `[system instructions, resource instructions?, user prompt]` — no file listing, no project status, and crucially **not the current content of the file it is asked to edit**, despite the tool's own arg contract ("assuming no prior context except the path's current content and status", `develop_file.go:25`). The sibling `developer_agent.go:83` uses the correct `FilterByParent(s.ParentID)` (the current call's message ID), which is what this line was evidently meant to be. +- **Failure scenario / perf impact:** Every `develop_file` invocation (a) wastes 3 serial pre-invoked tool executions whose results reach the UI transcript but not the model, and (b) starts the sub-loop blind, so the model must spend 1-3 extra LLM round-trips (at ~3-8 s each, uncached per finding 02) re-fetching the listing/status/content it was supposed to already have — or, worse, writes an existing file without having read it, risking a blind overwrite whose damage only shows up in the returned diff. This has existed since the file was introduced (`fbe8bf575`, Jan 2026). +- **Recommendation:** Change `:115` to `FilterByParent(s.ParentID)` (matching `developer_agent.go:83`); add a mock-LLM test asserting the sub-agent's first completion request contains the `read_file` result for the target path (there is currently no test covering the seeded messages). + +### deep-ai-performance-07 [LOW] `develop_file` sub-agent cold-starts per file: re-loads 26-59 KB of instructions, repeats the parent's discovery calls, and multiplies LLM iterations +- **Category:** performance **Confidence:** high **Novelty:** expands-existing (latency dimension of ai-11's nested-loop fan-out) **Must-fix:** no **Location:** `runtime/ai/develop_file.go:64-84,92-115,131`, `runtime/ai/developer_agent.go:60-77,99-102` +- **Problem:** Each `develop_file` call is an isolated sub-agent ("no prior context from the conversation", develop_file.go:36): it re-sends the 26 KB `development.md` plus up to 32.6 KB of resource-specific instructions as a fresh system prompt, and re-runs `list_files` + `project_status` + `read_file` serially (`:92-107`) even though the parent developer agent pre-invoked `list_files` + `project_status` at the start of the same turn (`developer_agent.go:60-77`). Worse, due to finding 10 those re-runs are then *discarded* before the LLM ever sees them. Each sub-loop is up to 10 more LLM iterations (min ~2), nested inside the parent's 20. A 4-file task ⇒ 4 × (fresh ~7-15 K-token system prompt with no cache reuse (finding 02) + 3 duplicate-and-dropped discovery calls + 2-10 LLM iterations + reconcile-blocked writes (finding 06)). +- **Failure scenario / perf impact:** "Build me a dashboard from this S3 bucket" routinely runs 15-40 total LLM calls across parent and sub-loops. The isolation design is defensible for context hygiene, but the duplicated discovery and uncached repeated instruction prompts are pure overhead. +- **Recommendation:** First fix finding 10 so the pre-invoked results actually reach the sub-agent; then pass the parent's fresh `list_files`/`project_status` results into the sub-agent's seed messages instead of re-invoking; with finding 02's cache breakpoints, the static instruction files become cache hits across sub-agent calls in the same session (same prefix), which removes most of the token-processing cost. + +### deep-ai-performance-08 [LOW] Agent-loop progress is coupled to client drain rate via the unbuffered subscriber hand-off under the session lock +- **Category:** performance **Confidence:** medium **Novelty:** expands-existing (perf angle of ai-02 / MUST-FIX D "AI subscriber send under the session lock") **Must-fix:** no **Location:** `runtime/ai/ai.go:656-661,893-900`, `runtime/server/chat.go:385-406` +- **Problem:** `AddMessage` performs a blocking send on the unbuffered subscriber channel while holding `s.mu`. Beyond the cancellation-hang already tracked in MUST-FIX D, this serializes the *producer* (agent loop) with the *consumer*: the reader goroutine performs `messageToPB` + `stream.Send` between receives, so the next `AddMessage` blocks (under the session mutex) until the previous message has been fully serialized and flushed to a possibly slow client connection. Tool execution and LLM-response processing pause for the duration. +- **Failure scenario / perf impact:** On a slow or high-latency client link (SSE over poor networks, large tool-result messages up to 100 KB), each message hand-off adds the client's per-message serialize+write time to the agent loop's critical path — turning a network-bound consumer into an agent-loop bottleneck. Mitigating factor (why confidence stays medium on magnitude, though the mechanism is certain): kernel socket buffers absorb small frames, so real producer stalls need either large messages or a genuinely stalled client with full buffers. Impact is negligible on localhost, real on slow WANs with chatty loops (30+ messages per turn). +- **Recommendation:** The fix for MUST-FIX D (buffered per-subscriber channels with non-blocking send, or notifying outside the critical section) also removes this backpressure; prefer a small buffered channel (e.g. 64) + drop-oldest/track-lag semantics so the producer never waits on the client. + +### deep-ai-performance-09 [LOW] Refutation: no router-classification LLM call and no feedback-agent call on the normal web turn +- **Category:** performance **Confidence:** high **Novelty:** new **Must-fix:** no **Location:** `web-common/src/features/chat/core/conversation.ts:116,361-365`, `web-common/src/features/chat/core/conversation-manager.ts:137-141,186-190`, `runtime/ai/router_agent.go:102-142`, `runtime/ai/feedback_agent.go:68-94` +- **Problem (negative finding):** The brief hypothesized a router LLM classification before every turn and a separate feedback-agent call. Traced end-to-end: every frontend surface constructs conversations with an explicit agent (`Conversation` defaults to `analyst_agent`; editor/canvas/sample-data surfaces pass `developer_agent`), and `startStreaming` always sends `agent` in the request body — so the router takes the `args.Agent != ""` branch and performs zero LLM calls (its overhead is title derivation and two in-memory access checks). The LLM "Agent choice" call only fires for API/MCP-adjacent callers that omit `agent` while both agents are accessible (requires `EditRepo` + `developer_agent` flag). The feedback agent runs only on explicit thumbs-down (one extra structured completion at that moment), never on normal turns. +- **Failure scenario / perf impact:** None on the web hot path. Worth documenting so orchestration-overhead work targets the real contributors (findings 01-05). One residual: external API callers who omit `agent` in Rill Developer do pay one extra serial LLM round-trip (~1-3 s) per turn, and the choice call re-sends the whole root-level conversation history (`router_agent.go:118-120`). +- **Recommendation:** No action needed for the web path. For API callers, document that passing `agent` skips a model call; consider a cheap heuristic pre-route (or a fast/small model) for the choice call. + +## Performance Notes — ranked latency contributors for a typical analyst turn + +Hot path measured/derived from code (first turn on an explore dashboard, managed AI): + +| # | Contributor | Rough cost per turn | Fix | +|---|---|---|---| +| 1 | No token streaming (finding 01): each of N LLM responses invisible until complete; final answer is the longest | dead-air = full generation time of every iteration; final answer 10-45 s invisible | streaming driver API + partial-message SSE events | +| 2 | Zero prompt caching on Claude + truncation-marker cache-bust on all providers (finding 02) | ~15-40 K uncached input tokens **per iteration**; ~1-3 s extra TTFT per iteration; ~150-400 K cumulative tokens per 10-iteration turn | `cache_control` breakpoints; cache-stable truncation | +| 3 | Prompt-forced query volume: ≥4-6 queries + chart each (finding 04) | 8-13 LLM iterations where 2-4 would answer; ×(row 1 + row 2) | adaptive depth; fast path for simple questions | +| 4 | Serial tool execution + serial seeding (finding 03) | 3-7 sequential OLAP calls before first LLM call (canvas); K× serial OLAP latency for K batched tool calls per iteration | parallelize independent calls | +| 5 | Managed-AI unary proxy + Opus-tier default model (finding 05) | +1 WAN RTT and full-history re-serialization per LLM call; 2-4× generation time from model tier | model config passthrough; streaming admin RPC; faster tier for loop iterations | +| 6 | Developer path: `write_file` full-project reconcile + 500 ms sleep (finding 06) | 0.5 s minimum to minutes per write; ×writes per task | targeted waits on declared resources | +| 7 | `develop_file` sub-agent cold start (finding 07) | +3 duplicate discovery calls + fresh 7-15 K-token system prompt + 2-10 iterations per file | seed with parent context; rely on cache after finding 02 | +| 8 | Subscriber hand-off backpressure (finding 08) | per-message client flush time inserted into agent loop; negligible on LAN | buffered subscriber channels | +| 9 | `develop_file` seeding dropped (finding 10) | 3 wasted pre-invoked tool calls + 1-3 extra LLM iterations per `develop_file` call | one-line filter fix (`s.ParentID`) | +| 10 | LLM timeouts/retries (note) | `AILLMTimeoutSeconds` = 4 min bounds each call (`ai.go:1302`, SDK retries occur *inside* that window); a single flaky call can stall an iteration up to 4 min, and the turn is capped at the 10-min `AICompletionTimeoutSeconds` budget (`registry.go:218-219`) | cap SDK retries; add per-iteration deadline budget | + +Not contributors (verified): router classification and feedback agent on web turns (finding 09); per-message DB writes during streaming (single deferred `Flush`, `chat.go:366-371`); LLM handle acquisition (`AcquireHandle` is cached per instance+connector, `connections.go:102-126`); `Instance`/`InstanceConfig`/`FeatureFlags` lookups (in-memory, `registry.go:47-59`, `feature_flags.go:16-27`); `query_metrics_view_summary` is bounded (≤2 serial `Timestamps` queries + 1 combined aggregate over a 24 h sample window, `executor_summary.go:91-183`; `Timestamps` is additionally memoized per executor and skips the OLAP probe entirely when `data_time_range` is declared, `executor.go:178,193-198`); `create_chart` executes locally with no LLM or OLAP call; resolver-level query caching (`Runtime.Resolve`) amortizes repeated seed queries across turns (subject to MUST-FIX A.1's cache-key fix). + +## Notes & Missing Test Coverage + +- **No latency instrumentation asserts the breakdown.** Spans exist per tool call (`ai.Session.Call`) and debug logs per iteration, but there is no per-turn summary metric splitting LLM time vs. tool time vs. serialization — add `llm_duration_ms`/`tool_duration_ms` attributes to the existing `ai_completion` activity event to make regressions in the above table observable. +- **`cached_input_tokens` is already emitted** (`ai.go:1272-1274`) — after implementing finding 02, an eval/CI assertion that cache reads are non-zero on iteration ≥2 would lock the behavior in. +- **No test covers `maybeTruncateMessages` prefix stability** (the cache-bust in finding 02); a table-driven test asserting byte-identical prefixes across consecutive truncations would prevent regressions once fixed. +- **No test covers parallel-tool-execution ordering** (needed before implementing finding 03: assert transcript order is deterministic when tool handlers finish out of order). +- **Evals (`runtime/ai/evals`) measure quality, not latency**; consider recording iteration counts per eval scenario to catch prompt changes that inflate loop length (finding 04). +- **No test covers the sub-agent seed messages** (finding 10 would have been caught by a mock-LLM assertion that `develop_file`'s first completion request contains the pre-invoked `read_file`/`list_files`/`project_status` results; `runtime/ai/developer_agent_test.go` only asserts routing and args). +- Prior-audit cross-references: finding 08 expands ai-02 (MUST-FIX D); finding 07 expands ai-11 and is partially root-caused by finding 10; ai-12's stale-seeding issue also has a perf silver lining (seeding is skipped on later turns) that any fix should preserve by deduplicating rather than always re-seeding. + +## Verification Notes + +Adversarial re-verification pass (2026-07-20): every cited file/line was re-opened and traced; no finding was removed (`removed_count = 0`). All 9 original findings were **confirmed in code**. Changes made: + +- **Confirmed unchanged (locations spot-verified end-to-end):** 01 (`drivers/ai.go:10-12` unary-only interface; blocking `Beta.Messages.New` claude.go:295, `Chat.Completions.New` openai.go:343, `Models.GenerateContent` gemini.go:318; no-tool-call response breaks the loop at ai.go:1345-1348 without a progress message; subscriber streaming is message-granular, chat.go:376-407); 03 (serial block loop ai.go:1353-1395; serial seeding analyst_agent.go:111-161 — canvas with 3 metrics views = exactly 7 serial calls; `ToolChoice` auto without `DisableParallelToolUse` claude.go:275-280; 2-min OLAP timeout metrics_view_query.go:260); 04 (prompt text verified verbatim at analyst_agent.go:357-358 and 402); 05 (unary `admin.Complete` proxy drivers/admin/ai.go:21-25 re-sends full history; admin/server/ai.go:19-87 unary; local Developer pins AI to the cloud admin connector app.go:281-293,324; admin bootstrap passes only `api_key` start.go:246-284; defaults Opus-4.5 claude.go:134, GPT-5.2 openai.go:168, gemini-3-flash-preview gemini.go:155); 06 (`Reconcile` file_write.go:123 with the `TODO`, fixed 500 ms sleep :128-132, `WaitUntilIdle` :149 confirmed global via controller.go:395-419 `idleWaits`); 07; 09 (frontend always sends `agent`: conversation.ts:116,363-365, conversation-manager.ts:137-141,186-190; router LLM branch only when `args.Agent == ""` and ≥2 candidates, router_agent.go:102-142; feedback agent only on explicit feedback, one structured completion for negative sentiment, feedback_agent.go:68-94). +- **Finding 02 — sizes corrected and analysis strengthened, severity unchanged:** measured `createChartDescription` = 24,802 bytes via go/types constant evaluation (prior text said ~26 KB) plus 12.7 KB `ChartsJSONSchema`; `metrics_view_query` description is 6,211 bytes (prior said ~5 KB); `metricsview/query.go:496` schema is 11,626 bytes (as claimed); instruction files 26,184 / 32,632 / 23,781 bytes (as claimed). Added the deeper cache-bust root cause: past 20 messages the kept tail is a *sliding* window (`ai.go:1635-1636`), so the prefix churns every iteration even if the marker text were frozen — the recommendation was updated to require stable truncation boundaries, not just a frozen marker. +- **Finding 04 —** location tightened (`MaxIterations: 20` is at `analyst_agent.go:198`) and noted the chart rule is gated on the `chat_charts` feature flag (it is on the default web path, so impact stands). +- **Finding 08 —** added the socket-buffer mitigating factor to justify the medium confidence on magnitude (the blocking mechanism itself — unbuffered `Subscribe` ai.go:656-661, send under `s.mu` ai.go:893-900, consumer doing `messageToPB`+`stream.Send` between receives chat.go:385-406 — is certain). +- **Performance-notes table row on timeouts corrected:** the previous "~12 min stall" figure was impossible — each LLM call runs under a 4-min `llmCtx` (ai.go:1302, SDK retries occur inside it) and the whole turn under the 10-min `AICompletionTimeoutSeconds` ctx (chat.go:337), so worst case is 4 min per iteration within a 10-min turn cap. +- **Added finding 10 (new, found while verifying 07):** `develop_file.go:115` seeds the sub-agent with `MessagesWithResults(FilterByParent(s.ID()))`, but `s.ID()` is the session UUID and message `ParentID`s are only ever `""` or message UUIDs (`ai.go:210-212,881,971`), so the filter never matches and the pre-invoked `list_files`/`project_status`/`read_file` results are silently dropped — the sub-agent starts blind, contradicting the tool's own arg contract, wasting 3 serial tool calls and forcing 1-3 extra LLM iterations per file. The correct pattern (`FilterByParent(s.ParentID)`) exists at `developer_agent.go:83`. Present since the file's introduction (`fbe8bf575`). +- **Must-fix flags:** all remain `false` — every item here is a performance/product-quality gap or a medium-severity bug, not a data-integrity/security/crash blocker; nothing meets the high/critical + high-confidence bar for the ship-blocker list. diff --git a/audit/deep-audit-canvas.md b/audit/deep-audit-canvas.md new file mode 100644 index 000000000000..bb1ed06a7f65 --- /dev/null +++ b/audit/deep-audit-canvas.md @@ -0,0 +1,279 @@ +# Deep Audit: Canvas Dashboards + +Scope: `web-common/src/features/canvas` in its entirety — components (KPI, charts, pivot, markdown), `layout-util.ts`, stores (`canvas-entity`, `time-state`, `filter-state`, `filter-manager`, `grid`), state-managers, filters, inspector, `selector.ts`, and `variables-store.ts`. Method: a multi-lens find phase (correctness, state, memory, performance) followed by an adversarial verify phase in which every candidate was traced end to end in code — and where feasible reproduced with executable tests — before being accepted; severities were adjusted where verification narrowed or widened the blast radius. + +## Summary + +| ID | Title | Severity | Category | Verdict | +|----|-------|----------|----------|---------| +| CANV-1 | `timeAndFilterStore` leaks a new inner subscription on every dependency change | high | memory-leak | CONFIRMED | +| CANV-2 | Move-with-`insertRow` flags the wrong row as touched, resetting widths of an untouched row in YAML | high | correctness | CONFIRMED | +| CANV-3 | `metricsViewName` never updates on `metrics_view` change, binding component filters/time to the wrong view | medium | correctness | CONFIRMED | +| CANV-4 | Time-range resolution requests re-issued for every metrics view on every spec emission | medium | performance | CONFIRMED | +| CANV-5 | Module-level `lastKey` shared across all pivot instances resets pagination | medium | state | CONFIRMED | +| CANV-6 | Async `TimeState.interval` has no stale-response guard; older request overwrites newer interval | medium | state | CONFIRMED | +| CANV-7 | In-list flag not removed on conversion to Select: `filter(...)` result discarded | medium | correctness | CONFIRMED | +| CANV-8 | FilterManager UI-filter stores leak inner subscriptions on each rebuild | medium | memory-leak | CONFIRMED | +| CANV-9 | FilterManager leaked subscriptions rerun `convertToUIFilters` per past mount (companion to CANV-8) | medium | memory-leak | CONFIRMED | +| CANV-10 | `clearDefaultFilters` throws when the YAML has no `defaults` key | medium | correctness | CONFIRMED | +| CANV-11 | Exponential O(2^n) metrics-view combination map rebuilt on every spec emission | medium | performance | CONFIRMED | +| CANV-12 | Unconditional `specStore.set` on every spec emission rebuilds every chart's query pipeline | medium | performance | CONFIRMED | +| CANV-13 | Markdown templated-string query store leaks inner subscriptions and fresh `timeAndFilterStore` chains | medium | memory-leak | CONFIRMED | +| CANV-14 | `Grid.updateFromCanvasRows` sets row stores unconditionally, making its own diff dead code | low | performance | CONFIRMED | + +--- + +## CANV-1: `timeAndFilterStore` leaks a new inner subscription on every dependency change + +**File:** `web-common/src/features/canvas/components/BaseCanvasComponent.ts:364` · **Severity:** high · **Verdict:** CONFIRMED + +In BaseCanvasComponent's `timeAndFilterStore` getter, the outer derived over 17 stores executes `derived([mvFilters.parsed], ...).subscribe(set)` (line 364) inside its callback, discarding the unsubscriber and returning no cleanup function. Every emission of any dependency (time-range change, filter change, spec reconcile) while the store is subscribed permanently adds one subscription to the session-lived `FilterState.parsed` writable; one-shot `get(this.timeAndFilterStore)` calls in BaseChart/ComboChart/custom-chart leak one subscription each as well. Leaked closures capture that run's timeRange/comparisonTimeRange/canvasData, so on each subsequent `parsed` emission all accumulated stale closures fire in order, pushing a synchronous burst of stale time windows through `set` to downstream consumers (pivot, charts, KPIs) before the final correct value. Subscriptions are never released — not on outer-store teardown, component destroy, or unmount — so memory and per-interaction CPU grow without bound until the canvas page is left. + +**Manual reproduction:** +1. Run `rill start` on a project with a canvas dashboard containing several components backed by a metrics view, and open the canvas in Chrome. +2. Interact once with a dimension filter (add any filter pill) so that `FilterState` exists for the metrics view and the leaking code path (the `mvFilters` branch) is active. +3. Open Chrome DevTools > Memory and take a heap snapshot. Filter the snapshot for closures; note the baseline count of closures retaining `ParsedFilters` / `V1TimeRange` contexts. +4. Change the global time range (or toggle time comparison / edit a filter) 30-50 times. Each change re-runs the outer derived callback for every subscribed component, adding one undisposed subscription to `FilterState.parsed` per component per change. +5. Take a second heap snapshot and compare: the closure count from step 3 grows roughly by (number of canvas components x number of interactions) and is never reclaimed, even after forcing GC. +6. To observe the stale-value burst: open DevTools > Network (filter on metrics-view query endpoints), then add or remove one dimension filter. Observe a burst of extra query requests/invalidation churn whose size grows with the number of prior time-range interactions, because each accumulated stale closure pushes an outdated time window through the store before the final correct value. +7. DevTools > Performance: record while toggling a filter early in the session and again after many interactions; scripting time per toggle grows steadily, confirming the per-interaction CPU cost increase until page reload. + +**Suggested fix:** Capture the inner unsubscriber and return it from the outer derived callback (Svelte invokes the returned cleanup before each re-run and on teardown), or restructure to a single flat `derived` that includes `mvFilters.parsed`. + +--- + +## CANV-2: Move-with-`insertRow` flags the wrong row as touched, resetting widths of an untouched row in YAML + +**File:** `web-common/src/features/canvas/layout-util.ts:239` · **Severity:** high · **Verdict:** CONFIRMED + +In `generateArrayRearrangeFunction`'s `move` case, `insertRow` splices a new row into `newArray` but the parallel `touchedRows` array is not spliced, so the subsequent `touchedRows[source.row] = true; touchedRows[rowIndex] = true` (lines 239-240) uses pre-splice indices against post-splice positions whenever the destination row is at or above the source row (any drag of a component into a new row above its current row). The final `cleaned.map(..., cleanedTouched[index])` then applies the touched flag to the wrong rows: the YAML row updater resets item widths (`COLUMN_COUNT / items.length`) on an untouched row, destroying user-configured widths there, while the actual source row keeps its stale widths, which no longer sum to 12; render-time `normalizeSizeArray` silently evens the source row out, so the rendered layout diverges from the persisted YAML. The move of the item itself is unaffected because `sourceRow` is captured by reference before the splice. Verification reproduced the misalignment with an executable vitest spec exercising the exact UI-dispatched operation; the only existing spec covering `insertRow` is an `add` operation, which does not hit the misalignment. + +**Manual reproduction:** +1. In Rill Developer, create a canvas dashboard with two rows: row 1 containing two components (e.g. two KPI grids) and row 2 containing two components (e.g. two charts). +2. In the canvas editor, drag the column divider in row 1 so its components have unequal widths (e.g. 3 and 9), and do the same in row 2 (e.g. 4 and 8). Open the YAML and confirm the widths 3/9 and 4/8 are persisted. +3. Drag the first component of row 2 and drop it on the horizontal drop-zone divider at the very top of the canvas (above row 1), creating a new row. +4. Inspect the YAML: the previously-untouched row 1 has had its item widths reset to 6 and 6 (user-set 3/9 lost), while the old row 2's remaining component still has width 8, so that row's widths sum to 8 instead of 12. +5. Observe that the canvas still renders the old row 2's remaining component at full width (`normalizeSizeArray` evens out any row not summing to 12), so the rendered layout no longer matches the persisted YAML; committing the file records the corrupted widths. + +**Suggested fix:** Splice `touchedRows` in lockstep with `newArray` whenever `insertRow` inserts a row (`touchedRows.splice(rowIndex, 0, false)`) before assigning the source/destination flags, using the post-splice source index (`source.row + 1` when `source.row >= rowIndex`). + +--- + +## CANV-3: `metricsViewName` never updates on `metrics_view` change, binding component filters/time to the wrong view + +**File:** `web-common/src/features/canvas/components/BaseCanvasComponent.ts:97` · **Severity:** medium · **Verdict:** CONFIRMED + +`BaseCanvasComponent.metricsViewName` is assigned only in the constructor (line 97) and never refreshed in `update()` (lines 172-181), while `CanvasEntity.processRows` (canvas-entity.ts:756) reuses the existing instance whenever the renderer type is unchanged (`areSameType` compares types only). When a user switches a component's metrics view in the inspector (`MetricSelectorDropdown` → `updateProperty("metrics_view", ...)`), the instance keeps the old name, so: (1) `timeAndFilterStore` fetches `hasTimeSeries` and the global filter state (`mvFilters`) for the OLD metrics view (lines 227-229) while validating them against the NEW view's dimensions/measures (lines 286-289), so the `where` clause sent with the component's queries (consumed by KPIProvider, charts, pivot, etc.) reflects the old view's filter map; (2) `localFilters` (FilterState) and `localTimeControls` (TimeState) remain keyed to the old view, so subsequently added widget-level filters resolve against the old view's dimension/measure maps and `hasTimeSeries` checks the wrong view; (3) `inputParams()` implementations that read `this.metricsViewName` (e.g. kpi-grid) show or hide time-series options incorrectly. Concrete failure: switch a KPI from mv_a to mv_b, then add a global filter on a dimension that exists only in mv_b — the KPI silently ignores it until a full page reload. Scope-limiting factors: filters on dimensions shared by both views coincidentally work (they land in both FilterStates), and the stale binding is confined to the live editing session (a reload reconstructs components correctly), so deployed-dashboard viewers are not affected. + +**Manual reproduction:** +1. In Rill Developer, create a project with two metrics views, mv_a and mv_b, where mv_b has a dimension (e.g. `country`) that does NOT exist in mv_a. +2. Create a canvas dashboard with two components: a KPI (or chart) bound to mv_a, and another component bound to mv_b. +3. Open the canvas, select the mv_a component, and in the inspector sidebar switch its "Metrics view" dropdown from mv_a to mv_b. The component re-renders with mv_b measures (spec-driven parts update, masking the bug). +4. In the canvas filter bar, add a global dimension filter on `country` (the dimension that exists only in mv_b) and select a value that excludes most rows. +5. Observe: the other mv_b component's numbers change to reflect the filter, but the switched component's numbers do NOT change. In DevTools Network tab, its metrics-view aggregation request carries no `where` condition for `country`. +6. Reload the page: the switched component now respects the filter and its numbers change — confirming the stale binding existed only for the pre-reload session. +7. Alternate observation (hasTimeSeries path): make mv_a have no time dimension and mv_b have one, then switch a KPI from mv_a to mv_b; the Sparkline / Time range display options in the inspector remain hidden (stale hasTimeSeries) until reload. + +**Suggested fix:** Recompute `this.metricsViewName` (and recreate/re-key `localFilters` and `localTimeControls`) in `update()` and in the spec-store subscription when `spec.metrics_view` differs from the cached name, or read the metrics view name from the current spec inside `timeAndFilterStore` instead of caching it. + +--- + +## CANV-4: Time-range resolution requests re-issued for every metrics view on every spec emission + +**File:** `web-common/src/features/canvas/stores/time-state.ts:158` · **Severity:** medium · **Verdict:** CONFIRMED + +The canvas global (and per-component local) TimeState `interval` derived store re-issues `queryServiceMetricsViewTimeRanges` network requests for every referenced metrics view whenever the canvas spec store emits, even when nothing relevant changed. Both of its upstream stores are unconditionally reset on every `processSpec`: canvas-entity.ts:332 sets `_metricsViews` without an equality guard (Svelte writables always notify for object values), and time-manager.ts `checkIfHasTimeSeries` builds and sets fresh Maps each call — so `processSpec` triggers the interval derivation twice per run. `processSpec` itself runs on every spec-store emission (including isFetching flips with unchanged data), and every Canvas resource reconcile event refetches the `resolveCanvas` query (resource-invalidators.ts:188-194), so each YAML-edit reconcile or upstream refresh produces a burst of duplicate MetricsViewTimeRanges requests (one-plus per metrics view). `fetchTimeRanges` uses `staleTime: 60` (60 ms, likely meant 60 s) and `deriveInterval` sets `cacheBust` whenever the range contains "now" (invalidating the cache before fetching), so these re-runs are real network/OLAP round-trips rather than cache hits. The new Interval object identity also propagates through `timeAndFilterStore`, causing Svelte recompute/render churn in all components — though downstream chart data queries are value-keyed and deduped by TanStack, so there is no chart-data refetch storm and no correctness impact. + +**Manual reproduction:** +1. In Rill Developer, open a project with a canvas dashboard that references 2 or more metrics views with time dimensions (e.g. add a chart from each metrics view), with a default time range set (e.g. `defaults: time_range: P7D`). +2. Open the canvas file in the editor so the split code/preview view is showing. +3. Open browser DevTools > Network and filter requests by "time-ranges" (the MetricsViewTimeRanges query endpoint); note the baseline request count after the page settles. +4. Make a trivial, time-unrelated edit to the canvas YAML (e.g. change `display_name` by one character) and wait for the save/reconcile to complete. +5. Observe a burst of new MetricsViewTimeRanges requests, at least one per referenced metrics view, even though the time range, timezone, and metrics view list are unchanged. +6. Repeat the edit several times: each reconcile produces the same duplicate burst. With a time range containing "now", the cacheBust path invalidates the query cache first, so duplicates fire even when re-runs land within the 60 ms staleTime window. +7. Optional: trigger a refresh of an upstream source/model the canvas depends on and observe the same duplicate burst without touching the canvas file, confirming it fires on any spec emission, not just edits. + +**Suggested fix:** Guard the store writes with equality checks (skip `_metricsViews.set`/`hasTimeSeriesMap.set` when contents are unchanged, as the neighboring `checkAndSet*` helpers already do), and/or short-circuit the interval derived when (range, metricsViewNames, timeZone) are unchanged from the previous run. Revisit `staleTime: 60` (likely meant 60_000). + +--- + +## CANV-5: Module-level `lastKey` shared across all pivot instances resets pagination + +**File:** `web-common/src/features/canvas/components/pivot/util.ts:88` · **Severity:** medium · **Verdict:** CONFIRMED + +The module-level singleton `let lastKey` (line 88) is shared by all canvas pivot/table component instances, but `processPivot`/`processFlat` use it to detect "config changed, reset pagination" per component. Since `getPivotConfigKey` excludes `rowPage` and each `PivotCanvasComponent` has its own config-derived store, any recompute of component B stores keyB in the shared variable; the next recompute of component A (including the recompute triggered by A's own infinite-scroll `rowPage` increment) sees `lastKey !== keyA` and resets A's `rowPage` to 1, discarding loaded pages and re-issuing page-1 aggregation queries. On any canvas with two or more table/pivot components, alternating scrolls between them (or any shared specStore/timeAndFilterStore emission) makes it impossible to keep both components paged past page 1. The explore counterpart (dashboards/pivot/pivot-data-config.ts) uses the same module-level pattern but is safe in practice because explore mounts one pivot at a time; the pattern became a bug when copied to canvas where many pivots coexist. + +**Manual reproduction:** +1. In Rill Developer, open or create a canvas dashboard containing two table (or pivot) components, A and B, with different column sets, each backed by a metrics view whose dimension has more distinct rows than one page (more than ~50 rows so infinite scroll triggers additional pages). +2. Open the browser DevTools network tab and filter for metrics-view aggregation requests. +3. Scroll table A to the bottom so it fetches its next page: additional rows append and a new aggregation request is issued. +4. Scroll table B to the bottom so it fetches its next page (this stores B's config key in the shared module-level variable). +5. Return to table A and scroll to the bottom again to load its next page. +6. Observe the bug: instead of appending the next page, table A snaps back to page 1 — its scroll position and previously loaded rows reset, and the network tab shows the page-1 aggregation queries for A re-issued. Alternating between the two tables reproduces the reset every time. + +**Suggested fix:** Move the key tracking into per-component state: store `lastKey` on `PivotCanvasComponent` (or close over it inside `createPivotConfig`) instead of at module scope. + +--- + +## CANV-6: Async `TimeState.interval` has no stale-response guard; older request overwrites newer interval + +**File:** `web-common/src/features/canvas/stores/time-state.ts:199` · **Severity:** medium · **Verdict:** CONFIRMED + +The async `interval` derived (lines 142-209) launches `Promise.all(metricsViewsWithTimeSeries.map((mvName) => deriveInterval(range, client, mvName, timeZone)))` and calls `set(latestInterval)` plus `this.minMaxTimeStamps.set(...)` in `.then()` with no cancellation, sequence token, or cleanup. `deriveInterval` performs a real network fetch via `queryClient.fetchQuery` with `staleTime: 60` ms, so consecutive invocations (user changes time range or timezone) race, and TanStack's in-flight request deduplication makes out-of-order resolution deterministic when switching A → B → A quickly (the third invocation joins A's earlier in-flight request, so B's request resolves last and its stale result overwrites the store). The result: `rangeStore` shows the new range in the time pill while `interval` — which `BaseCanvasComponent.timeAndFilterStore` uses to build the `timeRange` for every component data query — holds the superseded window, and `canPanStore`/`minMaxTimeStamps` are computed against stale values. The wrong state persists until the next input change re-triggers the derived. + +**Manual reproduction:** +1. In Rill Developer, open a project with a canvas dashboard whose metrics view has a time dimension, and open the canvas in preview mode. +2. Open browser DevTools, go to the Network tab, and set throttling to "Slow 3G" so that MetricsViewTimeRanges requests take multiple seconds. +3. Using the global time range pill, quickly select three ranges in succession, ending on the first one, e.g. "Last 24 hours" -> "Last 7 days" -> "Last 24 hours", completing all three clicks before the first request finishes (TanStack dedup makes the third selection reuse the first in-flight request, so the "Last 7 days" response resolves last and wins). +4. Wait for all MetricsViewTimeRanges requests to settle. The time pill shows "Last 24 hours", but inspect the subsequent component data requests in the Network tab: their timeRange start/end span 7 days, and charts render the 7-day window. +5. Optionally verify the pan arrows: with the mismatched state, the left/right pan availability (`canPanStore`) is computed against the stale interval rather than the displayed range. +6. Change any time input (range, grain, or timezone) once more and let it settle: the state self-corrects, confirming the stale write was from the superseded async batch. + +**Suggested fix:** Guard with a monotonically increasing token (`const myToken = ++this.intervalToken; ... if (myToken !== this.intervalToken) return;`) or return a cleanup from the derived callback that sets a cancelled flag. + +--- + +## CANV-7: In-list flag not removed on conversion to Select: `filter(...)` result discarded + +**File:** `web-common/src/features/canvas/stores/filter-state.ts:309` · **Severity:** medium · **Verdict:** CONFIRMED + +In `toggleDimensionValueSelections` (line 309), when an existing in-list filter is converted to a Select filter, the code calls `dimensionsWithInListFilter.filter((d) => d !== dimensionName)` and discards the result, so the dimension is never removed from the in-list flag array (the sibling action `applyDimensionInListMode` correctly mutates the same array with `push`). The immediately following `getFilterParam` call therefore serializes the newly created IN expression back into the URL with `IN LIST` syntax (converters.ts lines 113-117), and the URL round-trip re-parse (`convertFilterParamToExpression` → `getDimensionFilterItemsMap` line 593) marks the pill as `DimensionFilterMode.InList` again. The user sees a "Converted filter type to Select" toast, and the filter's values are replaced with the clicked value(s), but the pill silently stays in In-List mode; query results are still correct, so the impact is a persistent UI/URL state mismatch rather than wrong data. + +**Manual reproduction:** +1. Start Rill Developer with a project that has a canvas dashboard containing a leaderboard component backed by a metrics view with a string dimension. +2. Open the canvas dashboard. +3. In the filter bar, add a filter pill for that dimension, open the pill dropdown, switch its mode to "In list", and paste two or more values, then apply. Confirm the URL filter param now reads ` IN LIST ('a','b')`. +4. In the leaderboard component, click one of the dimension's values to select it. +5. Observe the toast "Converted filter type to Select" appears. +6. Check the browser URL: the filter param still uses `IN LIST (...)` syntax instead of `IN (...)`. +7. Reopen the filter pill dropdown: the pill is still in "In list" mode, not "Select", contradicting the toast; the value list has been replaced with just the clicked value. + +**Suggested fix:** Mutate in place: `const idx = dimensionsWithInListFilter.indexOf(dimensionName); if (idx !== -1) dimensionsWithInListFilter.splice(idx, 1);`. + +--- + +## CANV-8: FilterManager UI-filter stores leak inner subscriptions on each rebuild + +**File:** `web-common/src/features/canvas/stores/filter-manager.ts:178` · **Severity:** medium · **Verdict:** CONFIRMED + +`activeUIFiltersStore` (line ~178), `defaultUIFiltersStore` (line ~141), and `filterMapStore` (line ~196) all follow the pattern `derived([this.metricsViewFilters], ([...], set) => { derived([...stores]).subscribe(set); })` with the inner unsubscriber discarded and no cleanup function returned, so Svelte cannot dispose the inner subscription when the outer callback re-runs or when the outer store loses its last subscriber. A new inner subscription chain is leaked (a) each time `updateConfig` registers a metrics view not seen before (`StoreOfStores.set` replaces the Map, re-running the outer callback) and (b) each time a component mounts and takes the outer store from 0 to 1 subscribers (CanvasFilters.svelte subscribes to both `activeUIFiltersStore` and `filterMapStore`). The inner deriveds subscribe to always-live writables on the FilterManager, which is owned by the registry-cached CanvasEntity whose `dispose()` never tears down the FilterManager, so chains accumulate for the session lifetime of the cached canvas entity. Each leaked chain re-runs the nontrivial `convertToUIFilters` on every pinned/temporary/filter change (CPU cost grows with each mount cycle), and after a spec update adds a metrics view, the older chain (missing the new view's `parsed` store) fires first and synchronously emits a `UIFilters` value computed without the new view's filters before the newer chain corrects it, which synchronous downstream deriveds (canvas pivot `whereFilterStore`, chat context) can observe. The leak is bounded per FilterManager (the cycle is GC-able once the entity is evicted and unreferenced) but unbounded across mount cycles while the entity remains cached. See CANV-9 for the recomputation-cost profile of the same defect. + +**Manual reproduction:** +1. Run Rill Developer on a project with a canvas dashboard that has filters enabled (filter bar visible) and at least one pinned or active filter. +2. Open the canvas dashboard, then navigate away (e.g. to a model or the project home) and back to the canvas 10-15 times; each visit mounts CanvasFilters.svelte and leaks one inner subscription chain per store. +3. In browser DevTools, set a breakpoint (or a logpoint counting invocations) inside `FilterManager.convertToUIFilters` in filter-manager.ts, then toggle a filter pin or add a temporary filter once. +4. Observe `convertToUIFilters` executes once per leaked chain plus one (roughly N+1 times for N revisits) for a single user action; the count grows by one with every additional visit to the canvas. +5. For the stale-emission variant: with the filter bar mounted, edit the canvas YAML to add a component referencing a metrics view not previously used on the canvas; after reconcile, add a subscriber log on `activeUIFiltersStore` and change a pinned filter: the store synchronously emits an intermediate `UIFilters` value missing the new metrics view's filters before emitting the corrected value. +6. Memory observation: take a heap snapshot before and after 20 navigation cycles on the same canvas and compare retained closure counts referencing FilterManager/`convertToUIFilters`; they grow linearly with visits while the canvas entity stays cached. + +**Suggested fix:** Return the inner unsubscriber from the outer derived callback so Svelte disposes it on re-run and on teardown. + +--- + +## CANV-9: FilterManager leaked subscriptions rerun `convertToUIFilters` per past mount (companion to CANV-8) + +**File:** `web-common/src/features/canvas/stores/filter-manager.ts:141` · **Severity:** medium · **Verdict:** CONFIRMED + +Companion finding to CANV-8, verified independently with a focus on the recomputation cost. The three UI-filter stores (`defaultUIFiltersStore` line 141, `activeUIFiltersStore` line 178, `filterMapStore` line 196) end their outer derived callback with `).subscribe(set);` and return nothing. Because Svelte derived stores are lazy, the outer callback re-runs on every first-subscriber transition — i.e. every SPA navigation into the canvas page — and also whenever `StoreOfStores.set` notifies (new metrics view added via `updateConfig`/`processSpec`). Each re-run creates a fresh inner subscription while the previous one stays permanently attached to the FilterManager's writable stores (pinned/temporary/required keys, allMeasures/allDimensions, each `FilterState.parsed`). The FilterManager lives for the whole browser session: CanvasEntity is cached in `canvasRegistry` (`removeCanvasStore` has no callers) and `CanvasEntity.dispose()` does not tear down FilterManager stores. After N visits to a canvas, a single filter interaction runs `convertToUIFilters` N+1 times — each a full pass over all merged measures and dimensions plus two sorts whose comparator rebuilds `Array.from(temporaryFilterKeys.keys())` per comparison — and each leaked closure calls `set`, triggering N+1 downstream notifications and filter-bar re-renders. Notification order means the final value is still correct (newest subscription fires last), so this is a growing CPU/memory leak rather than a correctness bug. + +**Manual reproduction:** +1. Start Rill Developer (`rill start`) on a project containing a canvas dashboard backed by at least one metrics view with filters enabled (a pinned filter and a few dimension filters make the effect easier to see). +2. Open the canvas dashboard in the browser, then open Chrome DevTools > Sources and set a logpoint with `console.count('convertToUIFilters')` at the top of `convertToUIFilters` in filter-manager.ts (line ~402). +3. Click a filter pill's pin toggle once and note the number of hits (baseline, typically 1-2 per triggering store). +4. Using in-app SPA navigation (not a full page reload), navigate away from the canvas and back. Repeat 10-20 times. +5. Toggle the same filter pin again and count hits: it now fires roughly once per prior visit for a single click (N+1 executions), confirming the accumulated leaked inner subscriptions. +6. Memory side: in DevTools > Memory, take a heap snapshot, navigate in/out of the canvas 10 more times, take a second snapshot, and compare — the retained-closure count for subscribers attached to `pinnedFilterKeysStore`/`temporaryFilterKeysStore` grows linearly with visits and is never released. +7. Optional user-visible symptom: with many accumulated visits on a canvas with many measures/dimensions, filter pill interactions become measurably slower (record a Performance profile while clicking a pill and observe repeated `convertToUIFilters` frames). + +**Suggested fix:** Return the inner unsubscriber from each outer derived callback (`return derived(...).subscribe(set);`) so Svelte tears the previous inner subscription down on re-run and on last-unsubscribe. + +--- + +## CANV-10: `clearDefaultFilters` throws when the YAML has no `defaults` key + +**File:** `web-common/src/features/canvas/stores/canvas-entity.ts:498` · **Severity:** medium · **Verdict:** CONFIRMED + +In `clearDefaultFilters` (line 498), `yaml.get("defaults").items.length` is evaluated outside any try/catch. When the canvas YAML has no `defaults:` mapping (the state of every newly created canvas) or `defaults:` is empty/null, `yaml.get("defaults")` returns undefined/null and the property access throws an uncaught `TypeError: Cannot read properties of undefined (reading 'items')`, aborting the function before the trailing `yaml.delete("filters")` and `updateEditorContent` run. The preceding `deleteIn` calls are inside a try/catch (and do throw "Expected YAML collection at defaults" when the key is missing, which is swallowed), but that catch does not cover line 498. The button is one click away: the inspector's always-visible "Defaults" tab (CanvasTabs.svelte via PageEditor.svelte:268) unconditionally renders DefaultFilterDisplay.svelte, whose "Clear default filters" button calls `clearDefaultFilters` directly. Net effect: an uncaught exception in the click handler, and if the file has a top-level `filters:` block (pinned/required) but no `defaults:`, that block is silently never removed. Verified empirically against the repo's installed yaml v2.8.3. + +**Manual reproduction:** +1. Start Rill Developer (`rill start`) on a project and create a new canvas dashboard (or open any canvas whose YAML has no `defaults:` block). +2. Open the canvas in the visual editor and select the canvas page settings so the right-hand "Canvas configurations" inspector is visible. +3. Click the "Defaults" tab in the inspector header. +4. Open the browser DevTools console. +5. Click the "Clear default filters" button at the bottom of the panel. +6. Observe an uncaught `TypeError: Cannot read properties of undefined (reading 'items')` in the console originating from `clearDefaultFilters` in canvas-entity.ts; the YAML file content is not updated. +7. To observe the silent data-loss variant: hand-edit the canvas YAML to add a top-level `filters:` block (e.g. `filters:\n pinned:\n - some_dimension`) while keeping no `defaults:` block, then repeat steps 3-5 and observe the `filters:` block remains in the file even though the clear action should have removed it. + +**Suggested fix:** Guard the access: `const defaults = yaml.get("defaults"); if (isMap(defaults) && defaults.items.length === 0) { ... }`, mirroring the `isMap`/`instanceof YAMLMap` check already used in `saveDefaultFilters` (lines 440-443). + +--- + +## CANV-11: Exponential O(2^n) metrics-view combination map rebuilt on every spec emission + +**File:** `web-common/src/features/canvas/stores/filter-manager.ts:1063` · **Severity:** medium · **Verdict:** CONFIRMED + +`FilterManager.updateConfig` ends by calling `createDimensionsForUniqueCombinationsOfMetricsViews`, which invokes `getAllCombinations` (line 1063) to enumerate every non-empty subset of the canvas's referenced metrics views (2^n − 1 subsets, each `structuredClone`'d) and builds a merged dimension Map per subset. `updateConfig` is invoked by `CanvasEntity.processSpec` on every specStore emission (canvas-entity.ts:551-559 subscribes with no equality guard beyond a first-load skip), and canvas resource write events force a ResolveCanvas refetch (resource-invalidators.ts:189-195), so the full exponential rebuild reruns on every canvas reconcile/save even when metrics views are unchanged. Only keys corresponding to the distinct metrics-view groups produced by `mergeFilters` are ever looked up in `convertToUIFilters` (lines 453/472), so all but a linear number of the 2^n entries are dead weight. Cost is negligible for typical canvases (1-5 metrics views) but grows to hundreds of thousands of Map insertions at ~15 metrics views and multi-second main-thread freezes plus large memory growth at ~20. + +**Manual reproduction:** +1. In a Rill Developer project, create one model and 16 metrics views over it (copy one metrics view YAML 16 times with distinct names, each with ~10 dimensions). +2. Create a canvas dashboard with one KPI or chart component per metrics view so all 16 metrics views are referenced by the canvas. +3. Open the canvas preview in the browser and open Chrome DevTools > Performance; start recording. +4. Edit the canvas YAML (e.g., change `display_name`) and save; each save reconciles the Canvas resource, which refetches ResolveCanvas and reruns `FilterManager.updateConfig`. +5. Stop the recording and inspect the flame chart: observe a long main-thread task inside `createDimensionsForUniqueCombinationsOfMetricsViews` / `getAllCombinations` / `structuredClone` (65,535 subsets at 16 metrics views), repeated on every save and on query status flips. +6. Optionally scale to 20 metrics views (~1M subsets): the tab visibly freezes for seconds on every reconcile, and the DevTools Memory panel shows a large heap jump from the ~1M-entry Map of dimension arrays. + +**Suggested fix:** Compute dimension arrays only for the metrics-view groupings that actually occur (the distinct `mvNames` sets produced by `mergeFilters`), instead of all 2^n subsets, and skip the rebuild entirely when the metrics-view specs are unchanged since the last `updateConfig`. + +--- + +## CANV-12: Unconditional `specStore.set` on every spec emission rebuilds every chart's query pipeline + +**File:** `web-common/src/features/canvas/components/BaseCanvasComponent.ts:180` · **Severity:** medium · **Verdict:** CONFIRMED + +`CanvasEntity.acquire()` (canvas-entity.ts:551-559) calls `processSpec(data)` on every emission of the canvas-level TanStack query store with no data-changed guard, and query result objects are new on every observer notification (refetch, invalidation, isFetching toggles). `processRows` then calls `existingClass.update(newResource, path)` for every component on the canvas (canvas-entity.ts:757), and `BaseCanvasComponent.update()` (lines 172-181) unconditionally calls `this.resource.set(resource)` and `this.specStore.set(yamlSpec)`. Svelte's `writable.set` uses `safe_not_equal`, which returns true for any object value even when the reference is identical, so every subscriber of every component's `specStore` is notified on every canvas spec emission regardless of whether that component's spec changed. This has two per-component costs: (1) the constructor subscription (lines 157-165) re-runs `onFilterStringChange` and `onUrlChange`; (2) in CanvasChart.svelte, `$: chartSpec = $specStore` dirties `$: chartData = getChartDataForCanvas(...)`, which calls `component.createChartDataQuery(...)` — each provider constructs fresh derived stores and multiple new `createQuery` observers (topN X, topN color, main aggregation), and the `$chartData` auto-subscription swap destroys the old QueryObservers and mounts new ones for every chart on every emission. Mitigations that bound the impact: the TanStack cache dedupes actual network fetches for identical query keys, and emissions occur per debounced file-save/reconcile/refetch rather than literally per keystroke — so the cost is main-thread observer/derived-chain churn and re-renders proportional to chart count, visible as jank on large canvases during editing or frequent reconciles, not redundant network traffic. + +**Manual reproduction:** +1. In Rill Developer, open or create a project with a canvas dashboard containing many chart components (10 or more charts across several rows) backed by a metrics view. +2. Open the canvas file so the visual canvas preview is rendered, and open the browser DevTools Performance panel. +3. (Optional, clearest signal) Add a temporary `console.count(component.id)` at the top of `getChartDataForCanvas` in web-common/src/features/canvas/components/charts/selector.ts and run the dev frontend. +4. Start a Performance recording, then make a trivial edit that only affects one component — e.g. change one chart's `title` in the canvas YAML — and let autosave/reconcile complete. Repeat the edit a few times. +5. Stop the recording. Observe that on every save/reconcile, `getChartDataForCanvas` / `createChartDataQuery` runs once for every chart on the canvas (the console.count increments for all N charts, not just the edited one), and the flame chart shows a long task per emission spent constructing derived stores and TanStack QueryObservers. +6. On a canvas with many charts, this is user-visible as main-thread jank (dropped frames, sluggish typing in the split-view YAML editor) during rapid edits. Refocusing the browser window (which triggers a query refetch returning identical data) reproduces the same full rebuild without any edit at all. + +**Suggested fix:** In `update()`, skip `specStore.set` when the new `yamlSpec` reference (or a cheap deep-equal / JSON string) matches the current value, and likewise for `resource`. Alternatively make CanvasChart derive its query from the store directly instead of re-invoking `getChartDataForCanvas` on each spec object emission. + +--- + +## CANV-13: Markdown templated-string query store leaks inner subscriptions and fresh `timeAndFilterStore` chains + +**File:** `web-common/src/features/canvas/components/markdown/util.ts:194` · **Severity:** medium · **Verdict:** CONFIRMED + +`getResolveTemplatedStringQueryOptions` (lines 135-196) nests a derived inside the async-form callback of an outer derived and calls `.subscribe(set)` while discarding the unsubscriber and returning nothing, so Svelte never cleans up the inner subscription. Every run of the outer callback — once per Markdown component mount (the outer store is created and subscribed per mount in Markdown.svelte) and once per emission of `filterManager.metricsViewFilters` (which emits when a new metrics view's filter store is registered) — permanently leaks a live pipeline. Each run also invokes the `component.timeAndFilterStore` getter (BaseCanvasComponent.ts:184), which constructs and subscribes an entirely new 17-source derived chain whose sources live as long as the canvas, so leaked pipelines are retained indefinitely and keep recomputing `buildRequestBody` (serializing all parsed metrics-view filters) and building query options on every subsequent time or filter change. In a session that repeatedly remounts templated markdown tiles (dashboard navigation, edit/preview toggles), CPU work per filter/time change grows linearly and old spec/filter objects are retained until page reload. (Note: the dominant leak vector is component remounts, not steady-state reconciles — `metricsViewFilters` emits only when a new metrics view's FilterState is first registered.) + +**Manual reproduction:** +1. In Rill Developer, create a canvas dashboard containing a markdown component whose content uses templating syntax (e.g. `{{ ... }}` referencing a metrics view measure) alongside at least one metrics-view-backed component so filters and time controls are active. +2. Open the canvas dashboard in the browser and open Chrome DevTools. In the Sources tab, add a logpoint (or `console.count('buildRequestBody')`) inside `buildRequestBody` in web-common/src/features/canvas/components/markdown/util.ts. +3. Change the global time range once and note the number of `buildRequestBody` invocations (baseline: 1 per markdown tile). +4. Remount the markdown component about 10 times by navigating away from the canvas and back (or toggling between the canvas edit and preview views). +5. Change the global time range or a dimension filter once more: observe `buildRequestBody` now fires roughly once per past mount (10+ times) for a single user action, and the count keeps growing with every additional remount. +6. Memory retention: in DevTools > Memory, take a heap snapshot, perform 10 more remount cycles, take a second snapshot, and compare — closures referencing the markdown util derived callback and TimeAndFilterStore chains accumulate and are never released until a full page reload. + +**Suggested fix:** Return the inner unsubscriber from the outer callback (`return derived(...).subscribe(set);`) and hoist `component.timeAndFilterStore` to a single memoized store created once per component. + +--- + +## CANV-14: `Grid.updateFromCanvasRows` sets row stores unconditionally, making its own diff dead code + +**File:** `web-common/src/features/canvas/stores/grid.ts:101` · **Severity:** low · **Verdict:** CONFIRMED + +In `Grid.updateFromCanvasRows` (grid.ts:98-115), `row.items` and `row.widths` are set unconditionally at lines 101-102 before the changed-check at lines 104-109, making the diff guard dead code: since Svelte writables always notify on `set` with a fresh array, every row store in the top-level grid and in every tab group emits new array identities on every `processSpec` run (which fires on every specStore emission, including reconcile-driven refetches with unchanged data). Additionally, `widths` is set twice per call with inconsistent fallback defaults (25 at line 102 vs `COLUMN_COUNT / length` at line 112). Each emission causes a wasted invalidate-and-flush of every `StaticCanvasRow`/`EditableCanvasRow` component (re-running `normalizeSizeArray`, the grid-template string rebuild, and keyed-each diffing). Because the each blocks are keyed by column index and Svelte batches the synchronous sets into one flush, no components remount and no visual glitch occurs — the cost is redundant reactive work per row per spec emission, exactly what the (dead) diff was written to avoid. + +**Manual reproduction:** +Not directly user-visible (no remounts or visual glitches occur because the each blocks are keyed and Svelte batches the flush); observe via instrumentation: +1. In a Rill project with a canvas dashboard containing several rows, add a temporary `console.count("row-flush")` inside the reactive statement `$: widths = normalizeSizeArray($itemWidths)` in web-common/src/features/canvas/StaticCanvasRow.svelte (line 24) and EditableCanvasRow.svelte (line 68). +2. Run Rill Developer (`rill start`) and open the canvas dashboard in edit mode. +3. Trigger a reconcile that does not change the canvas layout: edit an unrelated field in the canvas YAML (e.g. `display_name`) or save an unrelated file in the project. +4. Observe in the browser console that the counter increments once per row (and per tab-group row) on every spec emission, even though row items and widths are unchanged — the diff at grid.ts:104-109 never suppresses a notification. +5. Optionally, set a breakpoint on grid.ts line 101 and confirm it executes on every emission before the guarded set, and that the guarded branch at line 108 is redundant when it runs. + +**Suggested fix:** Delete the unconditional `row.items.set`/`row.widths.set` at lines 101-102 and keep only the guarded sets; add the same changed-check for widths before setting. diff --git a/audit/deep-audit-leaderboards.md b/audit/deep-audit-leaderboards.md new file mode 100644 index 000000000000..fafea4d01c64 --- /dev/null +++ b/audit/deep-audit-leaderboards.md @@ -0,0 +1,226 @@ +# Deep Audit: Leaderboards + +Scope: `web-common/src/features/dashboards/leaderboard`, `web-common/src/features/dashboards/dimension-table`, and `web-common/src/features/dashboards/leaderboard-context-column.ts`, plus directly coupled shared code (`dashboard-utils.ts`, state-manager selectors/actions). Method: a multi-lens find phase (correctness, state, security, performance, memory) followed by an adversarial verify phase in which every candidate finding was traced end to end through the code (and, where relevant, installed library sources and git history) before being accepted. Two independent reports of the same percent-of-total bug were merged into LEAD-3. + +## Summary + +| ID | Title | Severity | Category | Verdict | +|----|-------|----------|----------|---------| +| LEAD-1 | `makeHref` renders unvalidated URL schemes from row data as anchor hrefs | medium | security | CONFIRMED | +| LEAD-2 | Measure value of exactly 0 renders as no-data "-" in leaderboard cells | medium | correctness | CONFIRMED | +| LEAD-3 | Percent-of-total divides by undefined/zero total, rendering "NaN%"/"Infinity%" | medium | correctness | CONFIRMED | +| LEAD-4 | Selected filter values with no data in the current time range vanish from the leaderboard | medium | correctness | CONFIRMED | +| LEAD-5 | Selected value can appear twice in leaderboard: strict `Set.delete` vs coercing selection compare | medium | state | CONFIRMED | +| LEAD-6 | Dimension table selection matching lacks the legacy string-filter compatibility used by leaderboards | medium | state | CONFIRMED | +| LEAD-7 | Global Ctrl/Cmd+A handler hijacks select-all from textareas/contenteditable, bulk-mutating filters | medium | state | CONFIRMED | +| LEAD-8 | Dimension table virtualizers torn down and recreated on every scroll range change | medium | performance | CONFIRMED | +| LEAD-9 | `rowOverscanAmount=120` effectively disables row virtualization for the 250-row dimension table | medium | performance | CONFIRMED | +| LEAD-10 | `selectedDimensionValues` stores recreated inline for every leaderboard on every dashboard-store change | medium | performance | CONFIRMED | +| LEAD-11 | Dimension table column widths estimated once at mount from empty rows and never recomputed | medium | state | CONFIRMED | +| LEAD-12 | `DIMENSION_TABLE_CONFIG` singleton mutated per-table and never reset; header height leaks across dashboards | low | state | CONFIRMED | +| LEAD-13 | Leaderboard IntersectionObserver never disconnected on component destroy | low | memory-leak | CONFIRMED | + +## LEAD-1: `makeHref` renders unvalidated URL schemes from row data as anchor hrefs + +**File:** `web-common/src/features/dashboards/dashboard-utils.ts:174` · **Severity: medium** · **Verdict: CONFIRMED** + +`makeHref` (dashboard-utils.ts:155-181) validates only that a URI has *some* scheme, not that the scheme is safe: any value containing a protocol is returned unchanged and bound directly to `` in `LeaderboardRow.svelte`, virtualized-table `Cell.svelte`, and the pivot/dimension-table paths (via `makeDimensionHref`), with no sanitization. When a dimension is configured with `uri: true` the href is the raw dimension value, and for the expression form it is the per-row `__rill_uri` measure resolved from the dataset — so `javascript:`, `data:`, `file:`, `vbscript:`, `intent:` etc. reach the DOM unchecked. This is a genuine missing-scheme-allowlist defect. It is medium rather than high: exploitation requires the author to enable `uri` on an attacker-influenced column, a victim click, and (for the `javascript:`/`data:` vectors) a legacy WebView/embedding context, since modern desktop browsers block those schemes for the `target="_blank"` top-level navigations these anchors use. + +**Manual reproduction** +1. In Rill Developer, create/edit a model whose data includes a text column (e.g. `landing_page`) and insert a row where that column's value is `javascript:alert(document.domain)` (or `data:text/html,`). +2. In the metrics view YAML, define a dimension on that column and set `uri: true` on it. +3. Open an explore dashboard built on that metrics view and view the leaderboard for that dimension (or open the dimension detail table). +4. Observe the external-link icon rendered next to the malicious row value; hover to see the `title`/href is the raw `javascript:`/`data:` string (no `https://` prefix was added because a scheme was detected). +5. Inspect the anchor in DevTools: ``. In older WebView/embedding contexts, clicking it executes the scheme; in modern desktop Chrome/Firefox the `javascript:`/`data:` navigation is blocked, but other schemes (`file:`, `intent:`, `vbscript:`) still pass through unvalidated. +6. Confirm the missing guard directly: `leaderboard-utils.spec.ts` has no scheme-validation case, and `makeHref` returns any protocol-bearing string unchanged. + +**Suggested fix:** Allowlist schemes in `makeHref`: parse with `new URL(...)` after the `https://` fallback and return `undefined` unless the protocol is `http:` or `https:` (optionally `mailto:`). + +## LEAD-2: Measure value of exactly 0 renders as no-data "-" in leaderboard cells + +**File:** `web-common/src/features/dashboards/leaderboard/LeaderboardRow.svelte:261` · **Severity: medium** · **Verdict: CONFIRMED** + +In the leaderboard, a measure value of exactly 0 renders as the no-data placeholder "-" instead of a formatted 0. `LeaderboardRow.svelte` uses truthiness rather than a null check in three cells: the main value cell (lines 261-263), the time-comparison absolute-delta cell (lines 305-307), and the relative-delta cell (lines 335-337). Because `0` is falsy, the formatted value is replaced with `null`, which `FormattedDataType`/`Base` and `PercentageChange` render as "-" (their explicit no-data state). The zero survives the data pipeline intact (`finiteOrNull` in `leaderboard-utils.ts` preserves 0), so any dimension value whose measure, absolute delta, or relative delta is exactly 0 displays as if data were missing. This is inconsistent with the same row's hover tooltip (line 248, which uses `!= null` and shows "0") and with the expanded dimension table (`dimension-table-utils.ts` line 473, `val !== null`), which both show the formatted 0. + +**Manual reproduction** +1. In Rill Developer, create a model with a dimension value whose measure is exactly 0, e.g. a SQL model: `SELECT 'a' AS cat, 0 AS num, TIMESTAMP '2026-07-10' AS ts UNION ALL SELECT 'b', 10, TIMESTAMP '2026-07-10'`. +2. Create a metrics view on the model with dimension `cat`, measure `sum(num)`, and timeseries `ts`, plus an explore dashboard for it. +3. Open the explore dashboard and look at the `cat` leaderboard: the row for 'a' shows '-' in the measure column instead of '0'. +4. Hover over that cell: the tooltip shows '0', contradicting the '-' shown in the cell. +5. Click 'Expand' to open the dimension table for `cat`: the same row shows a formatted '0', confirming the leaderboard and table disagree for identical data. +6. For the delta cells: extend the model so a dimension value has the same measure value in two adjacent periods (e.g. 'b' = 10 on 2026-07-09 and 10 on 2026-07-10), enable time comparison (e.g. 'Previous day'), and enable comparison columns. The absolute-delta column for 'b' shows '-' instead of '0', and the percent-delta column shows '-' instead of '0%'. + +**Suggested fix:** Use explicit null checks in all three cells: `values[measureName] != null ? formatters[measureName]?.(values[measureName]) : null`, and likewise for `deltaAbsMap` and `deltaRels`. + +## LEAD-3: Percent-of-total divides by undefined/zero total, rendering "NaN%"/"Infinity%" + +**File:** `web-common/src/features/dashboards/leaderboard/leaderboard-utils.ts:106` (also line 216) · **Severity: medium** · **Verdict: CONFIRMED** (independently found and verified twice; merged) + +Both `cleanUpComparisonValue` (lines 105-106) and `prepareLeaderboardItemData` (lines 215-216) compute percent-of-total with the guard `total !== null && value !== null ? value / total : null`, which misses `total === undefined` and `total === 0`. Because `Leaderboard.svelte` initializes `leaderboardTotals` to `{}` until the totals query resolves (lines 213-220) and gates row rendering only on the sorted-rows query's loading state (line 210), leaderboard percent-of-total cells transiently render "NaN%" whenever the sorted query resolves before the independent totals query (intermittent, since the cheaper ungrouped totals query usually wins the race; below-the-fold rows are not gated by any loading state at all). Separately and permanently, a measure with `valid_percent_of_total: true` whose filtered total is exactly 0 (e.g. a net amount summing to zero) renders "Infinity%"/"-Infinity%" for nonzero rows (and "NaN%" for zero rows), because `PercentageChange.svelte` treats NaN/Infinity as ordinary numbers (`Math.round(100 * value).toString()`). The dimension table guards both cases (`dimension-table-utils.ts` lines 92 and 528 return `PERC_DIFF.CURRENT_VALUE_NO_DATA`), so the leaderboard is inconsistent with it. + +**Manual reproduction** +1. Deterministic case (Infinity%): create a model whose measure sums to zero, e.g. `SELECT * FROM (VALUES ('a', 5.0), ('b', -5.0)) t(category, net)`. +2. Create a metrics view with dimension `category` and measure `net_total` = `SUM(net)` with `valid_percent_of_total: true`, and an explore dashboard on it. +3. Open the explore dashboard with the leaderboard sorted by `net_total` so the percent-of-total context column is visible. +4. Observe the percent-of-total column shows "Infinity%" for row 'a' (5/0) and "-Infinity%" for row 'b' (-5/0), permanently. The expanded dimension table for the same dimension correctly shows '-' for the same cells. +5. Transient case (NaN%): open any explore dashboard with a `valid_percent_of_total` measure; in Chrome DevTools enable network throttling (e.g. Slow 4G) and repeatedly change a filter or the time range. +6. Whenever the sorted leaderboard row query resolves before the totals query, the percent-of-total column briefly shows "NaN%" on every row until the totals response arrives. + +**Suggested fix:** Change the guard to `total != null && total !== 0 && value !== null ? value / total : null` (or use `Number.isFinite(value / total)`) in both `cleanUpComparisonValue` and `prepareLeaderboardItemData`. + +## LEAD-4: Selected filter values with no data in the current time range vanish from the leaderboard + +**File:** `web-common/src/features/dashboards/leaderboard/Leaderboard.svelte:272` · **Severity: medium** · **Verdict: CONFIRMED** + +The below-the-fold fallback in `Leaderboard.svelte` (lines 272-279) is all-or-nothing: if the below-the-fold aggregation query returns any rows, only those rows are rendered; placeholder rows (with null measure values) for selected values are rendered only when the query returns zero rows. Because the query filters `dim IN (belowTheFoldValues)` over the selected time range and a GROUP BY returns no row for a value with no underlying data, a partial result silently drops selected filter values from the leaderboard. Concretely: with values A and B in the include filter and a time range where A has data (but is not top-7) and B has none, only A renders below the fold and B disappears from the leaderboard entirely — even though the same code renders both as null-valued placeholders when neither has data, showing the intended behavior is to always display selected values. The value remains visible and removable in the top filter bar pill, so the impact is confined to the leaderboard surface. + +**Manual reproduction** +1. In Rill Developer, open an explore dashboard backed by time-series data where a dimension has values that only occur in part of the overall time range (e.g. a 'customer' value that stopped appearing after a certain date). +2. Set a wide time range (e.g. All Time). In a dimension leaderboard, click to include two values A and B that are both outside the top 7 for the current sort measure; both appear as selected rows below the fold (under the divider). +3. Narrow the time range to a window where A still has data but B has zero rows, keeping both outside the top 7. +4. Observe the leaderboard: only A is rendered below the fold; B has vanished from the leaderboard even though it is still an active include filter (the filter pill at the top still lists B). +5. For contrast, pick a time range where neither A nor B has any data: both now reappear below the fold as rows with null/blank measure values, demonstrating the inconsistent all-or-nothing fallback. + +**Suggested fix:** Merge instead of replace: start from the query rows, then append placeholder `{ [dimensionName]: value, ...: null }` entries for any `belowTheFoldValues` not present in `data.data` (matched with `compareLeaderboardValues`). + +## LEAD-5: Selected value can appear twice in leaderboard: strict `Set.delete` vs coercing selection compare + +**File:** `web-common/src/features/dashboards/leaderboard/leaderboard-utils.ts:189` · **Severity: medium** · **Verdict: CONFIRMED** + +In `prepareLeaderboardItemData` (line 189), `belowTheFoldValues` is seeded from `selectedValues` and pruned with `Set.delete(dimensionValue)` (strict equality), but selection highlighting uses the type-coercing `compareLeaderboardValues` (lines 191-193), the helper added in commit `7c58f94f2` specifically because legacy filters stringify all non-null values. When a numeric dimension has a filter value stored as a string (legacy proto-state URL/bookmark, or a current URL like `?f=year IN ('2024')`, since the filter grammar parses quoted values as strings) and the matching row is in the top-`slice` results (returned by the aggregation API as a number), the row renders selected above the fold but the string stays in `belowTheFoldValues`. `Leaderboard.svelte` then fires an extra below-the-fold aggregation query and renders the same dimension value a second time as a below-the-fold row; the duplicate appears even if the extra query returns nothing, because the fallback at lines 272-279 fabricates a null-measure row from `belowTheFoldValues`. This is a regression against the intent of `7c58f94f2`, which pruned by the comparator-found index. + +**Manual reproduction** +1. In Rill Developer, create a project whose model has an integer column, e.g. `SELECT 2020 + (range % 6) AS year, range AS id FROM range(0, 1000)`, and a metrics view exposing `year` as a dimension with a `count(*)` measure, plus an explore dashboard for it. +2. Open the explore dashboard so the `year` leaderboard is visible; note the top values (e.g. 2024 is within the top 7 rows). +3. Edit the browser URL to add a dimension filter with the numeric value quoted as a string: append `?f=year IN ('2024')`. Alternatively, load a legacy `state=` proto URL or an old bookmark that stored the numeric filter value as a string. +4. Observe the `year` leaderboard: 2024 renders selected in the above-the-fold list AND appears a second time as an extra below-the-fold row under the divider (duplicated entry, both marked selected). +5. Optionally open DevTools > Network and observe an additional `metrics-view-aggregation` request whose where clause is `year = '2024'` — a wasted query issued solely for the value already shown above the fold. Even if that request returns no rows, the duplicate row still renders (with a blank measure) via the client-side fallback. + +**Suggested fix:** Prune with the same comparator used for selection: iterate `selectedValues` and remove entries where `compareLeaderboardValues(selected, dimensionValue)` is true, instead of `Set.delete(dimensionValue)`. + +## LEAD-6: Dimension table selection matching lacks the legacy string-filter compatibility used by leaderboards + +**File:** `web-common/src/features/dashboards/dimension-table/DimensionTable.svelte:66` · **Severity: medium** · **Verdict: CONFIRMED** + +`DimensionTable.svelte` (lines 64-67) computes `selectedIndex` and `DimensionDisplay.svelte` (lines 191-193) computes `areAllTableRowsSelected` using strict equality between filter values and aggregation-row values, while the leaderboard uses `compareLeaderboardValues` (`leaderboard-utils.ts` line 317, added in #3769) precisely because older filters stored all non-null values as strings. `selectedDimensionValues` returns raw filter-expression values and `prepareDimensionTableRows` keeps raw JSON row values (its `as string` is a type cast only), so for a non-string dimension with a string-typed filter value (legacy bookmark, legacy URL, or any URL of the form `dim IN ('2024')`) the leaderboard shows the value as selected but the expanded dimension table shows no checkmark in the gutter, `areAllTableRowsSelected` is false, and select-all / Meta+A (via `selectItemsInFilter`, which also compares strictly) appends duplicate typed values (e.g. `IN ('2024', 2024)`) for values already in the filter. + +**Manual reproduction** +1. In Rill Developer, open a project whose metrics view has a dimension on a non-string column (e.g. an INTEGER column such as `year` or `status_code`). +2. Open the explore dashboard for that metrics view. +3. Edit the URL to add a string-typed filter for the numeric dimension, e.g. append `?f=year IN ('2024')` (URL-encoded: `?f=year%20IN%20('2024')`), and load the page. +4. Look at the leaderboard for that dimension: the row for 2024 shows a check icon (selected), because the leaderboard matches via `compareLeaderboardValues`. +5. Click the dimension name to expand it into the dimension table. +6. Observe the bug: the 2024 row has no checkmark in the filter gutter, and the select-all checkbox in the dimension header is unchecked even though every visible row is in the filter. +7. Press Meta+A (or click the select-all control): a notification reports items were added, and the filter pill now contains duplicate entries for the same value (string '2024' plus number 2024) instead of recognizing the rows as already selected. + +**Suggested fix:** Use `compareLeaderboardValues(label, row[dimensionName])` in both `DimensionTable.svelte` and `DimensionDisplay.svelte` when matching selected filter values against query rows. + +## LEAD-7: Global Ctrl/Cmd+A handler hijacks select-all from textareas/contenteditable, bulk-mutating filters + +**File:** `web-common/src/features/dashboards/dimension-table/DimensionDisplay.svelte:233` · **Severity: medium** · **Verdict: CONFIRMED** + +`DimensionDisplay.svelte` attaches a window-level keydown handler for Ctrl/Cmd+A whose only exemption is `e.target.tagName === "INPUT"`. While a dimension table is expanded, pressing Cmd/Ctrl+A with focus in any other editable element — the TipTap contenteditable chat input (`ChatInput.svelte`; ProseMirror never stops propagation, so the event reaches window even though TipTap handles Mod-a itself) or any `