On this page
- Status: Accepted. D1-D6 shipped. Amended 2026-11-07: D6 was NOT built at the 2026-07-25 audit and is built now; see "Implementation status" below.
- Date: 2026-07-23 (revised same day after a 4-lens expert review: SaaS-scale architecture, data-platform correctness, security/tenancy, onboarding UX)
- Context owner: Platform
- Related: ADR 0008 (marketing family), ADR 0014 (sheet stream connectors — D2 sinks, D3 header maps, deferred M3), ADR 0015 (semantic layer + dashboard templates), §10/§41 (ICT), §15 (mapping is data), §16 (template immutability), §32 (no fake values), §44 (PII), §49 (one impl), §56 (permanent → DLQ once), §66/§75 (DB-free drivers, RLS scope), §68 (NULLS NOT DISTINCT)
Implementation status (audited 2026-07-25)#
Recorded because this ADR sat at "Accepted (implementing)" for two days while three code comments still asserted the opposite of D2 — enough for a reader to conclude the two transports were separate mechanisms. They are not.
| Decision | Status | Evidence |
|---|---|---|
| D1 — canonical contract IS the dictionary | Shipped, but it had drifted | STREAM_/STREAM_/STREAM_ cover all 23 streams. See "Dictionary drift" below — the declaration disagreed with the consumer on orders, creators, budget_ and social_. |
| D2 — one mapping asset, both transports | Shipped | One applyTemplate, called from parser. (upload) and values. (sheets); transport- guards it. Scope of that test is now stated in the test itself: it proves MAPPING parity, not persistence parity. |
| D3 — resolution + failure semantics | Shipped | resolve, the four TEMPLATE_ permanent codes, sync_, save-time mirrors in connectors.. |
| D4 — the template is the customer's file template | Shipped | listSpecSourceColumns → header-only CSV download. |
| D5 — binding UX | Shipped | Per-binding template picker, inline wizard, connectors. preview against real cells. |
| D6 — domain pack incl. system-managed default templates | Built (amended 2026-11-07) | applyOrgBlueprint installs starter mapping templates through install (apps/). The 2026-07-25 audit found no mapping-template step: default templates lived only in per-customer onboarding scripts, so a new tenant started with zero. |
Dictionary drift found while auditing D1
D1's claim is only as good as the agreement between the registry the wizard GENERATES FROM
(STREAM_FIELDS) and the one that VALIDATES (STREAM_SCHEMAS) — and nothing asserted they
described the same fields:
orders/creators: the declaration was fiction.STREAM_FIELDS.orderslistedtotal_vndandcreated_atas REQUIRED — no code reads either — and omittedexternal_sku_idandplaced_at, whichpromoteOrdersrejects a row for missing. Since the wizard drafts its columns from this list, a wizard-authoredorderstemplate mapped two ignored fields and none of the required ones: every row it produced was rejected. Every working orders/creators template in existence came from a seed script. Both entries now declare what the promoter reads, andorderCanonicalSchema/creatorCanonicalSchemawere widened to match so the two registries agree.budget_plan.bucketwasnullable()— null allowed, ABSENT rejected — so a yearly plan sheet, which has no bucket column to map, failed every row. Nownullish()normalized to null.social_signals.sourcewas validated by the schema but missing from the dictionary, so no template could map it. Now declared.inventoryhas no silver promoter (dispatchPromoteno-ops), so its fields describe nothing; said so in the declaration rather than leaving it implied.
The enforcement D1 assumed but never had
A typo in dedupeKey failed loudly at save (validateDedupeContract). The SAME typo in
columns[].target was accepted, stored, and then silently stripped by Zod at promote time — the
datum never arrived and nothing reported it. That asymmetry is precisely how field names multiply
per customer, which is the one thing a shared dictionary exists to prevent. validateColumnTargets
(mapping/dictionary.ts) now rejects a non-dictionary target at authoring time, and
findDictionaryDrift is asserted by dictionary.test.ts so the two registries cannot drift apart
again. Adding the gate was safe to do without a migration: production held zero mapping templates.
Transport asymmetries found and closed
Genuine defects, not design differences:
ad_spendupload cutover guard was a no-op.promoteAdSpendnever loaded the stream'sapiCutoverDay, sobuildUploadCutoverSetWherereceived null and returnedundefined— whileupsertAdSpendCanonical's own docstring claimed the guard was applied. Four sibling marketing promoters load it. Consequence: a stale re-upload (source='upload') could overwrite fresher sheet/API rows (source='api') on the same natural key, and ad spend is the MER/CPL denominator — wrong money on a dashboard, no visible failure.- PII asymmetry.
applyTemplateerror strings embed the offending cell value; the sheets path redacts them throughsanitizeRowError, the upload path stored them raw in operator-visiblemanual_upload_jobs.rejectedReasons. The CRM streams carry buyer PII (§44). Now both redact. - Preview vs run timezone. The upload preview called
parseUploadWithTemplatewith nobrandTimezonewhile the sheet preview passed ICT, so anoutput:'iso'column with noassumeTimezonepreviewed seven hours off from what the import would write — the operator approved a mapping against dates the run would never produce.
Context#
Customers keep arriving with the SAME kinds of data (CRM leads, ad spend, web analytics, social pages, email, budget plans…) in DIFFERENT column shapes, and want to feed it either by uploading CSV/Excel or by connecting a Google Sheet. The platform already has the load-bearing pieces, but they meet the two transports differently:
- The standard data contract exists:
TARGET_STREAMS+STREAM_SCHEMAS+STREAM_FIELDS(packages/connectors/core/src/mapping/{spec,streams}.ts) define the canonical fields per stream; every silver table sits behind ONEupsert*Batchsink (apps/worker/src/promoters/silver-upsert.ts); standard metrics live above in the pillar semantic layer (ADR 0015 S1); dashboards bind to metrics/datasets, never to source columns. - The upload path is per-org configurable:
import_mapping_templatesstores a versioned, immutableImportTemplateSpec(§15/§16) applied by the pureapplyTemplate(mapping/apply.ts); rows stage inimport_staging_rowsand promote viadispatchPromote. - The sheets path is NOT: a binding maps headers either by exact canonical field names
(
values.tsgeneric mode) or by a FIXED product header map in code (product-maps.ts, ADR 0014 D3). A customer whose sheet has its own column names is a code change — the per-customer conditional §15 exists to forbid. ThesheetBindingSchema.mappingTemplateIdhook was reserved for this (ADR 0014 "M3") and never wired, because the driver must stay DB-free (§66/§75).
Decision#
D1 — The canonical stream contract IS the product's standard data dictionary
TARGET_STREAMS/STREAM_SCHEMAS/STREAM_FIELDS is the single registry of standard fields
per data domain; the pillar metric catalog (ADR 0015) is the single registry of standard
metrics above it. Onboarding a customer NEVER adds fields to it. A genuinely new data kind is
a PRODUCT release: new stream + sink + rollup consumer (§46) + pillar metrics + dashboard
template — never a per-customer branch or table. Customer variability is absorbed entirely by
mapping templates (D2) and org/brand configuration. New in this ADR: a per-stream
natural-key registry STREAM_NATURAL_KEYS exported from @yng/connectors-core (one
definition; values.ts DEDUPE_KEYS and the template validator both consume it — §49 applied
to identity).
D2 — ONE mapping asset per org, applied identically on both transports
import_mapping_templates is the org's single mapping asset for BOTH transports:
- Upload (existing): template →
parseUploadWithTemplate→applyTemplate→import_staging_rows→ promoter → sink. - Sheets (this ADR): the WORKER resolves the binding's template (D3) and passes the
resolved
ImportTemplateSpecintorunSheetsSyncas plain data; the driver applies the SAME pureapplyTemplateper row and validates against the SAMESTREAM_SCHEMAS[stream]. The driver stays DB-free (§66/§75). Template-mode rows go direct-to-sink (no staging): the sheet itself is the retained, replayable source; staging a 500-row tab every cron tick would be an unbounded write amplifier with no purge story.
Identity contract: the silver natural key (STREAM_NATURAL_KEYS) is authoritative for
cross-transport row identity — it is what every sink upserts on. The template's
spec.dedupeKey governs staging supersede/audit ONLY. At template save, a new version's
dedupeKey must (a) name only mapped column targets and (b) cover the target stream's
natural key — so the two transports can never collapse rows differently (§68/#24 class).
Cell contract (sheets): the client pins valueRenderOption: 'FORMATTED_VALUE' (codifies
today's implicit default — the same rendering a "Download as CSV" export produces, which is
what D4 hands the customer). Stringification: String(cell) + trim for number/boolean cells.
Guard against separator misconfiguration: an int/decimal transform that finds MORE THAN
ONE decimalSep occurrence in a value rejects the row ("ambiguous separators") instead of
truncating — the observed failure is a vi-locale "1.234.567" against a decimalSep:'.'
template parsing to 1 (silent ×10⁶ money corruption). Authoring-time protection is D5's
preview against REAL tab cells.
Parser-knob contract (per transport): skipLines — applied to the values grid exactly as
to CSV text; trimHeaders — replicated when building the source record; headerCaseInsensitive
— active on both (it drives lookupSource, not CSV parsing); delimiter/quote/encoding —
inert on sheets. Fixed in the same change: concat/product sources now resolve through
lookupSource (they were case-sensitive even with headerCaseInsensitive: true — silent
defaultValue: 0 money on a case mismatch); the dead __pendingDate branch in
buildDedupeKey is deleted (dates parse inline; dedupe keys derive from PARSED values).
Timezone contract: both call sites pass ctx.brandTimezone = 'Asia/Ho_Chi_Minh' (§10 —
the platform is ICT end-to-end; a template for another zone sets assumeTimezone). This also
fixes the pre-existing upload gap where processTemplatedUpload passed no ctx, so an
output:'iso' date column with no assumeTimezone stamped VN wall-clock as UTC — the §10
boundary-leak class. Implementation must audit existing active template specs for reliance on
the old null→UTC behavior before flipping (§55: confirm semantics, then fix).
Parity gate: one behavioral test comparing POST-STREAM_SCHEMAS-parse payloads AND
dedupe keys, with fixtures entering as raw CSV bytes on one side and a typed
string|number|boolean cell grid on the other (never pre-stringified rows). Fixtures include
locale-formatted numbers, booleans, auto-typed dates, an id column exceeding 2^53, and an
iso-datetime column with no assumeTimezone. Wired into the unit gate.
Source discriminator (declared, unchanged): template-mapped sheet rows keep each sink's
current source semantics (e.g. ad_spend source:'api' — a continuously-refreshed feed for
cutover purposes). A distinct 'sheet' source value is deferred until a customer actually
feeds one stream via both transports (§55 — don't change metric semantics speculatively).
Mapping-mode precedence per binding: explicit mappingTemplateId > fixed product header map
(SHEETS_PRODUCT_STREAMS) > generic canonical-name mapping. Existing bindings are untouched.
Template mode closes the documented M2 limitation (percent→bp / decimal→milli scaling via the
decimal transform instead of pre-scaled sheet integers).
Sink coverage: every stream in CANON_SHEET_STREAMS gets a SHEET_STREAM_SINKS entry in
this ADR's scope — the upsert*Batch implementations all exist already; today 8 of 13
bindable streams DLQ as CONNECTOR_STREAM_UNWIRED at sync time, which contradicts the
binding UI. A unit test asserts CANON_SHEET_STREAMS ⊆ wired sinks so the class stays closed.
D3 — Template resolution + failure semantics
- Lineage semantics: a binding stores a template uuid; at sync time the worker resolves
it to the ACTIVE version of the referenced row's lineage
(orgId, brandId, sourceKind), so a mapping edit (= new version, §16) applies next sync with no connector edit. Resolution lives in ONE shared helperresolveActiveTemplateused by both the sheets sync and (for its lineage lookups) the upload path. The upload path's exact-version pin at upload time stays — declared intentional: an upload is a point-in-time operator action against the version they can see; a scheduled sync is an ongoing subscription that follows the head. - Tenancy: resolution runs inside
runWithRlsContext(orgId, brandId)BEFORE any driver I/O (§66b), with an expliciteq(importMappingTemplates.orgId, orgId)predicate as the trusted app-layer check (invariant 1: RLS is the net, not the authz) — mirroringloadAndDecryptConnectorandprocessTemplatedUpload. - Failure semantics: four PERMANENT config errors (§56 — DLQ once, dedup on stable codes,
operator-visible Vietnamese message; fail BEFORE driver I/O so no Google quota burns):
TEMPLATE_NOT_FOUND,TEMPLATE_LINEAGE_ARCHIVED,TEMPLATE_STREAM_MISMATCH,TEMPLATE_BRAND_MISMATCH(templatebrandIdmust be NULL — org-wide — or equal the connector'sbrandId). - Save-time mirrors: the connector create/update mutation validates the same four
conditions PLUS "targetStream is a wired sink", so a misconfigured binding fails at save,
not at 02:00. On the template side,
upsertVersion(a) rejects atargetStreamchange within an existing lineage (a different stream = a newsource_kind) — otherwise a template edit silently breaks every referencing binding; (b) keeps §16 immutability. The dead "per-brand overrides take precedence" comment inimports.tsis corrected to the real semantics (explicit reference, org-wide templates usable by any brand). Hardening:import_templates_version_uniqgains NULLS-NOT-DISTINCT semantics (§68 applied to our own table) so org-wide lineages cannot mint duplicate version numbers under concurrency. - Accounting (the auditability home):
sync_jobsgains an additivestream_accountingjsonb column: per stream{promoted, rejected, templateId, templateVersion, errorSamples}whereerrorSamplesis a CAPPED (≤20) list of{rowIndex, target, reason}that NEVER echoes raw cell values (§44 — CRM streams carry PII;applyTemplate's raw-value error strings are sanitized at the recording boundary). When MORE THAN ONE binding feeds the same stream (the driver merges batches per stream), template attribution is OMITTED for that stream — an honest absence beats a wrong attribution (§32 applied to metadata). Rendered in the connector detail panel so the operator self-serves "why were 4,000 rows rejected" — the sheets mirror ofmanual_upload_jobs.rejectedReasons. - Volume model (declared): template-mode bindings read via the existing paged reader; full re-read + natural-key upsert is the idempotency model (no watermark — correct at current volumes); a documented per-tab row ceiling makes customer #50's 200k-row sheet a known "no", not a discovered outage. Materialization refresh stays once-per-sync, skip-on-zero-promoted.
D4 — The template is also the customer's file template
A mapping template fully determines its expected source columns (listSpecSourceColumns).
The templates UI gains "Tải file mẫu": a generated CSV whose header row is the template's
source columns — the artifact handed to a customer for the export→upload path, or the target
shape of their Google Sheet. Served by a brand-scoped tRPC procedure resolving the template
under the caller's org (never a bare uuid route); emits HEADERS ONLY (no sample values — a
template's constant/enum internals stay server-side).
D5 — Binding UX: pick or create a mapping template in place, previewed on real cells
- The google-sheets binding editor gains, per binding row, an optional "Mẫu ánh xạ cột"
picker: the org's template lineages filtered to the binding's
targetStream, labeled with the active version. Per-template usage-count labels in the picker are DEFERRED (revisit when orgs hold enough lineages for it to matter); instead, saving a new version of a lineage that live bindings reference surfaces a post-save notice ("N liên kết sẽ dùng phiên bản mới từ lần đồng bộ tới").connectors.updateConfig's binding input gainsmappingTemplateId— without this the wholesale-replace mutation would silently strip saved template ids on every config edit. - "Tạo mẫu mới" opens the EXISTING template wizard extracted into a dialog (prefill props:
target stream, sniffed headers, default
source_kind; anonCreated(templateId)callback sets the picker — no page navigation, no second wizard). - New endpoint
connectors.sniffSheetRange(brand-scoped): decrypts the connector's stored credential SERVER-side, reads the first ~6 rows of the binding's range, returns{headers, sampleRows}.sheetTitlesfrom the driver's ping (already returned, currently discarded byconnector-ping.ts) are plumbed to the binding editor for tab pickers — finishing ADR 0014 D5. Preview-before-save runs the chosen/created template against those REAL tab cells (same render mode as sync, per D2) — this is the authoring-time guard that catches sheet-locale vs template-separator mismatch. - Sheet-origin templates default
source_kindtosheet_<targetStream>(editable, follows theimports.tsconvention). The wizard warns before archiving a lineage that live bindings reference. All new/relocated copy goes throught()(vi source of truth, §5/§62); the exposed source-kind field is labeled "Loại nguồn dữ liệu".
D6 — Reusability closes through ADR 0015 + an explicit pack upgrade contract
Dashboards/report templates already bind to pillar metrics and dataset registries over
canonical tables — once a customer's data is mapped (by ANY transport), existing dashboard
templates render without modification. A "domain pack" = org blueprint (plugins + dashboard
templates, applyOrgBlueprint) + system-managed default mapping templates + this ADR's
binding UX. The previously-undefined fleet rules, now explicit:
- A pack/system upgrade publishes version N+1 of a lineage ONLY while the head is still
is_system_managed: true. A customer edit flips the lineage to customer-owned (upsertVersionalready writesisSystemManaged: false) — that takeover is ONE-WAY and the platform never overwrites a customer-owned head. - Pack application is idempotent and iterates every org by default (
ORG_IDpins one, §28). - A template qualifies as a pack default only if its spec contains NO customer-specific
constants or customer-derived identifiers — e.g. the YNM seed baking
constant(LINKEDIN_ORG_URN)must never be cloned to another org (it would fabricate another customer's identifiers into silver, §32). Review before promotion to a pack.
Non-goals
- Per-customer custom fields, EAV, or schema-on-read ON CONNECTOR CANONICAL STREAMS — variability lives in mappings; a field two customers need becomes a NULLABLE canonical field via a product release (§32: unmapped → NULL, never fabricated). Scope amended 2026-09-03: a tenant's own vocabulary as typed, versioned, server-validated catalog rows is a different thing and is allowed — ADR 0023 made that exception for content dimensions, and the same split (shared semantics compile, tenant vocabulary is data) governs tenant numeric datasets (HR, finance) so a new department does not need a new org type or a release.
- LLM-suggested auto-mapping (future; the spec model is the right substrate).
- Excel (.xlsx) template generation — CSV headers first.
- Migrating the three fixed product header maps to templates — they are correct, tested code for FIXED vendor exports.
- A distinct
source:'sheet'discriminator (deferred, see D2).
Consequences#
- Onboarding customer N with a different export shape = create/adjust ONE mapping template in the UI — identical effort whether they upload files or connect a sheet; zero code.
- The parity gate turns "two ingest fronts, one behavior" from a comment into a test; any
future transport (SFTP drop, email attachment, API push of tabular rows) must join the same
contract: rows →
applyTemplate→STREAM_SCHEMAS→ sink. - Sheet syncs become auditable per binding (
stream_accounting: template id + version + capped, PII-safe reject samples), and mapping edits roll forward without touching connector config. - The worker gains one RLS-scoped template read per sheets sync, before driver I/O (§66).
- Known accepted asymmetries, stated not hidden: upload pins an exact version at action time
while sheets follow the lineage head; template-mapped sheet rows keep each sink's existing
sourcesemantics until a real mixed-transport customer forces the split.