Skip to content

Part C. The complete database design

One database, bideward, two schemas: hub (the receiver, dashboard, accounts, bots, settings, money, rounds, alerts) and research (the existing research service tables, plus read-only views over hub for the Research page). All structure changes are numbered SQL files (db/migrations/0001_….sql) applied in order by a small runner that records each in hub.schema_migrations; nobody edits tables by hand.

  1. Two layers, one database. Layer 1 (C.2) is a faithful copy of how the Worker stores data (a key and a JSON value), so the same Worker code runs on day one and behaviour is identical. Layer 2 (C.3) is the proper relational design. Each key family moves from Layer 1 to Layer 2 one at a time (C.8), with the two compared side by side before the old key is retired. Nothing is rewritten in one big bang.
  2. Money rows are never lost. Bets, take-profit and ruin events, deposits and withdrawals, and the state mirror commit with full durability. Rows are never updated in place when history matters: they are appended, and the current value is a separate row or a view.
  3. Deleting means flagging. Bots, loaders and accounts get removed_at, removed_by and a restore window. A permanent delete is a separate, owner-only action with the control password.
  4. Every owner action is audited in hub.audit_log, which the application role can append to but never change or delete.
  5. Every configurable value has a catalogue row (hub.setting_defs): its type, section, label, default, limits, which levels it may be set at, and the version that introduced it. The Settings dashboard, Studio and the research page read the catalogue; no default lives only in code.
  6. Time is always timestamptz in UTC. Amounts are numeric (never float). Money rows carry the currency and the unit (bits, USDT).
  7. Big append-only tables are partitioned by month (round log, events, crash history, audit) so deleting old data is a fast DROP of a partition, not a slow DELETE.
  8. Least privilege by schema: the hub role cannot see the research schema; the research role cannot see accounts, sessions or secrets.
create table hub.kv (
k text primary key,
v jsonb,
vb bytea, -- only for values that are not plain JSON (adapter tags them)
updated_at timestamptz not null default now()
) with (fillfactor = 70); -- room for in-place updates of hot keys
create index kv_prefix on hub.kv (k text_pattern_ops); -- fast storage.list({prefix})
create table hub.alarms (
id smallint primary key default 1 check (id = 1), -- one alarm, as in a Durable Object
due_at timestamptz not null
);
create table hub.schema_migrations (
id text primary key, applied_at timestamptz not null default now(), checksum text not null
);

Key families stored here on day one (from the Worker): auth:user:, auth:sess:, auth:meta, auth:setup:, auth:lock:, auth:code:, auth:pref:, bot:<id>, rlm: and rlc: (round log), loader:, loader:tok:, lstate:, lgone:, inst:n:, inst:tok:, inst:held, rel:published:, rel:history:, rel:cur:, blocked:, crh: and crhm: (crash history), cust:audit, cust:preset:, backup:*, rates, usdtPrice, updates, realtime, deepmode, hiddenscripts, control, budget, stuck:alert, quota:alert, tg:muted.

