data

Data Model

Aturan: tidak ada foreign key lintas store. Referensi lintas store memakai publicid.

  • Status: Frozen (desain), implementasi dimulai dari sini
  • Storage: DO SQLite per cell; Postgres (control plane); R2 (objek); WORM ledger
  • ORM: Drizzle (drizzle-orm/durable-sqlite)
  • Terkait: ARCHITECTURE.md, 03-api/INVENTORY.md, 04-data/IDEMPOTENCY.md, ADR-0014

1. Pembagian data

StoreIsiTidak boleh
Control plane (Postgres)akun, membership, project registry, API key hash/metadata, plan, entitlement, invoice refData keputusan, isi dataset
Project cell (SQLite)Semua state project: agent, session, decision, dataset metadata, action, approval, planningData lintas project
Feed cell (SQLite)Signal append-only per topikData project
Object storage (R2)File dataset mentah, embedding, dokumen, render, audit ledgerState transaksional
Analytics (Neon PG + pgvector)Snapshot agregat, embedding untuk ANNSumber kebenaran
Audit ledger (R2 Object Lock)Entry WORM + hash chainData yang bisa diedit

Aturan: tidak ada foreign key lintas store. Referensi lintas store memakai public_id.


2. Strategi ID (dual ID)

2.1 Dua ID, dua peran

KolomTipePeranBoleh keluar cell?
idINTEGER / BIGSERIALPrimary key internal, join, FK, urutanTidak pernah
public_idTEXTIdentitas eksternal: API, webhook, audit, object key, logYa
API request path   → public_id
Response `id`      → public_id
Webhook payload    → public_id
Audit subject_id   → public_id
Object key         → public_id
Join / FK          → id (integer)
Cursor             → (created_at, id) di-sign

Aturan keras: internal id tidak boleh muncul di response, error, log, webhook, audit, object key, atau prompt model. Test serialisasi harus menolak field internal.

2.2 Bentuk public_id

<prefix>_<nanoid>
  • prefix: 2–5 huruf kecil, dari registry tetap (lihat §2.3).
  • nanoid: 21 karakter, alphabet base32 Crockford lowercase 0123456789abcdefghjkmnpqrstvwxyz (tanpa i, l, o, u, _, -).
  • Entropi: 21 × 5 bit = 105 bit; collision negligible.
  • CSPRNG: crypto.getRandomValues (tersedia di Workers).
  • Case-sensitive? Canonical lowercase. Tolak input yang tidak cocok regex; jangan diam-diam mengubah case.
  • Prefix tidak menambah entropi. Jangan memperpendek Nanoid karena ada prefix.

Contoh: dec_7f3a9c2e1b4d6f8a5c0ef.

2.3 Prefix registry

EntitasPrefixCatatan
Organizationorg_control plane
Userusr_control plane
Projectproj_control plane; tidak muncul di API mesin
API keykey_control plane
Agenttanpa prefixpublic_id = slug (default.agent)
Sessionses_
Entryent_transcript/fork
Submissionsub_
Decisiondec_
Feedbackfbk_
Datasetds_
Onboarding sourcesrc_
Syncsyn_
Quarantine batchqb_
Connectorcn_
Actionact_
Action invocationinv_
Credentialcrd_
Approvalapr_
Projectionprjn_bukan prj_ agar tidak bentrok dengan project
Scenarioscn_
Deviationdev_
Documentdoc_
Correctioncor_
Evalevl_
Jobjob_
Audit entryaud_
Signalsig_
World subscriptionwsub_
Webhook endpointwhk_
Webhook deliverywhd_
Tracetr_korelasi, bukan tabel
Assumptiondriver_id + versionnatural key
Data contractversionnatural key
PeriodYYYY-MMnatural key

Registry disimpan di packages/contracts/ids.ts; validator & parser digenerate dari sana. CI gagal jika ada prefix di luar registry.

2.4 Pengecualian (natural key)

