Skip to content
MSO CloudDocumentation

ADR 0020 — The composable tenant: starter packs, declared pillars, org-created pages as first-class

On this page
  • Status: Accepted (implementing)
  • Date: 2026-07-25
  • Context owner: Platform
  • Related: ADR 0017 (one mapping contract, two transports — this ADR builds D6, which 0017 decided and never shipped), ADR 0012 (org workspace flexibility), ADR 0015 (semantic layer + dashboard templates), ADR 0019 (universal report surface), §15 (mapping is data), §16 (template immutability), §28 (maintenance scripts iterate every org), §47 (nav hiding is not enforcement)

Context#

Three separate complaints turned out to be one architectural gap, and it is not the gap the symptoms suggested.

The mapping mechanism is already right. ADR 0017 D1/D2 are real in code: there is ONE canonical data dictionary, ONE applyTemplate, and a Google Sheets tab binding selects a mapping template from the same import_mapping_templates asset an uploaded CSV uses. A sheet binding is an Excel template binding. That was the design and it is what shipped.

What is missing is everything around it that makes the mechanism reachable for a tenant nobody hand-onboarded:

  1. No product-level template library. ADR 0017 D6 defined a "domain pack" including system-managed default mapping templates, and applyOrgBlueprint has no template step. The defaults exist only inside onboarding scripts pinned to one org slug. So a tenant gets plugins and dashboards from its blueprint and zero mapping templates, and its uploads page is empty — which reads as "this product only supports marketplace files".
  2. Pillars are enforced by hand-written maps. Whether a surface belongs to the marketplace, marketing or market-intel plane is knowledge that lives in a person's head and, as of this week, in one hardcoded list inside plugin-host/gate.ts. Every new pillar-scoped surface is a chance to forget.
  3. An org-created dashboard cannot be a menu item. OrgMenuItem is a closed compile-time union and the join key for nav config, RBAC role policies, page guards and surface manifests; five sanitisers drop anything outside it. The one bridge is the pinned-dashboards block: capped at 8, welded to a fixed slot after "Saved views" in the overview group, unrenamable in nav, unorderable relative to real items, ungrantable per role. So the Layout Editor and custom dashboards — the features that exist SO THAT a customer need does not become a code change — dead-end at the sidebar, and the workaround is a code change.

At a million tenants each of these is the same failure: a customer's variability lands in our source tree instead of in their configuration.

Council#

Four independent reviewers were commissioned, each given a distinct mandate, opposing incentives, and read-only access to the codebase; each was required to state the strongest argument AGAINST its own recommendation. I adjudicated. Where I overruled a reviewer, the reason is recorded — including the one case where a reviewer's recommendation would have shipped a regression.

The debate produced two findings more severe than the questions asked, both verified against the production database before acting. They are written up in "Findings from the council" below.

Five roles argued; the ruling after each is mine and is what we build.

Data-platform lead. "Starter templates are a data-integrity risk, not a convenience. A pack default that carries one customer's identifier fabricates that customer's data into another tenant's silver. Ship the pack only with specs that describe a VENDOR's export format — Shopee's own order export is Shopee's for every seller — and make 'contains no customer-derived constant' a machine check, not a review habit." → Adopted. ADR 0017 D6 already stated the rule in prose; prose did not stop the YNM LinkedIn URN spec from sitting one copy-paste away from a pack. The audit is the enforcement.

SaaS architect. "Do not put the dictionary in the database. The moment a tenant can add a field at runtime you have schema-on-read, no compile-time consumer safety, and a support queue of one-off fields. Variability belongs in the MAPPING, which is already per-org data. The dictionary stays code and a new field is a product release." → Adopted, and it is already ADR 0017 D1 + its non-goals. Restated here because the pull toward per-tenant fields will recur every time a customer asks.

Security/tenancy. "A dynamic nav id is a new authorization key. If dashboard:<uuid> can appear in a role policy, every sanitiser that currently guarantees 'this string is a known nav item' must instead prove 'this uuid is a dashboard in THIS org that this viewer may see'. Get that wrong and menu configuration becomes a cross-tenant read." → Adopted as the shape of the work. The dynamic namespace is accepted, but validation moves from set-membership to an org-scoped resolve, and the existing dashboards.visibility filter remains the authority. Nav placement never grants access (§47) — the page guard does.