Show the code (80 lines)
create table hub.users (
id bigint generated always as identity primary key,
username citext not null unique,
display_name text,
password_hash text not null, -- the hash the existing auth core produces
totp_secret_enc bytea, -- encrypted with a key from the env file
totp_enabled boolean not null default false,
status text not null default 'active' check (status in ('active','locked','disabled')),
failed_count int not null default 0,
locked_until timestamptz,
must_change_pw boolean not null default false,
last_login_at timestamptz,
created_at timestamptz not null default now(),
created_by bigint references hub.users(id)
);
create table hub.roles (
id smallint generated always as identity primary key,
name text not null unique, -- owner, operator, viewer, and custom roles later
description text,
is_system boolean not null default false
);
create table hub.permissions (key text primary key, description text not null);
create table hub.role_permissions (
role_id smallint references hub.roles(id) on delete cascade,
permission_key text references hub.permissions(key) on delete cascade,
primary key (role_id, permission_key)
);
create table hub.accounts ( -- a customer or the owner's own workspace
id bigint generated always as identity primary key,
name text not null,
kind text not null default 'customer' check (kind in ('owner','customer','staff')),
status text not null default 'active',
created_at timestamptz not null default now(),
removed_at timestamptz
);
create table hub.account_members (
account_id bigint references hub.accounts(id),
user_id bigint references hub.users(id),
role_id smallint not null references hub.roles(id),
added_at timestamptz not null default now(),
primary key (account_id, user_id)
);
create table hub.platform_accounts ( -- one betting-site account of a customer
id bigint generated always as identity primary key,
account_id bigint not null references hub.accounts(id),
platform text not null check (platform in ('bustabit','coinscrash','bcgame')),
label text not null,
created_at timestamptz not null default now(),
removed_at timestamptz,
unique (account_id, platform, label)
);
create table hub.auth_sessions (
id bytea primary key, -- sha256 of the cookie token; the token itself is never stored
user_id bigint not null references hub.users(id) on delete cascade,
created_at timestamptz not null default now(),
expires_at timestamptz not null, -- 12 hours
ip inet, user_agent text, revoked_at timestamptz
);
create index on hub.auth_sessions (user_id, expires_at);
create table hub.login_attempts (
id bigint generated always as identity primary key,
at timestamptz not null default now(), username text, user_id bigint, ip inet,
step text not null check (step in ('password','totp','control')), ok boolean not null
);
create index on hub.login_attempts (ip, at desc);
create table hub.control_secret ( -- the owner control password (hash only)
id smallint primary key default 1 check (id = 1), hash text not null,
rotated_at timestamptz not null default now(), rotated_by bigint references hub.users(id)
);
create table hub.control_grants ( -- single-use ~2 minute passes
id uuid primary key default gen_random_uuid(), purpose text not null, user_id bigint,
loader_id text, issued_at timestamptz not null default now(), expires_at timestamptz not null, used_at timestamptz
);
create table hub.user_prefs (user_id bigint references hub.users(id) on delete cascade, k text, v jsonb, primary key (user_id, k));
create table hub.audit_log (
id bigint generated always as identity, at timestamptz not null default now(),
actor_user_id bigint, actor_label text, action text not null, target_type text, target_id text,
detail jsonb, ip inet, primary key (id, at)
) partition by range (at);

The application role gets INSERT and SELECT on hub.audit_log only (no UPDATE, DELETE or TRUNCATE), so even a bug or a stolen hub login cannot erase the trail. Permissions in hub.permissions are the existing permission list (the owner/operator/viewer sets), loaded by a seed file, so the roles in the database behave exactly like today’s.

create table hub.loaders (
id text primary key, -- the loader's own id
account_id bigint references hub.accounts(id),
platform text, machine_label text, browser_label text, profile_label text, tab_no int,
custom_name text, status text not null default 'waiting' check (status in ('waiting','approved','blocked','gone')),
key_fingerprint text, approved_at timestamptz, approved_by bigint references hub.users(id),
loader_version text, last_seen_at timestamptz, first_seen_at timestamptz not null default now(), removed_at timestamptz
);
create table hub.loader_tokens (
token_hash bytea primary key, loader_id text not null references hub.loaders(id) on delete cascade,
kind text not null check (kind in ('pass','session','resume')), created_at timestamptz not null default now(),
expires_at timestamptz not null, used_at timestamptz
);
create table hub.bots (
id bigint generated always as identity primary key,
instance_no int, -- the number shown on the card
account_id bigint references hub.accounts(id), loader_id text references hub.loaders(id),
platform_account_id bigint references hub.platform_accounts(id), platform text not null,
name text, custom_name text, mode text not null default 'test' check (mode in ('test','live')),
status text, script_version text, first_version text, created_at timestamptz not null default now(),
removed_at timestamptz, removed_by bigint references hub.users(id), restore_until timestamptz
);
create unique index one_live_bot on hub.bots (account_id, platform) where mode = 'live' and removed_at is null;
create unique index bot_instance_active on hub.bots (instance_no) where removed_at is null;
create table hub.instance_numbers (
n int primary key, state text not null check (state in ('free','used','held')),
bot_id bigint references hub.bots(id), held_until timestamptz -- a plain delete holds the number 3 hours
);