Tabel berikut tidak memakai public_id Nanoid karena alamatnya natural:

TabelPrimary keyAlasan
agent_contracts(agent_id, version)versi kontrak
assumptions(driver_id, version)driver + versi
data_contracts(id) + version unikversi
usage_counters(period, agent_id, model)counter
project_settingskeykonfigurasi
idempotency_keyskeyidempotency
memberships(org_id, user_id)relasi
periodsperiodkalender
financials(period, coa_code)baris GL
cursorssubscription_idstate

Pengecualian harus didokumentasikan di ADR; jangan menambah tanpa alasan.

2.5 SQLite vs Postgres

StoreInternal idCatatan
DO SQLiteINTEGER PRIMARY KEY (rowid)64-bit; tanpa AUTOINCREMENT kecuali butuh monotonic ketat
Postgres control planeBIGSERIAL PRIMARY KEYbigserial hanya di sini
Neon analyticsBIGINTsalinan internal + public_id

Jangan memakai AUTOINCREMENT secara default: ia menambah biaya dan tabel jarang hard-delete. Jika sebuah tabel bisa hard-delete dan id-nya dirujuk FK, gunakan AUTOINCREMENT atau larang reuse lewat kebijakan erase.

2.6 Cursor

Karena public_id Nanoid tidak sortable, cursor pagination memakai:

cursor = base64url(HMAC(secret, created_at || ":" || id))

Server memvalidasi signature, men-decode, lalu WHERE (created_at, id) < (?, ?). Jangan mengekspos id mentah. Alternatif: cursor berisi created_at + public_id (tanpa internal), dengan index (created_at, public_id).

2.7 Audit & replay

  • audit_outbox.subject_id = public_id.
  • Hash chain dihitung dari canonical entry yang memuat public_id, bukan id.
  • evidence.ref = public_id (mis. ds_...:row:<natural key>).
  • Replay tidak boleh bergantung pada id yang bisa berubah saat restore/migrasi.

3. Control plane

-- organizations
id            bigserial primary key,
public_id     text not null unique,            -- org_...
name          text not null,
slug          text unique not null,
created_at    timestamptz not null

-- users
id            bigserial primary key,
public_id     text not null unique,            -- usr_...
email         text unique not null,
name          text,
created_at    timestamptz not null

-- memberships
org_id        bigint not null references organizations(id),
user_id       bigint not null references users(id),
role          text not null,                   -- owner|admin|member|billing|auditor
created_at    timestamptz not null,
primary key (org_id, user_id)

-- projects (registry; bukan data keputusan)
id            bigserial primary key,
public_id     text not null unique,            -- proj_...
org_id        bigint references organizations(id),
name          text not null,
vertical      text not null,                   -- generic|<vertical-pack>
residency     jsonb not null,                  -- {region,bucketRegion,modelAllowlist}
cell_name     text not null unique,            -- DO name / actor id
status        text not null,                   -- provisioning|active|suspended|deleted
created_at    timestamptz not null

-- api_keys (hanya hash + prefix). Tidak ada human/machine: scope menentukan.
id            bigserial primary key,
public_id     text not null unique,            -- key_...
project_id    bigint references projects(id),
prefix        text not null,
hash          text not null,                   -- PBKDF2-SHA256
salt          text not null,
iterations    integer not null default 100000,
name          text,
scopes        text,                            -- JSON array; default read-only
environment   text not null default 'live',    -- live|sandbox (juga di prefix)
expires_at    timestamptz,
created_by    text,                            -- public id pembuat (metadata)
last_used_at  timestamptz,
revoked_at    timestamptz

-- plans / entitlements
project_id    bigint primary key references projects(id),
plan          text not null,                   -- build|starter|growth|enterprise
limits        jsonb not null,
model_funding jsonb not null,                  -- byok|platform_credits|hybrid
billing_ref   text,
updated_at    timestamptz not null