Frontend architect. "Keep the closed union for PRODUCT items. It is what gives us compile-time safety and lets ADR 0019's generator DERIVE the §47 plugin gate. Widening it to string to admit dashboards would trade a real guarantee for a feature. Add ONE namespaced kind instead, so the two sorts are distinguishable at every site that handles an id." → Adopted. OrgMenuItem | \dashboard:${string}`` — product items keep their union; org resources get exactly one prefix. A discriminated shape, not a widening (root convention: discriminated unions over stringly-typed flags).

Operator advocate. "ADR 0012 deliberately deferred cross-group moves as a sprawl trap, and that judgement was about per-ROLE reordering — a different thing from letting an org put its own report where its people look for it. Do not resurrect the trap while fixing the dead end: org-level placement and ordering, no per-role reordering." → Adopted. ADR 0012's non-goal stands as written; this ADR does not re-open per-user or per-role ordering.

Ruling on sequencing (mine). All four decisions ship in this change. D1/D2/D4 are additive and independently verifiable. D3 touches the id type, three sanitisers, the layout resolve and the sidebar, so it lands as one complete slice — namespace helpers with tests, an org-scoped resolve, group-aware rendering, and the editor tab — rather than a half-wired type change. The pinned-dashboards path (ADR 0012 D5) is untouched and keeps working; promotion is a separate, explicit action, so nothing regresses for an org that never uses it.

Findings from the council#

F1 — orders_natural_key was not tenant-scoped (verified on production, fixed here)

The correctness reviewer, asked about a declared key's grain, found something else:

UNIQUE (platform, platform_shop_id, platform_order_id)   -- no org_id

Confirmed by querying pg_constraint on the production database, not from the schema source.

A UNIQUE constraint is enforced across the whole table and does not respect RLS — RLS decides what a caller can SEE, not what a constraint COLLIDES with. And this ADR's own D1 made the collision path the normal one: a pack template carries no tenant identity, so it omits platform_shop_id, and promoteOrders defaults the field to <platform>-default for every tenant alike. Two organisations that both install the pack and both upload a TikTok Shop export therefore write the same (platform, platform_shop_id); if their marketplace order ids ever collide, the promoter's ON CONFLICT DO UPDATE overwrites one tenant's order row with the other's — silently, across the tenant boundary, into a row the writer cannot read.

No collision has occurred (orders holds zero rows in production today), and removing the per-customer shop constant from the pack is still right. But it converted an improbable collision into a structural one, so the constraint is now UNIQUE (org_id, platform, platform_shop_id, platform_order_id) — migration 0120, mirrored in the promoter's conflict target. The constraint is strictly WIDENED, so no existing row can violate it.

F2 — the pack admission check could be out-guessed by an unusual value

The data-platform reviewer found that IDENTIFIER_CONSTANT — the regex enforcing D1 rule 4 — matches URLs, URNs, x-abc slugs and long digit runs, but not a bare handle. A spec pinning page_external_id to 'younetmedia' would have been admitted. Value-shape matching is the wrong altitude: the rule now also refuses a constant on any target that IS the tenant's identity in its stream (site_url, page_external_id, property_external_id, platform_shop_id, …). A rule over targets cannot be out-guessed by an unusual value.

F3 — overruled: "reject a natural key with ANY empty part"

The correctness reviewer proposed tightening isEmptyNaturalKey from every to some, to catch a key that degenerates to "platform|" when one component is never produced. Rejected, and this is why reviewers get adjudicated rather than applied: budget_plan.bucket is legitimately NULL for a yearly plan, so some would reject every yearly budget row — a regression, shipped in the name of correctness. The underlying defect was real, so it is fixed at the right altitude instead: STREAM_NATURAL_KEYS.creators named external_creator_id, which no template maps and no promoter reads (the commission promoter keys on creator_handle), and a new derivability assertion now requires every natural-key field to be producible by a real template — canonical membership was never enough.

F4 — BUILT (2026-07-26): bind-time template parameters