The partial unique index enforces “one live bot per account and platform across every loader” in the database itself, not only in code.

C.3.3 Settings: the catalogue, the values in force, the history, templates and groups

Section titled “C.3.3 Settings: the catalogue, the values in force, the history, templates and groups”
Show the code (34 lines)
create table hub.setting_defs (
key text primary key, type text not null, section text, label text not null,
default_value jsonb, min_value numeric, max_value numeric, options jsonb,
levels text[] not null default '{bot}', -- which of global, platform, loader, bot may set it
since_version text, deprecated_in text, platforms text[], tooltip text
);
create table hub.settings_current (
scope text not null check (scope in ('global','platform','loader','bot')), scope_id text not null default '',
key text not null references hub.setting_defs(key), value jsonb not null,
set_by bigint references hub.users(id), set_at timestamptz not null default now(),
primary key (scope, scope_id, key)
);
create table hub.settings_history ( -- every change, never edited
id bigint generated always as identity primary key, at timestamptz not null default now(),
scope text not null, scope_id text not null, key text not null,
old_value jsonb, new_value jsonb, set_by bigint, reason text, bot_id bigint, epoch_id bigint
);
create index on hub.settings_history (scope, scope_id, at desc);
create table hub.setting_templates ( -- presets, batch test-bot presets, Studio presets, schedules
id bigint generated always as identity primary key, account_id bigint references hub.accounts(id),
kind text not null check (kind in ('preset','batch','schedule','restore_point')),
name text not null, description text, payload jsonb not null,
created_by bigint, created_at timestamptz not null default now(), updated_at timestamptz not null default now(),
unique (account_id, kind, name)
);
create table hub.setting_groups ( -- the recovery-target groups of doc 65 C8
id bigint generated always as identity primary key, name text not null unique,
kind text not null default 'recovery_ladder', targets numeric(5,2)[] not null,
is_system boolean not null default false, sort_no int not null default 0, note text
);
create table hub.group_assignments (
scope text not null, scope_id text not null default '', group_id bigint not null references hub.setting_groups(id),
set_by bigint, set_at timestamptz not null default now(), primary key (scope, scope_id)
);

The setting_groups seed holds the groups of doc 65 C8: Easier 2.10 / 2.21, Balanced 2.25 / 2.27, A bit harder 2.29 / 2.35, Harder 2.31 / 2.47, and the two new four-rung ladder groups Frank added on 29 Nov 2026: 2.04 / 2.10 / 2.21 / 2.27 and 2.11 / 2.17 / 2.25 / 2.29. The targets column is an array, so a group may have any number of rungs.