Kenapa API key di control plane: lookup prefix harus murah dan tidak boleh memanggil cell lain di jalur latency. Cell menerima projectId (internal) hasil resolusi; API tidak pernah menerima projectId dari klien.


4. Project cell

4.1 Agents & contracts

create table agents (
  id                    integer primary key,
  public_id             text not null unique,     -- slug: default.agent
  mode                  text not null,            -- shadow|assist|auto
  model                 text not null,            -- local:* | ext:*
  reviewer_model        text,
  escalation_threshold  real not null default 0.7,
  tools                 text not null,            -- JSON array
  instructions          text,
  budget_usd_per_month  real,
  contract_version      text not null,
  policy_version        text not null,
  created_at            text not null,
  updated_at            text not null
);

create table agent_contracts (
  agent_id        integer not null references agents(id),
  version         text not null,
  input_schema    text not null,                  -- JSON Schema
  output_schema   text not null,
  reason_codes    text not null,                  -- JSON array
  created_at      text not null,
  primary key (agent_id, version)
);

Agent sengaja memakai slug sebagai public_id karena API dan konfigurasi memakai nama agent. Jangan menambahkan prefix agent_ tanpa ADR baru.

4.2 Sessions & entries

create table sessions (
  id              integer primary key,
  public_id       text not null unique,           -- ses_...
  agent_id        integer not null references agents(id),
  parent_id       integer references sessions(id),
  forked_at       integer references entries(id), -- entry internal
  ownership       text not null,                  -- ownerless|task
  status          text not null,                  -- idle|running|waiting_approval|closed
  overrides       text,                           -- JSON
  model           text,
  created_at      text not null,
  updated_at      text not null
);
create index sessions_agent on sessions(agent_id, created_at desc);
create index sessions_parent on sessions(parent_id);

create table entries (
  id              integer primary key,
  public_id       text not null unique,           -- ent_...
  session_id      integer not null references sessions(id),
  role            text not null,                  -- user|assistant|tool|system
  content         text,
  tool_name       text,
  tool_args       text,                           -- JSON (redacted)
  cost_input      integer default 0,
  cost_output     integer default 0,
  cost_usd        real default 0,
  at              text not null
);
create index entries_session on entries(session_id, at);

create table submissions (
  id              integer primary key,
  public_id       text not null unique,           -- sub_...
  session_id      integer not null references sessions(id),
  request_id      text not null,                  -- Idempotency-Key
  state           text not null,                  -- queued|running|settled|unaffected
  answer_entry_id integer references entries(id),
  trace_id        text,                           -- tr_...
  created_at      text not null
);
create unique index submissions_request on submissions(request_id);

Fork: sessions.parent_id + forked_at; entry anak tidak menyalin entry induk. Query transcript menggabungkan induk sampai forked_at + entry anak. Internal id hanya dipakai join; API mengembalikan public_id.

4.3 Decisions

create table decisions (
  id                     integer primary key,
  public_id              text not null unique,     -- dec_...
  agent_id               integer not null references agents(id),
  session_id             integer references sessions(id),
  status                 text not null,            -- queued|running|decided|needs_review|...
  mode                   text not null,             -- shadow|assist|auto
  action                 text,
  reason_codes           text,                      -- JSON array
  confidence             real,
  evidence               text,                      -- JSON array of public refs
  rationale              text,
  missing_evidence       text,
  execution              text not null default 'advisory',
  proposed_invocation    text,                      -- JSON
  invocation_id          integer references action_invocations(id),
  escalated              integer not null default 0,
  model_used             text,
  policy_version         text not null,
  contract_version       text not null,
  feature_snapshot_hash  text,
  input_hash             text not null,
  cost_input             integer default 0,
  cost_output            integer default 0,
  cost_usd               real default 0,
  latency_ms             integer,
  trace_id               text not null,             -- tr_...
  approval_id            integer references approvals(id),
  created_at             text not null,
  decided_at             text
);
create index decisions_status on decisions(status, created_at desc);
create index decisions_agent on decisions(agent_id, created_at desc);
create index decisions_session on decisions(session_id);

