On this page
- Status: Accepted (2026-11-07). Written as "Proposed (2026-04-24)"; Cube is in the tree (
infra/cube/) andpnpm cube:generate:checkruns inaudit: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 againstagg_*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:
- 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_marginformula divergence between alerts and briefings). - 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.
- 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 security 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/ |
| 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_ 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.tsworks 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.tsremains 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/chartskeep their role; they switch their data source from tRPCmetricsrouter 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 (usesCUBE_API_SECRETper-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
metricsrouter routes through@yng/cube-clientonce Phase 1 is green; legacybuild-querypath 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'ssecurityContext, 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) besidebuild-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 sameorg_dataset_fieldsrows, 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_ before each query via a Postgres driver prepare override. (GUC name matches setOrgContext() in packages/.) |
| JWT secret leak | Stored in same envelope as ENCRYPTION_ (KMS in prod, . only in dev with ${VAR:?}). |
| Schema drift between catalog and Cube | CI step pnpm cube:generate && git diff - — 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- path during Phase 1 only; after migration, dashboards degrade to "data temporarily unavailable" with a status banner. |
Acceptance criteria for closing this ADR#
- All 20 metrics render through Cube in staging with byte-identical numbers vs
build-query. - Security test confirms cross-tenant query attempt returns empty result and logs an audit warning.
- AI agent (
packages/agent) uses Cube REST API for ≥1 use case end-to-end. - CI gate
cube:generate --checkis green and required. - Cube Phase 1 checklist 100 % complete (shipped).
References#
- Cube docs — semantic layer & multi-tenant security: https://cube.dev/product/semantic-layer-security
- Embedded BI comparison 2026 — Basedash: https://www.basedash.com/blog/best-open-source-bi-tools-compared-2026
- Vietnam social commerce Q1 2026 — Shopee 56 / TikTok 41 / Lazada 3: https://www.globenewswire.com/news-release/2026/04/22/3279204/28124/en/Vietnam-Social-Commerce-Market-Report-Q1-2026-Update-Competitive-Dynamics-Shift-as-Shopee-and-TikTok-Lead-Vietnam-s-Social-Commerce.html
- Internal:
packages/metrics/src/catalog.ts,apps/web/src/server/trpc.ts,docs/architecture/reference/warehouse-schema.html