create table hub.releases (
id bigint generated always as identity primary key, product text not null, version text not null,
sha text, status text not null default 'published' check (status in ('published','rolled_back','retired')),
notes text, published_at timestamptz not null default now(), published_by bigint, source_ref text,
unique (product, version)
);
create table hub.release_current (product text primary key, release_id bigint not null references hub.releases(id), set_at timestamptz not null default now());
create table hub.release_updates (
id bigint generated always as identity primary key, at timestamptz not null default now(),
loader_id text, bot_id bigint, from_version text, to_version text, kind text, result text
);
create table hub.deliveries ( -- watermarked single-use deliveries (E2 / S4)
id uuid primary key default gen_random_uuid(), release_id bigint references hub.releases(id), loader_id text,
user_id bigint, watermark text not null, key_id text, issued_at timestamptz not null default now(),
expires_at timestamptz not null, used_at timestamptz
);
create table hub.bot_sessions (
id bigint generated always as identity primary key, bot_id bigint not null references hub.bots(id),
session_no int not null, started_at timestamptz not null, ended_at timestamptz,
end_reason text check (end_reason in ('take_profit','ruin','manual','restart','error','stopped')),
currency text, start_bits numeric, end_bits numeric, peak_bits numeric,
bets int, wins int, max_cum_loss numeric, max_rec_level int, rec_episodes int, peak_debt numeric,
script_version text, epoch_id bigint, l2_option text, ladder_group_id bigint references hub.setting_groups(id),
extra jsonb
);
create index on hub.bot_sessions (bot_id, started_at desc);
create table hub.take_profit_events (
id bigint generated always as identity primary key, session_id bigint references hub.bot_sessions(id), bot_id bigint not null,
at timestamptz not null, tp_target numeric, achieved numeric, restart_due_at timestamptz, restarted_at timestamptz, restart_kind text
);
create table hub.ruin_events ( -- the same fields the script keeps in ruinHistory (18.8.34)
id bigint generated always as identity primary key, session_id bigint references hub.bot_sessions(id), bot_id bigint not null,
n int not null, session_at timestamptz, first_bet_at timestamptz, ruin_at timestamptz not null, dur_sec int,
start_bits numeric, end_bits numeric, bets int, peak_debt numeric, rec_episodes int, max_rec_level int,
max_rec_loss numeric, max_cum_loss numeric, reason text, restart_due_at timestamptz, restarted_at timestamptz
);
create index on hub.ruin_events (bot_id, ruin_at desc);
create table hub.money_events (
id bigint generated always as identity primary key, bot_id bigint not null, at timestamptz not null default now(),
kind text not null check (kind in ('deposit','withdrawal','tp_withdraw','adjust','settlement')),
amount numeric not null, unit text not null, balance_after numeric, source text, ref text
);
create index on hub.money_events (bot_id, at desc);
create table hub.round_log ( -- the round log (today rlm: and rlc:)
bot_id bigint not null, at timestamptz not null, game_id bigint not null, kind text not null, payload jsonb not null,
primary key (bot_id, at, game_id, kind)
) partition by range (at);
create table hub.crash_history ( -- real crash results seen by loaders (today crh: and crhm:)
platform text not null, game_id bigint not null, crash numeric(12,2) not null, at timestamptz not null,
primary key (platform, game_id, at)
) partition by range (at);

Partitions are created a month ahead by a job inside the hub; retention: round_log 90 days, crash_history kept (the daily compressed archive for research keeps the long history), events 180 days, audit 24 months.

create table hub.events (
id bigint generated always as identity, at timestamptz not null default now(), account_id bigint, bot_id bigint, loader_id text,
level text not null check (level in ('info','warn','error','critical')), kind text not null, message text, payload jsonb,
primary key (id, at)
) partition by range (at);
create table hub.alert_channels (id bigint generated always as identity primary key, account_id bigint, kind text not null default 'telegram', target text not null, enabled boolean not null default true, muted_until timestamptz);
create table hub.alert_deliveries (id bigint generated always as identity primary key, event_id bigint, sent_at timestamptz, channel_id bigint, status text, error text);
create table hub.state_snapshots (
bot_id bigint not null, version bigint not null, epoch int not null, taken_at timestamptz not null default now(),
payload bytea not null, size_bytes int not null, sha256 bytea not null, primary key (bot_id, version)
);
create table hub.state_journal (
bot_id bigint not null, version bigint not null, seq bigint not null, at timestamptz not null default now(), op jsonb not null,
primary key (bot_id, version, seq)
);
create table hub.state_fence (bot_id bigint primary key, epoch int not null, holder text, lease_until timestamptz);
create table hub.resume_codes (code_hash bytea primary key, bot_id bigint not null, created_by bigint, created_at timestamptz not null default now(), expires_at timestamptz not null, used_at timestamptz);

C.3.9 Backups, flags, rates and other small tables

Section titled “C.3.9 Backups, flags, rates and other small tables”
create table hub.backups (id bigint generated always as identity primary key, kind text not null, started_at timestamptz not null, finished_at timestamptz, bytes bigint, sha256 text, location text, status text not null, note text);
create table hub.restore_runs (id bigint generated always as identity primary key, backup_id bigint references hub.backups(id), scope text not null, started_by bigint, at timestamptz not null default now(), dry_run boolean not null default true, result jsonb);
create table hub.flags (key text primary key, value jsonb not null, updated_by bigint, updated_at timestamptz not null default now()); -- realtime, deepmode, hiddenscripts, budget, control, stuck/quota alerts
create table hub.blocked (id bigint generated always as identity primary key, kind text not null, subject text not null, until timestamptz, reason text, by_user bigint, at timestamptz not null default now());
create table hub.rates (key text primary key, value jsonb not null, fetched_at timestamptz not null default now()); -- exchange rates and USDT price
create table hub.schedules (id bigint generated always as identity primary key, scope text not null, scope_id text not null, spec jsonb not null, force boolean not null default false, enabled boolean not null default true, created_by bigint, created_at timestamptz not null default now());