The reason marketing starter packs are empty is not an oversight. A GSC CSV export has no site column, but site_url is required and is the natural key, so the only way to satisfy it today is a constant — one customer's own domain, which F2's rule correctly refuses. Three alternatives were evaluated and each fails a constraint this platform already committed to: deriving the value from the connector cannot work on the UPLOAD path (there is no connector), and making the field optional weakens the dictionary for every tenant to serve one. The accepted shape is a declared parameters list on the spec plus a param transform, with values supplied per binding/upload and validated at save, at resolve-before-I/O, and at apply.

It IS implemented now, end to end:

  • spec.ts declares parameters (max 8, lowercase snake names, optional {vi,en} label) and validateSpecParameters rejects an undeclared reference, a dead declaration and a duplicate.
  • transforms.ts gains the eleventh kind, { kind: 'param', name }. The closed set stays closed and replay stays deterministic because the spec declares every name it may read and the transport RECORDS the bound values.
  • apply.ts resolves it with three rules: an undeclared reference is a SPEC error (TemplateSpecError, classified permanent so it DLQs once instead of retry-flooding, §56); a declared required parameter with no value fails the ROW naming the parameter — never a default, never an empty string (§32); a declared optional one degrades exactly like an empty cell.
  • Both transports carry values per USE, which is the whole point: a sheet binding gains mappingParams (so two tabs can feed two properties through ONE template) and an upload passes params, persisted on manual_upload_jobs.mapping_params (migration 0122) because a spec with parameters is no longer a total function of (spec, file) and §16 only pins the spec.
  • Refused at SAVE on both fronts, where an operator is present: uploadTemplated rejects a blank required value, and validateSheetTemplateBindings does the same for a binding. The UI blocks it too, but the UI is not the authority — both mutations are reachable by API.
  • The payoff: the three Search Console templates are now expressible without a customer's domain and ship as origin: 'vendor-export' starter templates, so a marketing-only tenant installs a populated template library instead of an empty page.

Two gaps the work UNMASKED, both fixed here and worth recording because a gate was lying: scripts/security-scan.mjs treated an apostrophe inside a // comment as a string opener, so its paren walker ran past one mutation's closing paren and swallowed the NEXT mutation whole — that mutation was then never checked. uploadTemplated had shipped with no rate limit behind that blind spot, and making the walker comment-aware immediately surfaced a second one, admin.seedSampleData (which spawns a child process to reseed a whole org). Both now rate-limited. A scanner that silently skips a mutation is worse than no scanner, because the green tick is load-bearing.

F5 — ranked scale debt, with thresholds

The scale reviewer's ranking, recorded because "it works at one tenant" is not an architecture:

  1. Scheduler fan-out — enqueueActiveConnectorJobs / enqueueActiveMarketingConnectorJobs select every active connector unpaginated and enqueue sequentially, on a concurrency: 1 scheduled worker. One pass eventually exceeds the 5-minute interval that retriggers it, and then EVERY cron kind queues behind it. Cheapest fix: addBulk plus a cursor-paged select.
  2. import_staging_rows has no retention — supersede is a status flip, never a delete, and no purge job exists (unlike validation_runs and audit_logs, which both have one). The non-unique dedupe index accumulates an unbounded posting list per recurring key. Cheapest fix: a purge sweep mirroring the two that already exist.
  3. Sheets direct-to-sink re-triggers a 9-phase materialisation refresh per tick whether or not the sheet changed, because a successful upsert counts as promoted regardless of whether values moved. Cheapest fix: hash the read grid and skip when unchanged.

None is fixed here; each is now a named threshold with a named remedy rather than an unknown.

F6 — dictionary extensibility: field packs first, a declared extension namespace later

The extensibility reviewer established the real cost of the current design by counting: one new nullable field touches 4–7 files across three packages plus a migration, and up to a generated Cube artifact. It also found that the platform ALREADY grew an ungoverned escape valve — the orders promoter reads raw header strings out of source_payload by literal constant, invisible to the dictionary and available to no other stream.

Ruling: vertical field packs (still code-declared) absorb anything two tenants in a segment would want, and remain the first answer. A per-stream typed extension namespace is accepted in principle for the genuine one-off, with a hard boundary — extension fields may never enter METRIC_DEFINITIONS, the Cube generator, or a shared aggregate; display, export and single-org filtering only. EAV is rejected on the reviewer's own analysis rather than on inherited doctrine. Neither is built here.