create table decision_feedback (
  id              integer primary key,
  public_id       text not null unique,             -- fbk_...
  decision_id     integer not null references decisions(id),
  outcome         text not null,
  actual          text,
  note            text,
  observed_at     text,
  created_at      text not null
);

feature_snapshot_hash + input_hash adalah dasar replay. Jangan pernah update baris decisions setelah decided; koreksi = baris baru + relasi.

4.4 Datasets, onboarding sources, data contract

create table onboarding_sources (
  id              integer primary key,
  public_id       text not null unique,             -- src_...
  type            text not null,                    -- s3|postgres_cdc|webhook|upload
  config          text not null,                    -- JSON (tanpa secret plaintext)
  status          text not null,
  created_at      text not null
);

create table datasets (
  id                 integer primary key,
  public_id          text not null unique,          -- ds_...
  source_id          integer references onboarding_sources(id),
  name               text not null,
  entity             text not null,
  format             text not null,                 -- csv|ndjson|parquet
  status             text not null,                 -- registered|uploading|ingesting|ready|...
  pii_classification text not null,                 -- none|low|high
  rows               integer,
  checksum           text,
  object_key         text,                          -- R2
  schema_json        text,
  quality_gates      text,                          -- JSON
  created_at         text not null
);

create table data_contracts (
  id             integer primary key,
  version        text not null unique,              -- "3"
  project        text not null,
  owner          text not null,
  document       text not null,                     -- YAML/JSON canonical
  hash           text not null,
  status         text not null,                     -- draft|active|superseded
  approved_by    text,                              -- usr_... / key_...
  approved_at    text,
  created_at     text not null
);

create table syncs (
  id                    integer primary key,
  public_id             text not null unique,       -- syn_...
  source_id             integer not null references onboarding_sources(id),
  contract_id           integer not null references data_contracts(id),
  status                text not null,              -- active|paused|drifted|failed
  last_batch_at         text,
  lag_seconds           integer,
  quarantined_batches   integer not null default 0,
  decisions_frozen      integer not null default 0,
  created_at            text not null
);

create table quarantine_batches (
  id            integer primary key,
  public_id     text not null unique,               -- qb_...
  sync_id       integer not null references syncs(id),
  received_at   text not null,
  rows          integer not null,
  violations    text not null,                      -- JSON
  payload_key   text                                -- R2 untuk audit
);

4.5 Connectors, actions, invocations, credentials

create table connectors (
  id            integer primary key,
  public_id     text not null unique,               -- cn_...
  type          text not null,                      -- openapi|mcp|declarative
  url           text,
  spec          text,                               -- JSON/YAML
  warning       text,                               -- indikasi prompt injection
  status        text not null,                      -- active|disabled
  created_at    text not null
);

create table actions (
  id                   integer primary key,
  public_id            text not null unique,        -- act_...
  connector_id         integer references connectors(id),
  name                 text unique not null,        -- record.request_documents
  risk                 text not null,               -- read|write_low|write_high|financial
  endpoint             text not null,               -- JSON
  args_schema          text not null,               -- JSON
  idempotency          text not null,               -- JSON
  response_fields      text,                        -- JSON
  redact_fields        text,                        -- JSON
  guardrails           text not null,               -- JSON
  replay               text not null,               -- safe|unsafe
  enabled              integer not null default 0,
  created_at           text not null,
  updated_at           text not null
);

create table action_invocations (
  id                    integer primary key,
  public_id             text not null unique,       -- inv_...
  action_id             integer not null references actions(id),
  decision_id           integer references decisions(id),
  status                text not null,              -- proposed|approved|executing|succeeded|...
  args                  text not null,              -- JSON (context + model)
  idempotency_key       text not null,
  request_hash          text,
  response_hash         text,
  response_sanitized    text,                       -- JSON, hanya fields
  error                 text,
  actor_id              text,                       -- usr_... / key_...
  reconciled_by         text,
  reconciled_at         text,
  created_at            text not null,
  updated_at            text not null
);
create index invocations_status on action_invocations(status, created_at desc);
create unique index invocations_idem on action_invocations(idempotency_key);