C.3.10 Per-user control password (designed now, built right after the migration)

Section titled “C.3.10 Per-user control password (designed now, built right after the migration)”

Today one control password exists, owned by the owner (hub.control_secret). Every user gets their own. Nothing changes for the owner during the migration: the migration copies today’s owner password as it is, and the per-user tables are switched on in step W10 (C.8).

create table hub.user_control_secrets (
user_id bigint primary key references hub.users(id) on delete cascade,
hash text not null, -- hash of the random control password; the password itself is never stored
rotated_at timestamptz not null default now(),
rotated_by bigint references hub.users(id),
failed_count int not null default 0,
locked_until timestamptz,
last_used_at timestamptz,
shown_once boolean not null default false -- true once the user has seen the new password
);
-- which actions need it is a permission on the role:
alter table hub.role_permissions add column requires_control boolean not null default false;
-- hub.control_grants already has user_id: a grant is single use, about 2 minutes, for one purpose.

Rules:

  1. The password is generated by the server (random, 24 characters in groups of four, from an alphabet without look-alike characters), shown once when the account is created or the password is rotated, and stored only as a hash made with the same function as sign-in passwords.
  2. An action whose permission has requires_control = true needs a single-use grant from the caller’s own control password; the owner’s actions that need it today keep needing it.
  3. Five wrong tries lock the control password for 15 minutes and send a Telegram alert; every use, failure, lock and rotation is written to hub.audit_log.
  4. The owner can rotate anyone’s password; a user can rotate their own after signing in with the authenticator code.
  5. A control password is never shown again. A lost one is rotated, not recovered.

C.3.11 Secrets store, key generator and reveal (designed now, built after the migration)

Section titled “C.3.11 Secrets store, key generator and reveal (designed now, built after the migration)”

During the migration secrets live only in the root-only files of F.3. After it, the owner gets a secrets page on admin.bideward.com (behind Cloudflare Access, sign-in with the authenticator code, and the control password for every change). It works like the secrets pages of Cloudflare and other hosts, locked down harder because here the page itself holds the secrets.

create table hub.secrets (
name text primary key, -- for example TELEGRAM_BOT_TOKEN
class text not null check (class in ('app','integration','generated')),
revealable boolean not null default false, -- may the owner reveal it with the control password?
current_version int not null default 0,
rotates_every_days int,
description text,
created_at timestamptz not null default now()
);
create table hub.secret_versions (
name text references hub.secrets(name) on delete cascade,
version int not null,
ciphertext bytea not null, -- AES-256-GCM
nonce bytea not null,
key_id text not null, -- which master key encrypted it
status text not null check (status in ('current','overlap','retired')),
set_by bigint references hub.users(id),
set_at timestamptz not null default now(),
valid_until timestamptz, -- end of the overlap window of a replaced version
last_used_at timestamptz,
primary key (name, version)
);

Behaviour:

  1. Write-only. The page shows “set”, the version, who changed it and when. It never shows the value again.
  2. Generate. A button like the ones on other hosts: the server makes a random value with the system’s secure random source; you choose the length (16 to 64 bytes) and hex or base64url. The value is shown once with a Copy button, and is stored only after you tick “I have saved it”.
  3. Rotate. The new value becomes current and the old one stays valid as “overlap” until the window you set ends (for example 24 hours), so bots and loaders using the old key keep working while you update them. Then the old version is retired. For keys the hub checks on every request (for example the ingestion key) the hub accepts both during the overlap.
  4. Reveal. Only for secrets marked revealable. It needs the control password each time, shows the value for 30 seconds, writes an audit entry and sends a Telegram alert. These never become revealable: the master key, the database login, the tunnel token and the control passwords.
  5. Third-party values (the Telegram token, the GitHub token) can be pasted in; if lost, get a new one from the source.
  6. What stays in files: the database login (a Unix socket, no password), TUNNEL_TOKEN, and SECRETS_MASTER_KEY (the key that encrypts this table). They are needed before the page can run, so they live in /etc/bideward, root-only.
  7. Not generated here: the age private key for backups. It is made on your computer and stays offline.