Decision#

D1 — Starter template packs are a product artifact, org-agnostic and installable

A StarterTemplate (packages/connectors/core/src/mapping/starter-templates.ts) is { sourceKind, targetStream, name, origin, spec } where origin records WHY the spec is tenant-neutral: marketplace-export (Shopee/TikTok/Lazada seller exports) or vendor-export (Google Search Console CSV). One definition (§49) — the per-customer onboarding scripts import from this registry instead of declaring their own copies.

Admission rules, all machine-checked:

  1. spec parses as importTemplateSpecSchema and spec.targetStream equals the entry's stream.
  2. Every columns[].target is a field of STREAM_FIELDS[targetStream] (the D2 gate below).
  3. dedupeKey satisfies validateDedupeContract — so a pack template can never collapse rows differently from a hand-authored one.
  4. No constant transform carrying a customer-derived identifier. A spec that bakes one customer's account/org id would fabricate that customer's identifiers into another tenant's silver (§32) — the rule ADR 0017 D6 wrote in prose, now enforced.

Installation is idempotent and never overwrites: a lineage that already exists for (orgId, brandId, sourceKind) is skipped, so a customer edit — which flips the lineage to customer-owned — is permanent (ADR 0017 D6's one-way takeover). Packs apply through applyOrgBlueprint for new tenants and on demand for existing ones, iterating every org by default (§28).

D2 — Dictionary conformance is enforced where the mapping is AUTHORED

validateColumnTargets rejects a column target that is not a canonical field of the stream, at save time, in Vietnamese, naming the field. findDictionaryDrift asserts that STREAM_FIELDS and STREAM_SCHEMAS describe the same fields with the same required-ness, so the registry the wizard generates from cannot drift from the registry that validates. Both are in packages/connectors/core/src/mapping/dictionary.ts and asserted by its test.

This is the enforcement ADR 0017 D1 assumed it had. Without it, "map onto the canonical dictionary" was advice: a mistyped target was accepted, stored, and silently stripped at promote time, so the datum vanished with no error and the field name lived on in that customer's template.

D3 — An org-created dashboard is a nav citizen, under one namespaced id kind

OrgMenuItem | \dashboard:${uuid}``. The union stays closed for product items — ADR 0019's generator keeps deriving the §47 plugin gate from it, and a typo in a product id stays a compile error. Org resources arrive under exactly one prefix, so every id-handling site can tell the two apart and choose the right validation:

  • Set membership for product ids (unchanged).
  • Org-scoped resolve for dashboard:<uuid>: the dashboard must exist in the caller's org and pass the same dashboards.visibility filter the list page uses. A menu blob naming a dashboard from another org resolves to nothing and is dropped, exactly as an unknown product id is today.

Placement lives in an additive organizations.nav_custom_items jsonb ({ id, groupId, label? }), which is the same shape and the same tenancy as the four menu blobs beside it — no new table, no new RLS surface. Ordering, renaming and hiding reuse menu_order / menu_labels / hidden_menu_items, which now accept the namespaced form.

Ruled during implementation: a promoted dashboard does NOT enter org_role_policies.menu_items. The tempting symmetry — "it is a menu item, so grant it per role" — would give one resource TWO authorization keys: the role's menu set and dashboards.visibility. Two sources of truth for who may open a page is how an access bug gets written. So visibility is inherited from the dashboard itself: the layout resolves promoted items through the SAME visibility filter the dashboards list uses, and the sidebar skips the role-menu check for them precisely because that check describes the product catalogue, not org resources. requirePageMenuItem keeps its closed OrgMenuItem type and needs no cast. The org-wide hide list still applies, because hiding is cosmetic either way (§47).

Nav placement is still not enforcement (§47): the dashboard page's own visibility check remains the authority, and a dashboard removed from the menu stays reachable by URL exactly as now.

D4 — Pillars are declared on the surface, not remembered

ReportSurface gains requiresConnectorFamily?. The ADR 0019 generator emits the pillar→nav-item mapping, and both the nav filter and the page guard read that generated set. The hardcoded PILLAR_SETTINGS_NAV_ITEMS list added this week is deleted — it was the second copy of knowledge that belongs on the page it describes, and the kind of list that is correct only until someone adds a surface.

Non-goals

  • Per-tenant custom FIELDS (restated from ADR 0017: variability lives in mappings; a field two customers need is a nullable canonical field via a product release).
  • Per-user or per-role menu ORDERING (ADR 0012's deferral stands).
  • Promoting a dashboard to a nav item automatically. It is an explicit org-admin action; a tenant with 200 saved views does not get 200 menu entries.
  • Runtime-editable dictionary, EAV, schema-on-read.

Consequences#

  • A new tenant lands with mapping templates for the vendor exports its pillars imply, so the upload page and the sheet binding picker are populated on day one without an onboarding script.
  • The dictionary becomes enforceable rather than aspirational: a mistyped target fails at save, and the two registries cannot drift.
  • Adding a pillar-scoped surface is one manifest field; forgetting it is a generator failure rather than a tenant seeing settings for data it cannot have.
  • An org can put its own report in the menu where its people look for it, without a deploy — which is the whole point of the Layout Editor and custom dashboards.
  • The cost is honest: every site that handles a menu id now handles two kinds. That is why the namespace is one prefix and not free-form strings.

Addendum 2026-07-27 — D9: hai mặt phẳng metric (bài toán "hàng triệu metric × hàng triệu khách")#

Chỉ thị operator: thiết kế cho trường hợp mỗi khách có metric riêng, ở quy mô hàng triệu tenant.

D9 — Metric có đúng HAI mặt phẳng, không bao giờ trộn:

  1. Platform metrics = code catalog (METRIC_DEFINITIONS, ~100 slug): một slug cho một ngữ nghĩa dùng chung (GMV, chi tiêu quảng cáo, CTR…), mọi tenant dùng chung, versioned, §49 một định nghĩa. Catalog KHÔNG BAO GIỜ nhận entry riêng của một khách — đó chính là lớp lỗi KPI_LINE_PLATFORMS/DEFAULT_WEB_PROPERTY (hằng số khách trong code) đã bị dọn.
  2. Tenant metrics = DỮ LIỆU (business_kpi_facts: org × metric_key × năm × loại, nhãn là raw_label của chính khách): triệu metric riêng = triệu HÀNG, discovery per-request trong scope org với cap §1 (BUSINESS_KPI_ROW_CAP). Không enum toàn cục, không rebuild, không branch per-customer. Reader duy nhất: @yng/metrics/business-kpi-read (§49); surface đầu tiên: dataset business_kpi_facts (widget "Dữ liệu" trên mọi dashboard).

Hệ quả: một cấu hình thuộc về TENANT thì nó là CỘT/HÀNG dữ liệu có UI sửa (ví dụ kpi_targets.ad_platform, migration 0124), không phải hằng số; một ngữ nghĩa dùng chung thì nó là MỘT slug catalog, không nhân bản theo khách.

Amendment 2026-09-03#

D3's dashboard:<uuid> nav-item namespace gains a sibling, dashboard-tab:<uuid>, so a menu pin can address one Dashboard-tab inside a multi-tab Page instead of always landing on the Page's first tab — same prefix idiom, same UUID validation. The nav blobs D3 addresses also gain a brand-scoped tier (org_nav_config, one row per org plus one override per brand). See ADR 0043 D5/D6.

Amendment 2026-09-10#

D4's ReportSurface.requiresConnectorFamily declares a pillar on the surface; that pillar now also sits under a product-level Vertical above it (eCom, marketing, CRM, audience, market, HR, finance) — a fourth axis alongside plane, ingest family and resolver pillar, indexed by one compiled registry rather than folded into any of the three. See ADR 0048 D1.

D9's two metric planes (platform catalog = code, tenant metrics = data) stay exactly as decided; they gain ONE INDEX rather than a merge: the vertical registry maps each vertical to its metric mechanism, and a super-admin read surface lists both sides per vertical. See ADR 0048 D4 (index landed this batch; the /admin/metrics surface itself is planned for a later batch, ADR 0050).