create table credentials (
  id              integer primary key,
  public_id       text not null unique,             -- crd_...
  kind            text not null,                    -- model|action
  provider        text not null,                    -- ext:anthropic|onprem:enterprise|connector
  ciphertext      text not null,                    -- envelope encryption
  kms_key_ref     text not null,
  metadata        text,                             -- JSON (last4, expiry)
  last_validated  text,
  valid           integer,
  revoked_at      text,
  created_at      text not null
);

Kredensial tidak pernah masuk agents.instructions, entries.content, atau prompt. Kolom ciphertext hanya didekripsi di action-proxy/provider-gateway.

4.6 Approvals

create table approvals (
  id              integer primary key,
  public_id       text not null unique,             -- apr_...
  subject_type    text not null,                    -- decision|contract|assumption|projection|agent-mode|document|action-invocation
  subject_id      text not null,                    -- public_id subjek (polymorphic)
  state           text not null,                    -- pending|approved|rejected|expired
  required_role   text not null,                    -- reviewer|approver|admin
  requested_by    text not null,                    -- usr_... (manusia)
  decided_by      text,
  decided_at      text,
  note            text,
  conditions      text,                             -- JSON array
  due_at          text,
  created_at      text not null
);
create index approvals_pending on approvals(state, due_at);
create index approvals_subject on approvals(subject_type, subject_id);

subject_id sengaja public_id karena subjeknya polymorphic. Jika perlu join, tambahkan subject_internal_id integer nullable yang tidak diekspos.

Four-eyes: requested_by != decided_by. Untuk financial, minimal satu approver dan satu approver kedua (lihat RBAC).

4.7 Planning

create table assumptions (
  driver_id       text not null,
  version         text not null,
  label           text not null,
  value           real not null,
  unit            text not null,
  source_ref      text not null,                    -- wajib
  confidence      real,
  class           text not null,                    -- free|closing
  elasticity      real,
  impacted_lines  text,                             -- JSON
  approved_by     text,
  approved_at     text,
  superseded_by   text,
  created_at      text not null,
  primary key (driver_id, version)
);

create table projections (
  id                    integer primary key,
  public_id             text not null unique,       -- prjn_...
  as_of                 text not null,
  horizon_years         integer not null,
  assumption_version    text not null,
  baseline_period       text not null,
  statements            text not null,              -- JSON
  ratios                text not null,              -- JSON
  constraints           text not null,              -- JSON
  narrative             text,
  input_hash            text not null,
  created_at            text not null
);

create table scenarios (
  id              integer primary key,
  public_id       text not null unique,             -- scn_...
  projection_id   integer not null references projections(id),
  name            text not null,                    -- base|optimis|stres-1
  triggers        text not null,                    -- JSON
  result          text not null,                    -- JSON
  created_at      text not null
);

create table deviations (
  id              integer primary key,
  public_id       text not null unique,             -- dev_...
  projection_id   integer not null references projections(id),
  period          text not null,
  line_id         text not null,
  actual          real not null,
  planned         real not null,
  delta           real not null,
  delta_percent   real,
  material        integer not null,
  explanation     text,
  evidence        text
);

create table periods (
  period          text primary key,                 -- YYYY-MM
  closed_at       text
);

create table financials (
  period          text not null,
  coa_code        text not null,
  amount          real not null,
  statement       text not null,                    -- neraca|laba_rugi|komitmen_kontinjensi
  primary key (period, coa_code)
);

4.8 Evals, documents, jobs, usage