The existing research service tables (research_meta, research_bots, research_epochs, research_sessions, research_switches, research_events, research_patterns, research_decisions, research_articles, research_crash_days, research_groups, research_audit, research_state) are created by the research service’s own migration, with their existing owner_ref and class columns and row rules, inside schema research. They are fed by the bots’ res65 record, as designed in the earlier version of this guide. Nothing there changes in this migration.

New for the research page (built after the migration): read-only views in schema research over hub tables, so the page never needs a second copy of the data: research.v_tp_ruin (take-profit and ruin details per bot and session), research.v_l2_options (how each Layer 2 option performed), research.v_ladder_groups (sessions per ladder group), research.v_settings_epochs (settings in force over time) and research.v_user_analysis (the per-account page of doc 65 C9). Exact columns are confirmed against research/schema.mjs when the views are written.

What is saved Where How it is restored
Every setting change hub.settings_history Settings page, History tab: pick a time and Restore. The page shows a before-and-after list, needs the control password for global changes, writes a new history row and an audit row. Nothing is overwritten: restore is itself a change.
Named restore points (“Save current settings as…”) hub.setting_templates, kind restore_point Choose the point, Preview, Apply to a bot, a loader, a platform or all.
Presets, batch test-bot presets, Studio presets hub.setting_templates Apply or duplicate.
A removed bot or loader removed_at plus restore_until; instance number held in hub.instance_numbers Removed bots list, Restore by name or number. After restore_until, an owner-only permanent delete frees the number.
A running bot’s state hub.state_snapshots plus hub.state_journal, guarded by hub.state_fence (epoch) Resume by a single-use code (hub.resume_codes). A bot that resumes takes a higher epoch, so a stale copy can never write.
The whole database Nightly pg_dump (custom format), kept 14 days on the box, copy to Drive, Lightsail snapshots Part J.
The app data (as today) Existing Drive backup (JSON) Existing Restore route; used for the first import in Part G.
Per-account export A job that writes the account’s rows to one file Owner only; used before closing an account.

Safe-restore rules: every restore first runs as a dry run (hub.restore_runs, dry_run true) showing exactly what will change; the real run needs the control password; it never deletes newer rows without listing them; it is audited; after it the dashboard shows a banner “restored from <point> by <user>”.

C.6 What the Research page reads from the database

Section titled “C.6 What the Research page reads from the database”
Research view Source tables
Layer 2 options (which option, since when, results, switches) research_patterns, research_switches, hub.bot_sessions.l2_option, research.v_l2_options
Take profit details (target, achieved, time to reach, restart delay) hub.take_profit_events, hub.bot_sessions
Ruin details (count, depth, peak debt, recovery level, duration, restart) hub.ruin_events, hub.bot_sessions
Settings in force and changes over time hub.settings_history, hub.settings_current, research_epochs
Recovery ladder groups and results per group hub.setting_groups, hub.group_assignments, hub.bot_sessions.ladder_group_id
Pattern ranking and decisions log research_patterns, research_decisions
Per-account analysis (customers) hub.accounts, hub.bot_sessions, hub.money_events, research.v_user_analysis
Crash statistics hub.crash_history and the daily archive (research_crash_days)
Technical articles research_articles
Today (Layer 1 key family) Becomes (Layer 2) Step
auth:user:, auth:sess:, auth:lock:, auth:code:, auth:pref:, auth:meta, auth:setup: hub.users, auth_sessions, login_attempts, user_prefs, control_secret W2
loader:, loader:tok:, lstate:, lgone: hub.loaders, loader_tokens W3
bot:<id>, inst:n:, inst:tok:, inst:held hub.bots, instance_numbers W3
rel:published:, rel:history:, rel:cur: hub.releases, release_current, release_updates W3
cust:preset:, cust:audit hub.setting_templates, hub.audit_log W4
(settings inside bot:<id>) hub.settings_current, settings_history W4
(sessions, take profit and ruin inside bot payloads) hub.bot_sessions, take_profit_events, ruin_events W5
rlm:, rlc: hub.round_log W6
crh:, crhm: hub.crash_history W6
realtime, deepmode, hiddenscripts, control, budget, stuck:alert, quota:alert, tg:muted, blocked: hub.flags, hub.blocked, hub.alert_channels W7
rates, usdtPrice, updates hub.rates W7
backup:* hub.backups W7

