Skip to content
MSO CloudDocumentation

Warehouse schema — bảng và RLS

On this page

Sinh tự động bởi scripts/docs/generate-warehouse-schema.ts từ drizzle defs (packages/schema/src/tables) + packages/schema/sql/rls-policies.sql. Không sửa tay — chạy lại script rồi pnpm tsx scripts/docs-to-html.ts --only=docs/architecture/reference/warehouse-schema.md.

Postgres 19 multi-tenant theo medallion architecture. 280 bảng, nhóm theo bronze/silver/marketing/gold + bốn plane chuyên biệt (MSO, Market Intelligence, Social, Content Intelligence) + admin. Cột "Cột chính" bỏ qua boilerplate (id, org_id, brand_id, is_sample, created_at, updated_at, refreshed_at) và cắt ở 8 cột đầu.

Tenancy & RLS#

Tenancy là org → brand (invariant #1): một khách hàng = một org, fact/asset tables mang cả org_id lẫn brand_id. Truy vấn org-scoped đi qua orgProcedure (brand-partitioned: brandProcedure) trong apps/web/src/server/trpc.ts — mỗi resolver chạy trong runWithRlsContext (packages/schema/src/rls-context.ts): mở transaction, pin GUC app.current_org_id/app.current_brand_id transaction-local trên đúng một connection, rồi route mọi query của request lên transaction đó. Policy phía Postgres đọc GUC qua helper app_current_org()/app_current_brand() (GUC rỗng → deny). Cơ chế được kiểm chứng bằng scripts/audit/rls-context-effective.ts.

Các cohort trong packages/schema/sql/rls-policies.sql:

Cohort Policy Số bảng
org_only_tables org_scope_*: org_id = app_current_org() 104
brand_partitioned_tables org_brand_scope_*: thêm predicate brand (row brand_id NULL / không có brand context / khớp context) 146
auth_process_tables yng_auth với process attestation 7
identity_metadata_tables Đọc metadata; ghi theo process hoặc tenant attestation 3

Brand authz chính nằm ở app-layer (org_memberships.viewable_brand_ids); RLS là lưới an toàn. Lưu ý vận hành: RLS chỉ bind khi app connect bằng role không SUPERUSER/BYPASSRLS — role superuser bỏ qua cả FORCE ROW LEVEL SECURITY (đánh giá mso-14, mục C4). Ngoài RLS có chủ đích (ghi chú cuối rls-policies.sql, enforce bằng Drizzle helper ở app-layer): notification_channel_configs, platform_ai_connections, platform_connector_credentials, platform_connector_runs, platform_connector_state, push_subscriptions, shared_trend_history, shared_trend_items, shared_trend_review_decisions, site_settings, site_themes, user_channel_identities. audit_logs có thêm policy riêng: cấm UPDATE, DELETE chỉ cho rotation quá cửa sổ 90 ngày.

Đối chiếu RLS (giá trị audit của doc)

Tại thời điểm sinh doc: 0 bảng thiếu RLS — mọi bảng có org_id đều nằm trong một cohort hoặc được ghi chú app-layer có chủ đích.

Mục có trong rls-policies.sql nhưng KHÔNG còn trong drizzle schema (stale — dọn khi chạm file):

  • content_month
  • content_year
  • creator_detail
  • shop_detail

Bronze — landing, staging & mặt phẳng sync#

Payload nguồn ghi VERBATIM (§44) + hàng đợi sync/connector. Stream không canonical đi vào import_staging_rows, không vào raw_events (§17).

Bảng Cột chính org_id brand_id is_sample RLS
connector_backfill_runs connector_id, streams, since, until, status, slices_total, slices_done, slices_failed … (+4) ✓ ✓ ✓ RLS org+brand
connector_credentials connector_type, kind, label, credentials_ciphertext, credentials_iv, credentials_tag, key_version, org_credential_id … (+15) ✓ ✓ ✓ RLS org+brand
connector_watermarks connector_id, connector_type, stream_name, last_cursor, high_water_mark, last_success_at, last_backfill_at, rows_ingested_total ✓ — — RLS org
import_mapping_templates source_kind, target_stream, version, name, spec, is_active, is_system_managed, archived_at … (+1) ✓ ✓ — RLS org+brand
import_staging_rows template_id, template_version, upload_job_id, target_stream, source_kind, row_index, source_payload, normalized_payload … (+4) ✓ ✓ — RLS org+brand
manual_upload_jobs uploaded_by, connector_id, import_template_id, upload_type, filename, extension, byte_length, storage_ref … (+10) ✓ ✓ ✓ RLS org+brand
org_credentials credential_type, label, credentials_ciphertext, credentials_iv, credentials_tag, key_version, fingerprint, is_active … (+1) ✓ ✓ ✓ RLS org+brand
platform_shop_aliases platform, raw_shop_id, canonical_shop_id ✓ — ✓ RLS org
platform_shops platform, canonical_shop_id, display_name ✓ ✓ ✓ RLS org
raw_events connector_id, connector_type, stream_name, external_id, payload, payload_hash, source_batch_id, ingested_at … (+3) ✓ ✓ ✓ RLS org+brand
sync_dead_letters job_id, connector_id, connector_type, queue, job_type, payload, error_code, error_message … (+4) ✓ — — RLS org
sync_jobs connector_id, connector_type, job_type, status, rows_processed, rows_upserted, rows_rejected, error_code … (+7) ✓ — ✓ RLS org
sync_rejected_rows job_id, connector_type, stream_name, row_number, external_id, reason_code, reason_message, raw_row ✓ — ✓ RLS org

Silver — thực thể nghiệp vụ canonical (1st-party)#

Fact/entity đã chuẩn hoá theo platform-agnostic model — nguồn của mọi KPI 1st-party. Tiền tệ là VND integer (§2); NMV luôn đọc từ orders.nmv_blo_vnd, breakdown chỉ ALLOCATE (không tự cộng lại).

Bảng Cột chính org_id brand_id is_sample RLS
ad_spend_daily platform, account_external_id, campaign_external_id, campaign_name, day, spend_vnd, impressions, clicks … (+13) ✓ ✓ ✓ RLS org+brand
affiliate_order_lines connector_id, platform, platform_order_id, order_create_time, sku_id, product_id, quantity, price_vnd … (+15) ✓ ✓ ✓ RLS org+brand
budget_plans period, year, bucket, platform, channel, planned_spend_vnd, planned_gmv_vnd, planned_orders … (+1) ✓ ✓ ✓ RLS org+brand
categories name, slug, is_active ✓ — ✓ RLS org
category_platform_mappings category_id, platform, platform_category_id, platform_category_name, last_seen_at ✓ — ✓ RLS org
creator_costs creator_id, cost_type, amount_vnd, occurred_on, notes ✓ ✓ ✓ RLS org+brand
creator_performance_daily creator_id, platform, day, impressions, clicks, orders_count, gmv_vnd, cancellation_rate_bp ✓ ✓ ✓ RLS org+brand
creator_platform_mappings creator_id, platform, platform_creator_id, platform_handle ✓ ✓ ✓ RLS org+brand
creator_platform_profiles creator_id, platform, platform_creator_id, platform_handle, display_name, bio_description, avatar_url, profile_uri … (+28) ✓ ✓ ✓ RLS org
creators canonical_name, canonical_handle, notes, tier, followers_count, engagement_rate_bp, contract_type, default_commission_bp ✓ ✓ ✓ RLS org+brand
customer_cases shopper_id, order_id, kind, severity, status, platform, source_ref, title … (+9) ✓ — ✓ RLS org
engagement_events event_type, platform, shopper_id, creator_id, product_id, campaign_id, occurred_at, payload … (+1) ✓ — ✓ RLS org
inventory_snapshots product_id, snapshot_date, source_shop, quantity_on_hand, quantity_reserved, expiry_date, raw_event_id, source_batch_id ✓ ✓ ✓ RLS org+brand
live_session_metrics platform, platform_session_id, creator_id, campaign_id, started_at, ended_at, viewers, peak_viewers … (+5) ✓ — ✓ RLS org
live_sessions connector_id, platform, platform_session_id, title, creator_platform_id, started_at, ended_at, gmv_vnd … (+14) ✓ ✓ ✓ RLS org+brand
order_items order_id, product_id, platform_sku_id, quantity, unit_price_vnd, promo_code, unit_cogs_vnd_snapshot, list_price_vnd … (+3) ✓ ✓ ✓ RLS org+brand
orders platform, platform_shop_id, platform_order_id, status, gmv_vnd, nmv_vnd, nmv_blo_vnd, nmv_returned_vnd … (+18) ✓ ✓ ✓ RLS org+brand
org_dataset_field_values dataset_id, field_id, value_key, label_vi, label_en, sort_index, parent_value_key, status ✓ — ✓ RLS org
org_dataset_record_dims dataset_id, record_id, dim_key, value_key ✓ ✓ ✓ RLS org+brand
org_dataset_record_measures dataset_id, record_id, measure_key, value_int ✓ ✓ ✓ RLS org+brand
org_dataset_records dataset_id, source_id, record_external_id, grain_key, period_month, schema_version ✓ ✓ ✓ RLS org+brand
payout_lines platform, platform_shop_id, payout_batch_id, platform_order_id, order_id, payout_date, expected_payout_vnd, actual_payout_vnd … (+4) ✓ ✓ ✓ RLS org+brand
platform_sku_map product_id, platform, platform_shop_id, platform_sku_id, platform_product_name, platform_variant_id, last_price_vnd, last_price_seen_at … (+1) ✓ — ✓ RLS org
po_lines po_id, product_id, sku_code, quantity_ordered, quantity_received, unit_cost_vnd ✓ ✓ ✓ RLS org+brand
price_history product_id, platform, platform_shop_id, platform_sku_id, price_vnd, observed_at, source ✓ — ✓ RLS org
product_platform_mappings product_id, platform, platform_shop_id, platform_sku_id, platform_product_id, platform_product_name, platform_variant_id, list_price_vnd … (+4) ✓ ✓ ✓ RLS org+brand
products canonical_name, canonical_sku_code, barcode_ean, brand, category, category_override_at, category_override_reason, unit_size … (+2) ✓ ✓ ✓ RLS org+brand
purchase_orders supplier_id, status, po_number, total_vnd, ordered_on, expected_on, received_on, notes ✓ ✓ ✓ RLS org+brand
reconciliation_runs assertion, severity, passed, summary, details, run_at ✓ — ✓ RLS org
service_events case_id, event_type, actor_user_id, payload, occurred_at ✓ — ✓ RLS org
settlement_transactions connector_id, platform, external_id, statement_id, platform_order_id, transaction_type, fee_type, currency … (+7) ✓ ✓ ✓ RLS org+brand
shopper_identity_links shopper_id, platform, platform_shop_id, platform_buyer_id, confidence ✓ — ✓ RLS org
shoppers display_name, phone_hash, email_hash, consent_marketing, consent_updated_at, first_seen_at, last_seen_at ✓ — ✓ RLS org
sku_brand_rules sku_code, brand ✓ — ✓ RLS org
sku_category_rules sku_code, category_id ✓ — ✓ RLS org
sku_mapping_rules rule_type, pattern, target_product_id, priority, metadata, created_by ✓ — ✓ RLS org
sla_definitions kind, severity, target_minutes, escalate_after_minutes, is_active ✓ — ✓ RLS org
source_split_daily connector_id, canonical_shop_id, platform, day, source, gmv_vnd, orders_count, units_sold … (+2) ✓ ✓ ✓ RLS org+brand
targets period, year, quarter, month, platform, metric, target_value ✓ ✓ ✓ RLS org+brand
video_performance connector_id, platform, platform_video_id, title, creator_platform_id, posted_at, metric_date, gmv_vnd … (+7) ✓ ✓ ✓ RLS org+brand
video_product_performance connector_id, platform, platform_video_id, platform_product_id, platform_sku_id, product_name, metric_date, gmv_vnd … (+4) ✓ ✓ ✓ RLS org+brand

Marketing — mặt phẳng 1st-party ads/web/search/CRM (ADR 0008)#

Chi phí quảng cáo / web / search / CRM của chính nhà bán — 1st-party nhưng TÁCH khỏi silver marketplace (ADR 0008). KHÔNG đi qua market_intel_*, KHÔNG vào MARKET_CHAT_TOOLS (§58); Measure Spine vẫn chỉ validate trên orders (§60d) — conversions platform-ghi-nhận không phải orders, MER/CAC blended trên orders.

Bảng Cột chính org_id brand_id is_sample RLS
business_kpi_facts source, period_year, data_type, metric_group, metric_key, value_vnd, value_int, raw_label … (+1) ✓ ✓ ✓ RLS org+brand
crm_deals connector_id, provider, deal_external_id, title, pipeline_id, stage_id, stage_semantic, opportunity_vnd … (+14) ✓ ✓ ✓ RLS org+brand
crm_leads connector_id, provider, lead_external_id, title, status_id, status_semantic, source_id, opportunity_vnd … (+15) ✓ ✓ ✓ RLS org+brand
crm_stage_events connector_id, provider, entity_kind, entity_external_id, from_stage_id, to_stage_id, moved_at_source, raw_payload ✓ ✓ ✓ RLS org+brand
email_campaign_daily connector_id, provider, campaign_external_id, campaign_name, subject, day, is_lifetime, sends … (+13) ✓ ✓ ✓ RLS org+brand
email_transactional_event connector_id, provider, event, event_at, event_day, recipient_email, from_email, subject … (+7) ✓ ✓ ✓ RLS org+brand
kpi_targets metric_key, budget_line_key, budget_line_label, ad_platform, period_start, period_end, target_value, include_in_total … (+1) ✓ ✓ ✓ RLS org+brand
marketing_campaign_registry campaign_key, display_name, platform, year, objective, fb_external_ids, ga4_landing_page_patterns, ga4_hostnames … (+3) ✓ ✓ ✓ RLS org+brand
marketing_stream_cutovers stream, api_cutover_day ✓ — ✓ RLS org
plan_line_actuals source_kind, source_id, value_num, as_of_day, note, entered_by, entered_at ✓ ✓ ✓ RLS org+brand
plan_line_bindings source_kind, source_id, metric_slug, dimension_filter, status, confidence_bp, rationale, suggested_by … (+4) ✓ ✓ ✓ RLS org+brand
search_console_page_daily connector_id, site_url, day, page_url, clicks, impressions, ctr_bp, position_milli … (+1) ✓ ✓ ✓ RLS org+brand
search_console_query_daily connector_id, site_url, day, query, clicks, impressions, ctr_bp, position_milli … (+1) ✓ ✓ ✓ RLS org+brand
search_console_site_daily connector_id, site_url, day, clicks, impressions, ctr_bp, position_milli, raw_payload … (+1) ✓ ✓ ✓ RLS org+brand
social_page_daily connector_id, platform, page_external_id, page_name, day, followers_total, followers_organic_new, followers_paid_new … (+11) ✓ ✓ ✓ RLS org+brand
social_post_performance connector_id, platform, post_external_id, page_external_id, title, content, post_type, permalink … (+19) ✓ ✓ ✓ RLS org+brand
web_analytics_daily connector_id, property_external_id, day, channel_group, sessions, total_users, new_users, engaged_sessions … (+4) ✓ ✓ ✓ RLS org+brand
web_analytics_page_period connector_id, property_external_id, hostname, landing_page, traffic_slice, period_type, period_start, period_end … (+9) ✓ ✓ ✓ RLS org+brand
web_analytics_property_daily connector_id, property_external_id, traffic_slice, day, views, sessions, total_users, new_users … (+7) ✓ ✓ ✓ RLS org+brand
web_analytics_property_period connector_id, property_external_id, traffic_slice, period_type, period_start, period_end, views, sessions … (+4) ✓ ✓ ✓ RLS org+brand
web_analytics_source_period connector_id, property_external_id, source_medium, traffic_slice, period_type, period_start, period_end, sessions … (+5) ✓ ✓ ✓ RLS org+brand

Gold — dim / fct / agg / pred phục vụ dashboard#

Rollup/forecast do refreshOrgMaterializations (packages/metrics/src/materialize.ts) sinh — không ghi tay. Metric thiếu dữ liệu thật phải render — + mode, không fake 0/multiplier (§32/§35).

Bảng Cột chính org_id brand_id is_sample RLS
action_memos period_start, period_end, status, title, summary, recommendations, citations, tokens_used … (+3) ✓ — ✓ RLS org
agg_content_dim_total dataset_id, grain, grain_key, dim_key, value_key, platform_slug, mention_count, label_instances … (+2) ✓ ✓ ✓ RLS org+brand
agg_org_campaign campaign_id, gmv_vnd, orders_count, spend_vnd, unique_shoppers, source_watermark ✓ ✓ ✓ RLS org+brand
agg_org_creator_day creator_id, day, gmv_vnd, orders_count, impressions, clicks, cost_vnd, source_watermark ✓ ✓ ✓ RLS org+brand
agg_org_dataset_period dataset_id, period_month, dim_key, value_key, measure_key, scenario, version, schema_version … (+2) ✓ ✓ ✓ RLS org+brand
agg_org_day day, platform, gmv_vnd, nmv_vnd, nmv_blo_vnd, nmv_returned_vnd, orders_count, cancelled_count … (+7) ✓ ✓ ✓ RLS org+brand
agg_org_shopper_month shopper_id, month, orders_count, gmv_vnd, source_watermark ✓ ✓ ✓ RLS org+brand
agg_org_sku_day sku_id, day, units_sold, gmv_vnd, cogs_vnd, stockout_minutes, source_watermark ✓ ✓ ✓ RLS org+brand
anomalies metric_slug, severity, summary, detected_at, resolved_at, details, model_version ✓ — ✓ RLS org
audience_definitions name, description, dsl, refresh_cadence, last_refreshed_at, last_member_count, is_active, created_by ✓ — ✓ RLS org
audience_memberships audience_id, shopper_id, entered_at, exited_at, snapshot_payload ✓ — ✓ RLS org
audience_refresh_runs audience_id, triggered_by, candidates_seen, entered_count, exited_count, duration_ms, status, error_message … (+1) ✓ — ✓ RLS org
category_benchmarks category_slug, metric_slug, period_start, period_end, value_raw, peer_p25, peer_p50, peer_p75 … (+4) ✓ — ✓ RLS org
dim_brand name, slug, parent_brand_id ✓ — ✓ RLS org
dim_campaign name, platform, start_at, end_at, budget_vnd ✓ ✓ ✓ RLS org+brand
dim_category name, path, depth ✓ — ✓ RLS org
dim_location code, name, kind, region_vn ✓ — ✓ RLS org
dim_product product_id, dim_brand_id, category_id, display_name ✓ ✓ ✓ RLS org+brand
dim_sku product_id, sku_code, cogs_vnd, reorder_point, safety_stock, lead_time_days ✓ ✓ ✓ RLS org+brand
dim_supplier name, contact_email, lead_time_days ✓ — ✓ RLS org
fct_inventory_movement product_id, location_id, movement_type, quantity_delta, reason, reference_type, reference_id, occurred_at ✓ ✓ ✓ RLS org+brand
fct_order_touch order_id, shopper_id, touch_rank, touch_type, creator_id, campaign_id, placement, credit_bp … (+4) ✓ — ✓ RLS org
holiday_dim holiday_date, code, label_vi, label_en, sale_theme, is_major_sale ✓ — ✓ RLS org
pred_creator_score creator_id, score, reasons, model_version, generated_at ✓ — ✓ RLS org
pred_product_affinity product_a_id, product_b_id, affinity, support, model_version, generated_at ✓ — ✓ RLS org
pred_shopper_clv shopper_id, clv_vnd, clv_p90_vnd, churn_prob_bp, horizon_days, model_version, generated_at ✓ — ✓ RLS org
pred_sku_demand_daily sku_id, day, predicted_units, confidence_low, confidence_high, model_version, generated_at ✓ ✓ ✓ RLS org+brand

MSO — vòng học off-take (Marketing Systems OS)#

Ba lớp dữ liệu của vòng học: buzz 3rd-party (social_signal_daily) → Marketing Memory (offtake_models) → Decision Memory (decisions/decision_outcomes). Toán học chỉ ở packages/metrics/src/offtake.ts; persist chỉ từ packages/metrics/src/offtake-loop.ts (§60). Quan hệ chi tiết: mục "Decision Memory (MSO)" bên dưới.

Bảng Cột chính org_id brand_id is_sample RLS
action_commands kind, source, connector_type, connector_id, idempotency_key, status, requires_approval, approval_policy … (+8) ✓ — ✓ RLS org
briefing_runs cadence, run_date, outcome, reason, duration_ms, docs, recorded_at ✓ — ✓ RLS org
decision_approval_requests decision_id, episode_id, playbook_id, playbook_version, proposal_kind, policy_version_id, policy_version, payload … (+11) ✓ ✓ ✓ RLS org+brand
decision_episodes decision_id, trace_id, run_ref, step_index, parent_step_index, event_kind, actor_kind, actor_user_id … (+37) ✓ ✓ ✓ RLS org+brand
decision_outcomes decision_id, measured_value, expected_value, incremental_value, variance_bp, verdict, lesson_text, calibration_bucket … (+7) ✓ ✓ ✓ RLS org+brand
decisions decision_date, evaluation_date, execution_start_date, executed_at, evaluation_horizon_days, campaign_label, lever, context_snapshot … (+12) ✓ ✓ ✓ RLS org+brand
experiment_assignments action_command_id, subject_type, subject_key, arm, holdout_bp, observed_lift_bp, confidence_bp, measured_at ✓ — ✓ RLS org
experiments decision_id, type, design_note, metric_slug, window_start, window_end, treatment_value, control_value … (+27) ✓ ✓ ✓ RLS org+brand
mso_playbooks slug, version, status, title, purpose, region, trigger, when_to_use … (+9) ✓ ✓ ✓ RLS org+brand
offtake_models channel, variant_scope, lever, corr_rank_bp, lead_days, discount_cap_bp, confidence_bp, n_weeks … (+3) ✓ ✓ ✓ RLS org+brand
playbook_stats playbook_id, playbook_version, segment_key, matched_count, proposed_count, approved_count, rejected_count, abstained_count … (+15) ✓ ✓ ✓ RLS org+brand
policy_models domain, lever, mean_bp, var_bp2, n_obs, method ✓ ✓ ✓ RLS org+brand
policy_versions policy_kind, version, status, parent_version, config, label, evaluation_episode_id, gate_verdict … (+4) ✓ ✓ ✓ RLS org+brand
signal_events domain, plane, signal_key, measure_address, type, severity, impact_bp, rank_score … (+16) ✓ ✓ ✓ RLS org+brand
signal_stats domain, signal_key, fired_count, dismissed_count, acted_count, last_fired_at, last_dismissed_at, weight_bp … (+1) ✓ ✓ ✓ RLS org+brand
signal_values signal_name, signal_version, grain, period_start, entity_key, value_int, computed_at ✓ ✓ ✓ RLS org+brand
signals name, grain, tier, unit, label, description, sql_ref, version … (+1) ✓ ✓ ✓ RLS org+brand
social_signal_daily platform, source, metric_type, value, day ✓ ✓ ✓ RLS org+brand

Decision Memory (MSO)

Vòng học off-take ghi lại TOÀN BỘ chu trình Signal → Recommendation → Decision → Outcome → Lesson để chu kỳ sau sắc hơn (ADR 0004, CLAUDE.md §60). Quan hệ giữa các bảng:

social_signal_daily ──(fit hàng tuần: offtake-loop.ts)──▶ offtake_models
  buzz 3rd-party,                                           Marketing Memory: lever thắng,
  1 row / (brand, metric_type, ICT day)                     corr/confidence (basis points), mode

offtake_models ──(proposals: so SỐ với ngưỡng)──▶ decisions ──(approve)──▶ action_commands
                                                    │  natural key (org, brand,      lệnh hành động,
                                                    │  decision_date, campaign_label) idempotency_key
                                                    │                                      ▲
                                                    │                        experiment_assignments
                                                    │                        (treatment/holdout theo
                                                    │                         action_command_id)
                                          (measure: orders 1st-party)
                                                    ▼
                                            decision_outcomes  ←── 1–1 với decisions
                                            verdict + lesson       (unique decision_id)
  • social_signal_daily — tín hiệu đầu vào: buzz SocialHeat unpivot wide→long, 1 row / (brand, platform social-agg, metric_type, ngày ICT). Giá trị thô ghi verbatim (§44); winsorize chỉ tại thời điểm fit. Dữ liệu 3rd-party — không bao giờ nuôi KPI 1st-party (§60d).
  • offtake_models — Marketing Memory: model đã học, 1 row / (org, brand, channel, variant_scope), upsert theo natural key. lever thắng + corr_rank_bp/confidence_bp (basis points ×10000, không float — §2), lead_days (buzz dẫn GMV ~1 tuần), per_lever (map corr đầy đủ cho heatmap), mode gate trung thực: act / learning (<20 tuần) / no_reliable_signal (|corr| < 0.30 → render —, không bịa lift). Fit chạy ở worker (apps/worker/src/processors/offtake.ts), toán học thuần trong packages/metrics/src/offtake.ts (test với oracle đóng băng sim/decision_log.json).
  • decisions — Decision Memory: 1 row / quyết định, natural key (org, brand, decision_date, campaign_label). context_snapshot đóng băng NHỮNG GÌ vòng học biết lúc đề xuất (corr, confidence, số tuần, playbook selection trace); options là bảng trade-off; chosen + rationale (AI-draft, PCN-gated) là lựa chọn. Hợp đồng đo lường nằm ngay trên row: expected_outcome {metric_slug, target, horizon} + validation_metric_slug. Lifecycle status: proposed → approved → activated → measured, cùng abstained/learning (hệ tự kiềm) và rejected (owner bỏ qua). Duyệt là hành động RBAC-gated: chỉ owner/org admin (requireOwnerOrOrgAdmin trong offtake router), stamp approved_by/approved_at + bản ghi append-only audit_logs (mso.decision.approve). Ngày chạy thật tách khỏi ngày duyệt: execution_start_date neo cửa sổ đo, evaluation_date = ngày hẹn đối chiếu (ICT, §41).
  • action_commands — lệnh hành động cụ thể (kind: launch_flash_sale, reprice_sku, …) với requires_approval/approved_by và idempotency_key. decisions.linked_action_ids (uuid[], không FK cứng) trỏ tới các lệnh sinh ra khi duyệt. experiment_assignments chia subject vào arm treatment/holdout theo action_command_id — nguồn của incremental_value.
  • decision_outcomes — phán quyết của Measure Spine, 1–1 với decisions (unique decision_id, re-review update tại chỗ). Đo bằng ĐÚNG metric đã cam kết trong validation_metric_slug (gmv_vnd → SUM, orders → COUNT, aov → SUM/COUNT) trên orders 1st-party trong cửa sổ [execution_start_date, evaluation_date] ICT — measureActualForMetric đọc số, measureActivatedDecisions (offtake-loop.ts) quét các decision đang chạy. variance_bp có MỘT định nghĩa duy nhất: computeOutcomeVerdict (packages/metrics/src/offtake.ts) — mọi writer gọi nó, không re-derive. verdict máy đề xuất (hit/partial/miss/abstain/learning) chỉ thành CHÍNH THỨC khi owner xác nhận (confirmed_verdict/confirmed_by/confirmed_at); bài học cũng hai tầng — lesson_text là draft máy, confirmed_lesson mới là tri thức được nạp vào hệ. calibration_bucket nuôi card track-record ("hệ nói X% → đúng ~Y%").
  • mso_playbooks — thư viện playbook ngành EDITABLE (org-scoped, seed từ packages/metrics/src/mso-playbooks.ts). slug khớp id trong metrics để context_snapshot.selection.playbookId của decision join ngược về record — selection là code so SỐ với ngưỡng; when_to_use chỉ là biên nhận text, không tham gia tính toán.

Mọi con số của vòng học reconcile trong scripts/audit/data-reconciliation.ts (#14a/b/c, verify:data) với expected neo vào oracle đóng băng — không re-derive trong code (§53/§55).

Market Intelligence — estimate plane 3rd-party#

Ước lượng thị trường từ nguồn 3rd-party (white-label "MK Commerce"). KHÔNG BAO GIỜ join vào orders/NMV (§32/§35) và nằm ngoài verify:data theo chủ đích (§57) — guard bằng e2e/unit.

Bảng Cột chính org_id brand_id is_sample RLS
market_intel_categories snapshot_id, name, level, cate_id, revenue_vnd, growth_bp, shop_count, avg_shop_revenue_vnd … (+9) ✓ ✓ ✓ RLS org+brand
market_intel_competitors platform, shop_name, seller_type, main_category, source, status, score_bp, reasons … (+2) ✓ ✓ ✓ RLS org+brand
market_intel_content_month_ranks snapshot_id, kind, external_id, rank, external_creator_id, creator_handle, title, revenue_vnd … (+15) ✓ ✓ ✓ RLS org+brand
market_intel_content_session_products snapshot_id, kind, session_external_id, rank, external_product_id, product_title, revenue_vnd, units_sold … (+9) ✓ ✓ ✓ RLS org+brand
market_intel_content_sessions snapshot_id, kind, external_id, annual_rank, creator_handle, title, list_revenue_vnd, monthly_list_revenue … (+20) ✓ ✓ ✓ RLS org+brand
market_intel_creator_lives snapshot_id, external_creator_id, external_live_id, creator_handle, started_at, finished_at, title, duration_seconds … (+8) ✓ ✓ ✓ RLS org+brand
market_intel_creator_products snapshot_id, external_creator_id, external_product_id, external_shop_id, product_title, revenue_vnd, units_sold, avg_unit_price_vnd … (+1) ✓ ✓ ✓ RLS org+brand
market_intel_creator_profiles platform, handle, display_name, creator_type_override, override_set_by, override_set_at, override_note, demographics … (+2) ✓ ✓ ✓ RLS org+brand
market_intel_creator_shops snapshot_id, external_creator_id, external_shop_id, shop_name, seller_type, revenue_vnd, units_sold, live_revenue_vnd … (+3) ✓ ✓ ✓ RLS org+brand
market_intel_creator_summaries snapshot_id, external_creator_id, handle, display_name, vendor_creator_type, capture_batch, revenue_vnd, live_revenue_vnd … (+11) ✓ ✓ ✓ RLS org+brand
market_intel_creator_videos snapshot_id, external_creator_id, external_video_id, creator_handle, posted_at, description, duration_seconds, views … (+13) ✓ ✓ ✓ RLS org+brand
market_intel_creators snapshot_id, display_name, handle, followers, revenue_vnd, units_sold, avg_unit_price_vnd, engagement_bp … (+22) ✓ ✓ ✓ RLS org+brand
market_intel_lives snapshot_id, title, creator_handle, started_at, finished_at, record_type, duration_seconds, revenue_vnd … (+7) ✓ ✓ ✓ RLS org+brand
market_intel_load_receipts ingest_batch, source, platform, file_name, target_table, manifest_rows, manifest_sha256, spec_sha256 … (+6) ✓ ✓ ✓ RLS org+brand
market_intel_product_labels platform, external_product_id, kind, value, rule, confidence_bp, source, dictionary_version … (+3) ✓ ✓ ✓ RLS org+brand
market_intel_products snapshot_id, name, image_url, category_path, price_min_vnd, price_max_vnd, shipping_fee_vnd, listed_at … (+20) ✓ ✓ ✓ RLS org+brand
market_intel_settings comparison_basis, demo_mask, insight_language, insight_model, insight_business_context, insight_prompt_overrides, insight_shared_rules, insight_font_scale … (+7) ✓ — ✓ RLS org
market_intel_shop_creators snapshot_id, external_shop_id, external_creator_id, handle, display_name, vendor_creator_type, rank_in_shop, is_shop_own_account … (+6) ✓ ✓ ✓ RLS org+brand
market_intel_shop_lives snapshot_id, external_shop_id, external_live_id, creator_handle, rank_in_shop, started_at, finished_at, title … (+5) ✓ ✓ ✓ RLS org+brand
market_intel_shop_products snapshot_id, external_shop_id, external_product_id, product_title, rank_in_shop, revenue_vnd, units_sold, alloc_segment … (+2) ✓ ✓ ✓ RLS org+brand
market_intel_shop_summaries snapshot_id, external_shop_id, shop_name, seller_type, crawl_scope, rank_365, rank_powder, revenue_vnd … (+29) ✓ ✓ ✓ RLS org+brand
market_intel_shop_videos snapshot_id, external_shop_id, external_video_id, external_creator_id, creator_handle, rank_in_shop, posted_at, description … (+7) ✓ ✓ ✓ RLS org+brand
market_intel_shops snapshot_id, name, seller_type, revenue_vnd, units_sold, avg_unit_price_vnd, live_revenue_vnd, video_revenue_vnd … (+9) ✓ ✓ ✓ RLS org+brand
market_intel_snapshots source, platform, dataset, transport, scope_shop_name, scope_category_name, scope_keyword, scope_filters … (+11) ✓ ✓ ✓ RLS org+brand
market_intel_videos snapshot_id, title, duration_seconds, creator_handle, posted_at, revenue_vnd, units_sold, product_title … (+9) ✓ ✓ ✓ RLS org+brand
market_intel_watched_creators platform, handle, display_name, source, status, score_bp, note, added_by_user_id ✓ ✓ ✓ RLS org+brand

Social Intelligence — SocialHeat estimate plane#

Report metrics social (demand topics / SOV / trajectory / needs) — cùng kỷ luật 3rd-party như Market Intelligence: không trộn vào KPI 1st-party. Bao gồm cả nhánh SocialHeat social-listening (đa đối thủ, org-scoped) lẫn SocialTrend/SocialHeat market-intel sheet-fed (ADR 0014 D4).

Bảng Cột chính org_id brand_id is_sample RLS
shared_trend_history connector, window, cycle_at, vendor_id, origin, rank, name, passion_point … (+7) — — — global (không có org_id)
shared_trend_items connector, vendor_id, origin, name, passion_point, status, is_new, detected_at … (+17) — — — global (không có org_id)
shared_trend_review_decisions connector, vendor_id, title_key, title, decision, reason, decided_by, decided_at — — — global (không có org_id)
social_intel_brands snapshot_id, competitor_name, is_self, mentions, sov_bp, sent_pos_bp, sent_neu_bp, sent_neg_bp ✓ ✓ ✓ RLS org+brand
social_intel_snapshots source, platform, category_name, range_start, range_end, is_estimate, captured_at ✓ ✓ ✓ RLS org+brand
social_intel_topic_months snapshot_id, topic, month, mentions, evidence_rate_bp, breadth_authors, organic_share_bp ✓ ✓ ✓ RLS org+brand
social_intel_topics snapshot_id, kind, topic, mentions, growth_bp, sent_pos_bp, sent_neu_bp, sent_neg_bp … (+1) ✓ ✓ ✓ RLS org+brand
social_listening_brand_daily source, tracked_brand, day, discussions, posts, comments, shares ✓ — ✓ RLS org
social_listening_platform_daily source, tracked_brand, platform, day, discussions ✓ — ✓ RLS org
social_listening_top_items source, period_start, kind, rank, label, url, source_name, discussions … (+1) ✓ — ✓ RLS org
social_mentions source, mention_external_id, created_at_source, last_activity_at, mention_type, platform_code, platform, title … (+14) ✓ — ✓ RLS org
social_trend_posts source, topic_external_id, post_external_id, likes, shares, comments, engagement_sc, engagement … (+12) ✓ — ✓ RLS org
social_trend_rankings source, snapshot_at, rank, topic_external_id, topic_name, buzz_volume, comments, likes … (+6) ✓ — ✓ RLS org

Content Intelligence — mặt phẳng nghiên cứu audience (§81)#

Audience CI (Content Intelligence, ADR 0022–0025): fact content_mentions + dimension catalog (taxonomy là DATA, không phải code, §81) + rollup ngày. Brand-partitioned RLS — mỗi row là nghiên cứu bảo mật của một khách hàng trả phí.

Bảng Cột chính org_id brand_id is_sample RLS
agg_content_cross_day dataset_id, cross_pair_id, occurred_day, occurred_iso_week, dim_key_a, value_key_a, dim_key_b, value_key_b … (+8) ✓ ✓ ✓ RLS org+brand
agg_content_dim_day dataset_id, occurred_day, occurred_iso_week, dim_key, value_key, platform_slug, eligible, mention_count … (+6) ✓ ✓ ✓ RLS org+brand
content_cross_pairs dataset_id, dim_key_a, dim_key_b, status ✓ ✓ ✓ RLS org+brand
content_datasets dataset_key, label_vi, taxonomy_version, regulated_vertical, deck_presentation, status ✓ ✓ ✓ RLS org+brand
content_dimension_values dataset_id, dimension_id, value_key, label_vi, label_en, definition_vi, sort_index, color_token … (+4) ✓ ✓ ✓ RLS org+brand
content_dimensions dataset_id, dim_key, kind, role, label_vi, label_en, display_role, min_base … (+4) ✓ ✓ ✓ RLS org+brand
content_ingest_batches dataset_id, file_sha256, transport, template_id, template_version, declared_meta, source_filename, status … (+2) ✓ ✓ ✓ RLS org+brand
content_ingest_receipts dataset_id, ingest_batch_id, line_key, provenance_class, count_value, text_value, attested_by, attested_note … (+1) ✓ ✓ ✓ RLS org+brand
content_insight_publications dataset_id, block_ref, status, authored_by, body_vi, body_en, body_en_updated_at, body_en_source … (+10) ✓ ✓ ✓ RLS org+brand
content_mention_tags dataset_id, mention_id, dim_key, value_key, dimension_id, value_id, ordinal, confidence_bp … (+6) ✓ ✓ ✓ RLS org+brand
content_mentions dataset_id, ingest_batch_id, mention_external_id, source_row_ordinal, content, context_text, source_name, source_id … (+18) ✓ ✓ ✓ RLS org+brand
content_pii_spans mention_id, field, span_start, span_end, kind, detector, confidence_bp ✓ ✓ ✓ RLS org+brand
content_sources dataset_id, source_name, platform_slug ✓ ✓ ✓ RLS org+brand
content_value_aliases dataset_id, dimension_id, value_id, alias_raw, alias_norm, status, confirmed_by, confirmed_at ✓ ✓ ✓ RLS org+brand

Admin — tenancy, auth, AI runtime, vận hành#

Bề mặt platform: tenancy/auth/RBAC, cấu hình AI (ai_connections là runtime chính — §61), chat assistant, dashboard config, audit & vận hành.

Bảng Cột chính org_id brand_id is_sample RLS
agent_facts user_id, fact_key, fact_value, source_type, source_ref ✓ — ✓ RLS org
agent_semantic_memory user_id, role, topic, content, keywords, embedding_stub, source_type, source_ref ✓ — ✓ RLS org
ai_configs provider, model, api_key_ciphertext, api_key_iv, api_key_tag, key_version, base_url ✓ — ✓ RLS org
ai_configs_role role, provider, model, api_key_ciphertext, api_key_iv, api_key_tag, key_version, is_enabled ✓ — ✓ RLS org
ai_connections provider, label, models, api_key_ciphertext, api_key_iv, api_key_tag, key_version, base_url … (+2) ✓ — ✓ RLS org
ai_insight_cache cache_key, locale, text, provider, model, expires_at ✓ — ✓ RLS org
ai_prompt_templates slot, industry, body, version, body_hash, updated_by ✓ — ✓ RLS org
ai_usage_log provider, model, purpose, input_tokens, output_tokens, cached_input_tokens, cache_write_tokens, cache_write_1h_tokens … (+8) ✓ — ✓ RLS org
alert_events rule_id, severity, message, payload, fired_at, acknowledged_at, acknowledged_by, entity_key … (+6) ✓ ✓ ✓ RLS org+brand
alert_rule_user_states rule_id, user_id, is_muted, snoozed_until, channels ✓ — ✓ RLS org
alert_rules name, metric_slug, condition, channels, is_enabled ✓ — ✓ RLS org
alert_workflow_versions workflow_id, version, graph, graph_hash, kernel_version, published_by, published_at, note ✓ ✓ ✓ RLS org+brand
alert_workflows name, description, domain, plane, measure_address, status, draft_graph, active_version_id … (+3) ✓ ✓ ✓ RLS org+brand
api_tokens label, role, token_hash, token_preview, ttl_days, expires_at, last_used_at, allowed_ip_cidrs … (+2) ✓ — ✓ RLS org
audience_sync_destinations name, kind, encrypted_credentials, credentials_iv, credentials_tag, credentials_key_version, config, is_active ✓ — ✓ RLS org
audience_sync_runs audience_id, destination_id, triggered_by, members_considered, suppressed_count, consent_filtered_count, frequency_capped_count, hash_count_pushed … (+5) ✓ — ✓ RLS org
audit_exports export_type, destination, status, row_count, checksum, bytes, exported_at ✓ — ✓ RLS org
audit_logs actor_user_id, action, resource_type, resource_id, diff_before, diff_after, ip, user_agent … (+1) ✓ — — RLS org
auth_sessions sid, user_id, last_seen_at, revoked_at, amr, auth_time, origin_host, public_id … (+2) — — ✓ RLS auth/process
auth_view_sessions actor_sid, actor_user_id, target_user_id, reason, expires_at, ended_at ✓ — ✓ RLS auth/process
brands slug, name, default_locale, timezone, default_currency, logo_url, mask_display_name, theme_slug … (+4) ✓ — ✓ RLS org
briefings user_id, persona, briefing_date, cadence, title, summary, bullets, citations … (+3) ✓ ✓ ✓ RLS org+brand
chat_assistant_settings bot_name, welcome_message, persona_note, industry, starter_suggestions, market_starter_suggestions, ai_font_scale, updated_by_user_id ✓ ✓ ✓ RLS org
chat_conversations user_id, deck_dashboard_id, title, provider, model, archived_at ✓ ✓ ✓ RLS org+brand
chat_messages conversation_id, role, parts, text_preview, prompt_tokens, completion_tokens, finish_reason, rating … (+3) ✓ ✓ ✓ RLS org+brand
chat_tool_calls conversation_id, user_id, tool_name, input, output, error_text, duration_ms ✓ ✓ — RLS org+brand
collector_batch_chunks batch_id, kind, seq, sha256, bytes, object_key, received_at — — — global (không có org_id)
collector_batch_decisions batch_id, decision, decided_by_user_id, reason, consumed_at — — — global (không có org_id)
collector_batch_parts batch_id, kind, row_schema, manifest_rows, coverage_top_n, universe_exhausted, captured_at, source_sha256 … (+4) — — — global (không có org_id)
collector_batches collector_id, feed_id, idempotency_key, contract_version, window_grain, window_start, window_end, state … (+9) — — — global (không có org_id)
collector_events at, collector_id, key_id, batch_id, event, code, detail — — — global (không có org_id)
collector_feed_grants collector_id, feed_id — — — global (không có org_id)
collector_feeds key, source, platform, scope_category_name, scope_category_id, grain, kinds, feed_class … (+1) — — — global (không có org_id)
collector_keys key_id, collector_id, public_key, not_after, revoked_at, last_used_at — — — global (không có org_id)
collectors name, enabled, allowed_cidrs — — — global (không có org_id)
dashboard_snapshots widget_id, cache_key, payload, computed_at, expires_at ✓ — ✓ RLS org
dashboard_subscription_runs subscription_id, period_key, status, reason, recipient_count, row_count, last_error, started_at … (+1) ✓ — ✓ RLS org
dashboard_subscriptions dashboard_id, name, cadence, hour_ict, minute_ict, weekday, day_of_month, format … (+9) ✓ ✓ ✓ RLS org+brand
dashboard_tabs dashboard_id, parent_tab_id, label, label_en, subtitle, subtitle_en, template_tab_key, filter_bar … (+1) ✓ — ✓ RLS org
dashboard_user_views user_id, dashboard_id, name, state, is_default ✓ — ✓ RLS org
dashboard_versions dashboard_id, version, content, summary, restored_from, tag, note, created_by ✓ ✓ ✓ RLS org+brand
dashboard_widgets dashboard_id, widget_type, title, title_en, config, template_widget_key, origin, template_baseline … (+4) ✓ — ✓ RLS org
dashboards name, name_en, slug, is_template, template_key, template_version, plugin_gate, nav_menu_item … (+11) ✓ ✓ ✓ RLS org+brand
data_validation_day_diffs run_id, day, file_count, db_count, file_gmv_vnd, db_gmv_vnd, file_nmv_vnd, db_nmv_vnd … (+3) ✓ — ✓ RLS org
data_validation_order_diffs run_id, platform_order_id, day, diff_type, mismatched_fields, file_status, db_status, file_gmv_vnd … (+3) ✓ — ✓ RLS org
data_validation_runs requested_by, dataset_key, platform, range_from, range_to, filename, extension, byte_length … (+20) ✓ ✓ ✓ RLS org+brand
dsar_requests subject_kind, identifier, identifier_hash, action, contact_email, status, response_payload, requested_by … (+1) ✓ — ✓ RLS org
frequency_caps shopper_id, channel, pushed_at, audience_id ✓ — ✓ RLS org
idp_keys kid, kind, use, alg, public_jwk, private_jwk_enc, status, not_after — — ✓ global (không có org_id)
job_outbox queue_name, job_name, job_id, payload, options, attempts, available_at, lease_owner … (+4) ✓ — ✓ RLS org
magic_link_tokens token, email, expires_at, used_at, verifies_email ✓ — — RLS auth/process
notification_channel_configs channel, label, config_ciphertext, config_iv, config_tag, key_version, public_meta, is_active … (+2) — — ✓ global (không có org_id)
notification_deliveries user_id, type, dedupe_key, channel, status, provider_message_id, failure_kind, reason … (+4) ✓ — — RLS org
notification_digest_windows user_id, channel, status, opened_at, flush_at, closed_at, item_count ✓ — ✓ RLS org
notification_preferences user_id, type, channels, is_enabled ✓ ✓ ✓ RLS org+brand
notification_settings rule_id, is_enabled, channels, recipient_roles, email_subject, email_body, updated_by — — — global (không có org_id)
notifications user_id, type, severity, title, body, href, dedupe_key, source_kind … (+2) ✓ ✓ ✓ RLS org+brand
org_auth_ldap enabled, host, port, use_start_tls, use_ldaps, allow_insecure_tls, bind_dn, bind_password_ciphertext … (+7) ✓ — ✓ RLS org
org_auth_oidc provider_key, label, provider_preset, enabled, issuer, client_id, client_secret_ciphertext, client_secret_iv … (+9) ✓ — ✓ RLS org
org_backup_destinations name, provider, config, credential_ciphertext, credential_iv, credential_tag, credential_key_version, status … (+3) ✓ — ✓ RLS org
org_backup_schedules enabled, profile_id, cadence, hour_ict, weekday_ict, destination_id, retention_keep, last_run_at … (+2) ✓ — ✓ RLS org
org_blueprint_applications blueprint_key, version, applied_by, applied_at ✓ — ✓ RLS org
org_data_jobs kind, source_artifact_job_id, categories, scope, status, progress, artifact_key, artifact_bytes … (+8) ✓ — ✓ RLS org
org_dataset_fields dataset_id, field_key, role, data_type, unit, scale, aggregation, temporality … (+15) ✓ — ✓ RLS org
org_dataset_insights dataset_id, page_key, tab_key, widget_key, period_month, status, authored_by, body_vi … (+10) ✓ ✓ ✓ RLS org+brand
org_dataset_links link_key, from_dataset_id, to_dataset_id, join_on, label_vi, label_en, schema_version, status ✓ — ✓ RLS org
org_dataset_packs pack_key, label_vi, label_en, dataset_keys, version, status, content ✓ — ✓ RLS org
org_dataset_panel_rows dataset_id, period_month, period_sub, dims, measures, schema_version ✓ ✓ ✓ RLS org+brand
org_dataset_receipts dataset_id, source_id, line_key, provenance_class, count_value, text_value, attested_by, attested_note … (+1) ✓ ✓ ✓ RLS org+brand
org_dataset_recons dataset_id, recon_key, measure_key, period_month, expected_value_int, expected_value_label, oracle_note, verdict … (+2) ✓ ✓ ✓ RLS org+brand
org_dataset_sources dataset_id, source_name, transport, template_id, template_version, status, last_synced_at ✓ ✓ ✓ RLS org+brand
org_dataset_value_aliases dataset_id, field_id, value_id, alias_raw, alias_norm, status, confirmed_by, confirmed_at ✓ — ✓ RLS org
org_datasets dataset_key, label_vi, label_en, grain_fields, time_field_key, vertical, schema_version, cache_ttl_seconds … (+1) ✓ ✓ ✓ RLS org+brand
org_domain_activations domain_key, layer_kind, sequence, source_blueprint_key, version, state, activated_by, activated_at ✓ — ✓ RLS org
org_domains domain, status, verification_token, verified_at, last_checked_at, last_error ✓ — ✓ RLS org
org_login_page logo_light_url, logo_dark_url, favicon_url, accent_color, headline, tagline, support_email, legal_privacy_url … (+5) ✓ — ✓ RLS org
org_login_page_versions version, config, restored_from, published_by, published_at ✓ — ✓ RLS org
org_masking_settings masked_roles, mask_chrome, mask_records, updated_by_user_id ✓ — ✓ RLS org
org_masking_terms kind, term, term_folded, match_mode, replacement, status, origin, suggestion_batch_id … (+1) ✓ ✓ ✓ RLS org+brand
org_memberships user_id, role, viewable_brand_ids, invited_at, accepted_at, invited_email ✓ — — RLS identity metadata
org_nav_config menu_labels, menu_order, menu_group_order, hidden_menu_items, pinned_dashboard_ids, nav_custom_items, groups ✓ ✓ ✓ RLS org
org_notification_channels channel, is_enabled, updated_by ✓ — ✓ RLS org
org_playbooks name, description, cron_expr, steps, graph, trigger_kind, trigger_config, holdout_bp … (+4) ✓ — ✓ RLS org
org_plugin_installations plugin_id, plugin_version, enabled, config, operator_set_at, is_active, plan, limits … (+2) ✓ — ✓ RLS org
org_role_policies role, name_vi, name_en, description_vi, description_en, capabilities, menu_items, is_locked ✓ — ✓ RLS org
org_user_activity_day user_id, day, last_seen_at ✓ — ✓ RLS org
organizations slug, name, logo_url, sidebar_logo_url, sidebar_name, sidebar_tagline, mask_display_name, mask_logo_url … (+28) — — ✓ RLS identity metadata
platform_ai_connections provider, label, models, api_key_ciphertext, api_key_iv, api_key_tag, key_version, base_url … (+2) — — ✓ global (không có org_id)
platform_connector_credentials connector, credential_ciphertext, credential_iv, credential_tag, key_version, fields_hint, updated_by — — — global (không có org_id)
platform_connector_runs connector, trigger, status, started_at, finished_at, calls, rate_remaining, items_seen … (+11) — — — global (không có org_id)
platform_connector_state connector, settings, fingerprint, revision, announced_revision, last_check_at, last_full_at — — — global (không có org_id)
platform_outbox direction, event_id, event_type, subscription_id, payload, status, attempts, next_attempt_at … (+3) ✓ — ✓ RLS org
platform_webhook_subscriptions app_id, url, secret_ciphertext, secret_iv, secret_tag, secret_key_version, event_types, is_active ✓ — ✓ RLS org
pred_model_registry slug, version, kind, artifact_s3_key, metrics, is_active, notes, trained_at — — — global (không có org_id)
price_alerts product_id, min_price_vnd, max_price_vnd, delta_bp, threshold_bp, platforms, status, note … (+2) ✓ — ✓ RLS org
push_subscriptions user_id, endpoint_hash, endpoint_ciphertext, endpoint_iv, endpoint_tag, key_version, p256dh, auth … (+3) — — ✓ global (không có org_id)
resource_shares resource_type, resource_id, name, slug, viewer_scope, token_hash, password_hash, expires_at … (+5) ✓ ✓ ✓ RLS org+brand
site_settings site_name, site_tagline, page_title_suffix, landing_title, landing_description, logo_url, logo_dark_url, favicon_url … (+6) — — — global (không có org_id)
site_themes slug, name_vi, name_en, description, payload, updated_by ✓ — ✓ app-layer (chủ đích)
suppression_lists shopper_id, reason, note, suppressed_at ✓ — ✓ RLS org
user_auth_secrets user_id, password_hash, passphrase_hash, two_factor_secret_ciphertext, two_factor_secret_iv, two_factor_secret_tag, two_factor_secret_key_version, two_factor_last_used_step … (+1) — — — RLS auth/process
user_channel_identities user_id, channel, external_id_hash, external_id_ciphertext, external_id_iv, external_id_tag, key_version, link_token_hash … (+3) — — ✓ global (không có org_id)
user_credentials user_id, credential_id, public_key, counter, transports, device_name, aaguid, backed_up … (+1) — — — RLS auth/process
user_panel_settings user_id, dashboard_id, payload ✓ — ✓ RLS org
user_social_identities user_id, provider, subject, email, last_used_at — — — RLS auth/process
users email, name, two_factor_enabled, notification_prefs, is_super_admin, default_locale, last_login_at, email_verified_at … (+1) — — — RLS identity metadata
webauthn_challenges user_id, client_id, mode, challenge, expires_at — — — RLS auth/process

Bảng theo spec mso-13 §9.4 — trạng thái so với roadmap#

Bốn bảng trong docs/MSO-UCIP-Roadmap/mso-13-decision-engine-spec.html §9.4 phục vụ roadmap L1–L4. Ba trong bốn ĐÃ SHIP (xem nhóm MSO ở trên); chỉ playbook_rules còn chưa tồn tại trong schema (script này sẽ tự nhặt bảng khi nó xuất hiện trong packages/schema/src/tables):

Bảng Vai trò Trạng thái
signals / signal_values registry tín hiệu + feature store, versioned, test được (L2) đã ship — xem nhóm MSO
playbook_rules (nâng cấp mso_playbooks) rule đã mã hoá — predicate máy-kiểm được thay hardcode TS (L1) planned
experiments thí nghiệm incrementality (L3) đã ship — xem nhóm MSO
policy_models posterior bandit/lift per lever (L4) đã ship — xem nhóm MSO

Trạng thái hiện tại so với spec:

  • experiment_assignments là tiền thân holdout đơn giản đã có TRƯỚC experiments — gán arm treatment/holdout theo action_command_id; experiments (bảng L3 mới, cột decision_id) đo lift theo lever, ghi bởi packages/metrics/src/experiments.ts.
  • mso_playbooks giữ phần hiển thị + guardrail template; phần when predicate máy-kiểm được (L1) sẽ nằm ở playbook_rules với version/status (active/archived, immutable khi active — cùng kỷ luật §16 của mapping template) — đây là mảnh DUY NHẤT của §9.4 còn planned.
  • offtake_models hiện upsert đè theo natural key, chưa có model_version/valid_from (đánh giá mso-14): decision chỉ trace về model qua context_snapshot jsonb. Khi thêm version hoá, pattern có sẵn để copy là pred_model_registry.model_version.

Quy ước chung#

  • Migration: bảng mới = file trong packages/schema/src/tables/ + export trong src/tables.ts + pnpm --filter @yng/schema db:generate + RLS policy cùng change.
  • is_sample: mặc định false, có mặt trên mọi bảng dữ liệu (invariant #3) — các bảng auth/hạ tầng (users, magic_link_tokens, …) và một số bảng ledger là ngoại lệ có chủ đích.
  • Tiền tệ: VND integer (bigint), không numeric/float (§2); tỷ lệ/corr lưu signed basis points ×10000 (§60).
  • Ngày: mọi day-edge/label theo ICT (Asia/Ho_Chi_Minh) — @yng/ui/ict-date phía app, AT TIME ZONE 'Asia/Ho_Chi_Minh' phía SQL (§34/§41).
  • Credential: envelope-encrypted (AES-256-GCM, ciphertext + iv + tag + key_version), không bao giờ log/return (invariant #4).