create table evals (
  id              integer primary key,
  public_id       text not null unique,             -- evl_...
  type            text not null,
  status          text not null,
  dataset_id      integer references datasets(id),
  agent_id        integer references agents(id),
  metrics         text,                             -- JSON
  breakdown       text,                             -- JSON
  sample_size     integer,
  created_at      text not null
);

create table documents (
  id              integer primary key,
  public_id       text not null unique,             -- doc_...
  template        text not null,
  format          text not null,                    -- pdf|docx|xlsx
  status          text not null,
  object_key      text,
  checksum        text,
  created_at      text not null
);

create table document_corrections (
  id              integer primary key,
  public_id       text not null unique,             -- cor_...
  document_id     integer not null references documents(id),
  field           text not null,
  original_value  text,
  corrected_value text not null,
  reason          text,
  actor_id        text not null,
  created_at      text not null
);

create table jobs (
  id              integer primary key,
  public_id       text not null unique,             -- job_...
  type            text not null,                    -- backfill|eval|render|projection|...
  status          text not null,                    -- queued|running|paused|completed|failed|canceled
  progress        real not null default 0,
  checkpoint      text,                             -- JSON
  result          text,                             -- JSON
  error           text,                             -- Problem JSON
  created_at      text not null,
  updated_at      text not null
);
create index jobs_status on jobs(status, created_at desc);

create table usage_counters (
  period          text not null,                    -- YYYY-MM
  agent_id        integer not null,
  model           text not null,                    -- 'none' untuk non-model
  input_tokens    integer not null default 0,
  output_tokens   integer not null default 0,
  usd             real not null default 0,
  decisions       integer not null default 0,
  primary key (period, agent_id, model)
);

usage_counters adalah satu-satunya sumber budget. Ditulis dalam transaksi yang sama dengan keputusan (single writer = akurat). agent_id internal; API menampilkan slug.

4.9 Idempotency, audit outbox, webhook

create table idempotency_keys (
  key             text primary key,
  request_hash    text not null,
  response_status integer,
  response_body   text,
  resource_public_id text,
  expires_at      text not null,
  created_at      text not null
);
create index idempotency_expiry on idempotency_keys(expires_at);

create table audit_outbox (
  id              integer primary key,
  public_id       text not null unique,             -- aud_...
  type            text not null,
  actor           text not null,                    -- usr_... / key_...
  actor_type      text not null,                    -- user|key (atribusi saja)
  subject_id      text,                             -- public_id
  payload_hash    text not null,
  prev_hash       text,
  hash            text not null,
  at              text not null,
  delivered_at    text
);
create index audit_outbox_undelivered on audit_outbox(delivered_at) where delivered_at is null;

create table webhook_endpoints (
  id              integer primary key,
  public_id       text not null unique,             -- whk_...
  url             text not null,
  secret_cipher   text not null,
  events          text not null,                    -- JSON
  status          text not null,
  created_at      text not null
);

create table webhook_deliveries (
  id              integer primary key,
  public_id       text not null unique,             -- whd_...
  endpoint_id     integer not null references webhook_endpoints(id),
  event           text not null,
  status          text not null,                    -- pending|delivered|failed|dropped
  attempts        integer not null default 0,
  response_code   integer,
  next_attempt_at text,
  idempotency_key text not null unique,
  created_at      text not null
);

Aturan: mutasi domain + audit_outbox + usage_counters dalam satu transaksi. Jika salah satu gagal, transaksi rollback. Pengiriman ke WORM dilakukan async oleh worker.

4.10 Settings

create table project_settings (
  key             text primary key,
  value           text not null,
  updated_at      text not null
);
-- keys: budget_limit_usd, plan, retention_days, residency, model_funding, ...

Entitlement disinkronkan dari billing via webhook, disimpan di cell. Jalur kritis tidak pernah memanggil vendor billing.


5. Feed cell