C.8 The order the tables are switched on (after the migration)

Section titled “C.8 The order the tables are switched on (after the migration)”
Step What Why this order
W1 Migration itself: Layer 1 only, plus hub.schema_migrations, hub.backups, hub.audit_log Reproduces today’s behaviour exactly.
W2 Users, roles, permissions, sessions, login attempts, audit Accounts and roles are the first thing the new features need.
W3 Loaders, bots, instance numbers, releases Gives bots a real identity and enforces one live bot per account and platform in the database.
W4 Settings catalogue, current values, history, templates, groups Restore points and the recovery groups.
W5 Sessions, take-profit and ruin events The Research page’s TP and ruin details.
W6 Round log and crash history (partitioned) The biggest tables; moved once the rest is stable.
W7 Flags, rates, alerts, backups registry Small tables last.
W8 State mirror and resume codes (S1 and S3) Needs W3.
W9 Research views Needs W5 and W4.
W10 Per-user control password (C.3.10) Needs W2; the owner’s current password is copied as it is.
W11 Secrets store, generator and reveal (C.3.11) Needs W2 and W10.

For each step the hub writes to both places for a few days and compares them; only when they match is the old key family retired. A switch per family (hub.flags) turns the new table on or off without a deployment.

C.9 Changing the design later (the schema-change policy)

Section titled “C.9 Changing the design later (the schema-change policy)”

EXPLAIN — why: new features will need new tables and sometimes new columns. This policy keeps a deploy from ever breaking running code or losing data.

  1. Every change is a numbered SQL file in db/migrations (0002_…, 0003_…), applied in order by db/migrate.mjs and recorded with a checksum in hub.schema_migrations. Nobody edits a table by hand. An applied migration is never edited; a mistake is fixed by a new file.
  2. Add first, remove last (expand and contract). To change a column: (a) add the new column as nullable or with a default; (b) deploy code that writes both; (c) backfill the old rows in small batches; (d) deploy code that reads only the new one; (e) after at least one release and a backup, drop the old column in its own migration. A rename is an add, a copy and a drop, never an in-place rename.
  3. New tables link to what exists. A new table that belongs to a person, account, bot or loader carries a foreign key to hub.users, hub.accounts, hub.bots or hub.loaders. Use bigint identity keys and timestamptz, and a jsonb detail column only for data that is never filtered on.
  4. New settings need no migration: a row in hub.setting_defs (C.3.3) is enough.
  5. Rehearse every migration. Before the real database, the runner restores the newest dump into a scratch database (J.4 B), applies the new file there and runs the checks.
  6. Automatic backup first. The runner takes a dump (J.3) before it touches the real database and refuses to run if the dump fails.
  7. Safe on a live table. A migration sets lock_timeout and statement_timeout, adds indexes with CREATE INDEX CONCURRENTLY, adds constraints as NOT VALID and validates them afterwards. The big tables (round_log, crash_history) are partitioned, so a change touches one partition at a time.
  8. Forward-only. There is no automatic undo. A failed migration is fixed by a restore (L.1, level 3) or by a new corrective file.
  9. A data dictionary. Every table and column has a SQL comment, and a script prints the dictionary into docs/database/ so the documentation always shows the real schema.

← Previous: Part B. PostgreSQL: install, tune, secure (Phase P2) · Guide index · Next: Part D. Cloudflare: every setting, in order →