Skip to content
MSO CloudDocumentation

ADR 0001 — Adopt Cube as the headless semantic layer for analytics

On this page
  • Status: Accepted (2026-11-07). Written as "Proposed (2026-04-24)"; Cube is in the tree (infra/cube/) and pnpm cube:generate:check runs in audit:all.
  • Owner: TienLe (CTO / Product)
  • Supersedes: none
  • Related: packages/metrics, packages/alerts, packages/agent, apps/web/src/app/(dashboard)/dashboards, docs/architecture/reference/warehouse-schema.md

Context#

YNG Unified Commerce already ships a curated, opinionated Vietnamese-first analytics product:

  • Metric catalog (packages/metrics/src/catalog.ts) — 20 declarative metrics with units, grains, dimensions, source tables, ownership, version.
  • A SQL compiler (build-query.ts) that turns metric specs into Drizzle queries against agg_* rollups or facts.
  • A custom dashboards builder (apps/web/src/app/(dashboard)/dashboards).
  • AI briefings, alerts, and an action / playbook loop that all consume metrics.
  • Strict multi-tenant invariants: every org-scoped query must pass through setOrgContext(orgId) (RLS).

We have three growing pressures:

  1. Three consumers of the same metric definitions — UI, AI agent, alerts — each currently re-derives logic in different places. Drift is starting to show (e.g. gross_margin formula divergence between alerts and briefings).
  2. Power-user demand — beta customers want pivot tables, custom SQL, scheduled CSV exports, ad-hoc cohort builders. Building this in-house is a multi-quarter detour.
  3. AI hallucination cost — the agent writes raw SQL today and occasionally invents column names. Grounding the agent on a metric API would cut errors and preserve RLS.

The market for embedded BI is now mature. Reviewed in scope: Metabase, Apache Superset, Lightdash, Cube, Embeddable, Astrato, Toucan.

Decision#

Adopt Cube (open source) as the headless semantic layer. Keep the curated dashboards we own. Add Apache Superset as an optional embedded "Explore" surface for power users, gated behind a Pro-tier feature flag.

┌─ AI Agent (@yng/agent) ─┐
├─ Alerts (@yng/alerts) ──┤   ──►  @yng/cube-client  ──►  Cube  ──►  Postgres (RLS)
├─ Curated UI (@yng/web)  ┤                              │
└─ Superset (Pro Explore) ┘                              └─ pre-agg cache (cubestore / Postgres)

Why Cube

Requirement Why Cube fits
Multi-tenant security context aligns with our RLS model Cube securityContext.orgId injected into JWT → mapped to setOrgContext() via the data source pre-query hook
TypeScript-native team Cube schema is JS / YAML; tooling, codegen, and types live comfortably alongside packages/metrics
Same defs feed multiple consumers (UI, AI, alerts, BI) Cube exposes REST + GraphQL + SQL + MDX from a single schema
Don't want vendor lock Cube Core is Apache 2.0; can self-host on our existing infra
AI agent grounding Cube's meta endpoint and natural-language Cube AI hooks let the agent enumerate measures/dimensions instead of guessing column names
Pre-aggregations / caching Cube's pre-agg engine replaces hand-rolled agg_org_* materialization for new metrics (existing tables stay)

Why not the alternatives

  • Metabase as primary UI — multi-tenant story is weak (org-per-Metabase-collection hacks); embedding it as customer-facing UI would erase our VN-first UX moat.
  • Superset as primary UI — best-in-class explore but heavyweight; embedding for every customer fights our Tailwind / i18n / mobile-first surface. Use as power-user explorer only.
  • Lightdash — only worth it if we adopt dbt as the modeling layer. Our Drizzle + tRPC stack does not warrant that switch right now.
  • Build our own semantic layer further — packages/metrics/src/build-query.ts works for 20 metrics; at 50+ it becomes a maintenance tax we shouldn't pay when an OSS standard exists.

What stays the same

  • packages/metrics/src/catalog.ts remains the source of truth during migration. A generator script (scripts/cube/generate-schema.ts) emits Cube schema files from the catalog so we keep one place to declare a metric.
  • Drizzle remains the OLTP / write path. Cube only reads.
  • RLS policies remain the safety net — Cube's security context is defense in depth, not a replacement.
  • The custom dashboards UI and @yng/charts keep their role; they switch their data source from tRPC metrics router to @yng/cube-client.
  • All existing CI security gates apply (pnpm run security:scan).

What changes

  • New package: @yng/cube-client — typed REST client, JWT minter (uses CUBE_API_SECRET per-environment), tenant-scoped query builder, in-process metric proxy with the same shape as today's tRPC return.
  • New deploy target: Cube API service (Docker, behind internal LB, not exposed publicly). Local dev under docker compose --profile cube up.
  • New schema dir: infra/cube/schema/*.js (generated; do not hand-edit).
  • Existing tRPC metrics router routes through @yng/cube-client once Phase 1 is green; legacy build-query path kept behind a feature flag for one minor release, then removed.

Amendment 2026-09-03

  • Tenant datasets (ADR 0038) do not go through Cube. Cube's schema here stays a checked-in build artefact generated from a code catalog over nine fixed eCom tables, gated by cube:generate:check — a tenant dataset's schema changes at runtime, per org and per brand, and routing it through Cube would move tenancy from Postgres RLS to Cube's securityContext, a weaker enforcement point at exactly the moment the data gets sensitive (employee compensation). The tenant-dataset read path is an in-repo compiler (packages/metrics/src/dataset-rollup.ts) beside build-query.ts, inside the caller's own RLS transaction. Revisit only if a customer needs SQL-API/Superset over their own dataset — and then generate a per-org Cube schema from the same org_dataset_fields rows, which stay the single source either way.

Consequences#

Positive

  • One canonical metric definition feeds UI, AI agent, alerts, and BI.
  • Power-user surface ships in weeks, not quarters.
  • AI agent hallucinations drop because it queries a typed semantic API.
  • Pre-aggregation / caching becomes config, not a hand-rolled cron.

Negative / costs

  • A new service in the deploy pipeline — adds ~150 MB image, 1 container, JWT secret rotation surface.
  • Schema-generation step adds a build dep; CI must regenerate and verify-no-diff.
  • Cube has its own query language (Cube Query Format). Team must learn it, but the surface is small (~5 endpoints).

Risks & mitigations

Risk Mitigation
Cube bypasses RLS via service-role connection Cube uses an app-role Postgres user (RLS enforced); security context calls set_config('app.current_org_id', <orgId>, false) before each query via a Postgres driver prepareConnection override. (GUC name matches setOrgContext() in packages/schema/src/client.ts.)
JWT secret leak Stored in same envelope as ENCRYPTION_KEY (KMS in prod, .env only in dev with ${VAR:?}).
Schema drift between catalog and Cube CI step pnpm cube:generate && git diff --exit-code infra/cube/schema — fails build if generator output is stale.
Superset multi-tenant leak Superset never connects to Postgres directly — only to Cube SQL API with per-session JWT.
Cube outage UI falls back to legacy build-query path during Phase 1 only; after migration, dashboards degrade to "data temporarily unavailable" with a status banner.

Acceptance criteria for closing this ADR#

  1. All 20 metrics render through Cube in staging with byte-identical numbers vs build-query.
  2. Security test confirms cross-tenant query attempt returns empty result and logs an audit warning.
  3. AI agent (packages/agent) uses Cube REST API for ≥1 use case end-to-end.
  4. CI gate cube:generate --check is green and required.
  5. Cube Phase 1 checklist 100 % complete (shipped).

References#