create table signals (
  id              integer primary key,
  public_id       text not null unique,             -- sig_...
  topic           text not null,
  at              text not null,
  summary         text not null,
  source          text not null,                    -- URI wajib
  confidence      real,
  entities        text,                             -- JSON
  drivers         text,                             -- JSON
  content_hash    text not null
);
create index signals_topic_time on signals(topic, at desc);
create unique index signals_dedup on signals(content_hash);

create table subscriptions (
  id              integer primary key,
  public_id       text not null unique,             -- wsub_...
  topics          text not null,                    -- JSON
  webhook_url     text,
  filters         text,
  created_at      text not null
);

create table cursors (
  subscription_id integer primary key references subscriptions(id),
  cursor          text not null,
  updated_at      text not null
);

Feed cell append-only. Tidak ada update/delete signal kecuali retensi (hapus partisi lama).


6. Object storage layout

s3://agnestra-<region>/
  projects/<projectPublicId>/
    datasets/<datasetPublicId>/raw/<file>
    datasets/<datasetPublicId>/embeddings/<shard>.bin
    documents/<documentPublicId>/<file>.pdf
    exports/<exportPublicId>.zip
    snapshots/<timestamp>.sqlite
  audit/<projectPublicId>/<yyyy>/<mm>/<auditPublicId>.json
  audit/<projectPublicId>/chain/<auditPublicId>.proof
  feeds/<topic>/<yyyy>/<mm>/<signalPublicId>.json

Bucket policy:

  • Project hanya bisa mengakses prefix-nya (presigned URL).
  • Audit prefix: Object Lock COMPLIANCE, retensi per tier.
  • Snapshot read-only untuk analytics loader.
  • Tidak ada object key yang memakai internal id.

7. Invariant & constraint

#InvariantPenegakan
1Satu project = satu cellRegistry + nama cell unique
2Tidak ada tenant_idReview schema + test
3Internal id tidak pernah keluarSerializer whitelist + test
4public_id unik per tabelUnique index
5Prefix sesuai registryValidator + CI
6Decision final immutableTrigger/guard di repository
7Audit outbox dalam transaksiSatu db.batch
8Budget akuratSingle writer + counter
9Kredensial tidak di plaintextEnkripsi + akses hanya proxy
10Evidence milik projectResolusi public_id sebelum simpan
11Contract version immutableInsert-only
12Idempotency key unik per projectUnique index
13Soft delete + erasure asyncStatus + job
14Foreign key memakai internal idSchema review

8. Migrasi

  • Drizzle Kit menghasilkan SQL; dijalankan di blockConcurrencyWhile saat cell start.
  • Migrasi harus idempoten dan maju saja (tidak ada down migration di produksi).
  • Migrasi berat (backfill kolom) dipisah ke Job, bukan di jalur start.
  • Setiap migrasi punya test di @cloudflare/vitest-pool-workers dengan data seed.
  • Fallback raw SQL hanya untuk migrasi kritis yang didukung Drizzle belum stabil.
  • Sebelum deploy: wrangler deploy --dry-run + migrasi di staging.
  • Penambahan public_id pada tabel lama: buat kolom nullable → isi → unique index → jadikan NOT NULL; jangan pernah mengubah public_id setelah dipublikasikan.

9. Retensi & erasure

DataRetensi defaultCatatan
Decision tracesesuai tier (7 hari–7 tahun)WORM untuk Enterprise
Audit ledgersesuai tierObject Lock tidak bisa dihapus sebelum retainUntil
Dataset mentahsampai dihapus project
Session/entry90 hari idle
Idempotency key24 jam
Job30 hari
Feed signal30–365 hari per topik

Erasure:

DELETE /_ops/erasure/{publicId} → Job
  → soft delete (status=deleting)
  → hapus objek non-WORM
  → WORM tetap sampai retainUntil (catatan hukum)
  → tulis audit proof penghapusan
  → hard delete metadata

Erasure menghapus child rows berdasarkan internal id; public_id dicatat di audit proof sebelum dihapus.