Skip to main content

Hub schema

The tables and their state semantics, in their comments. The other schemas: cloud, watch; the architecture describes the parts they belong to.

-- Excubio hub database schema, v1.
--
-- Reference DDL. The sqlx migrations in crates/ex-store-hub/migrations
-- build this schema; `mise run check-schema-drift` compares the two
-- (pg_dump --schema-only) and fails on a difference. Targets PostgreSQL
-- 18 (docs/operations.md §1), no extensions. Embedded and external
-- Postgres use the same schema.
--
-- Conventions:
-- * hub scope (docs/architecture.md §12): a database is an installation
-- that serves one hub or many (§0). Every table with a hub_id column
-- is hub data: hub_id is its first column and the first column of its
-- primary key, natural keys are unique per hub (revision and change
-- set numbers, an alert's namespace and key, a Secret's versions, the
-- audit chain's seq, a blob's hash, a bundle), and references between
-- hub tables are composite foreign keys over (hub_id, …), so a row can
-- only point into its own hub; a reference that clears on delete
-- clears its own column only (ON DELETE SET NULL (column)). Row-level
-- security (§11) hides the other hubs' rows. Tables without hub_id are
-- installation-wide.
-- * every transaction on hub data first sets excubio.hub_id for the
-- transaction (§11), and every query names its hub besides: a filter
-- on hub_id, a hub_id in every row it writes.
-- * ids: uuid (v7, generated by the application) unless noted.
-- * revisions, change set numbers: bigint, monotonic per hub (r1, r2, …;
-- CS-1, …).
-- * hashes: bytea (SHA-256, 32 bytes).
-- * timestamps: timestamptz.
-- * vocabularies: an enum type for lifecycle states, a text CHECK otherwise.
-- * durable tasks (actions, operations) run on absurd, whose pinned SQL is
-- installed in schema "absurd" by the first migration (docs/stack.md §2);
-- rows here reference absurd task ids where needed, and a task's
-- parameters name its hub. absurd's queues are installation-wide.
-- Schema "absurd" is absurd's own and not part of this reference: the
-- drift check leaves it out.
-- * all objects live in schema "excubio"; reporting views in
-- "reporting_v1"; both, and schema "absurd", owned by excubio_hub_owner.
-- * queries name the objects of "excubio" unqualified: a node's
-- connections search it, and the database's default search_path is it
-- when the migration login may set that (the block below). A sandbox
-- session's temporary tables, which Postgres searches first for
-- relations, shadow the tables they name (docs/pipeline.md §12); they
-- carry hub_id like the tables they shadow.
-- * roles (§11): excubio_hub_owner, excubio_hub_app, excubio_hub_lookup
-- and excubio_reporting are group roles without login. Roles belong to
-- the cluster, not to the database, so the schema creates them only
-- when they are missing (the block below): a first migration by a
-- superuser or a login with CREATEROLE creates them, and on a cluster
-- where the administrator created them beforehand the block changes
-- nothing. The migration login must be able to SET ROLE
-- excubio_hub_owner; everything after the block is created as
-- excubio_hub_owner, and so is every later migration. The drift check
-- compares the objects, policies and functions with their owners and
-- grants (scripts/check-schema-drift); the migration tests check what
-- the roles may do (crates/ex-store-hub/tests).

DO $$
DECLARE r text;
BEGIN
FOREACH r IN ARRAY ARRAY['excubio_hub_owner', 'excubio_hub_app', 'excubio_hub_lookup', 'excubio_reporting'] LOOP
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = r) THEN
BEGIN
EXECUTE format('CREATE ROLE %I NOLOGIN', r);
EXCEPTION WHEN duplicate_object OR unique_violation THEN
NULL; -- created by a concurrent migration of another database
END;
END IF;
END LOOP;
-- excubio_hub_owner hands the lookup functions to excubio_hub_lookup (§11).
IF NOT pg_has_role('excubio_hub_owner', 'excubio_hub_lookup', 'MEMBER') THEN
BEGIN
GRANT excubio_hub_lookup TO excubio_hub_owner;
EXCEPTION WHEN duplicate_object OR unique_violation THEN
NULL;
END;
END IF;
IF NOT has_database_privilege('excubio_hub_owner', current_database(), 'CREATE') THEN
EXECUTE format('GRANT CREATE ON DATABASE %I TO excubio_hub_owner', current_database());
END IF;
END $$;

DO $$
BEGIN
IF (SELECT rolsuper FROM pg_roles WHERE rolname = current_user)
OR pg_has_role(current_user, (SELECT datdba FROM pg_database WHERE datname = current_database()), 'USAGE') THEN
EXECUTE format('ALTER DATABASE %I SET search_path = excubio', current_database());
END IF;
END $$;

SET ROLE excubio_hub_owner;
CREATE SCHEMA IF NOT EXISTS excubio;
SET search_path = excubio;

-------------------------------------------------------------------------------
-- 0. Installation and hubs (docs/architecture.md §12)
-------------------------------------------------------------------------------

-- The installation: exactly one row, written by init (docs/cli.md §6).
-- standalone: it serves the one hub init creates, enrolled with a token
-- and never provisioned through the installation channel, as a customer's
-- own installation is; managed: init --managed, its hubs provisioned by
-- the cloud through the installation channel, as every installation the
-- vendor runs is, which the cloud registers as shared or dedicated
-- (docs/operations.md §1).
-- partitions is the count of the event order's partitions (§4), fixed at
-- init (--partitions); correlator_shards and link_shards the counts of
-- correlator shards and link shards that the hubs' correlator_shard and
-- link_shard choose from, fixed at init too (--correlator-shards,
-- --link-shards; docs/architecture.md §4 Installations).
-- operator_hub: the hub whose admins operate the installation (its nodes,
-- holidays and audit policy) and where its own conditions are raised
-- (docs/pipeline.md §19): a standalone installation's one hub; on a
-- managed one the vendor's hub the provisioning names, never a
-- tenant's, and NULL until then.
CREATE TABLE installation (
singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),
kind text NOT NULL CHECK (kind IN ('managed', 'standalone')),
partitions int NOT NULL CHECK (partitions BETWEEN 1 AND 1024),
correlator_shards int NOT NULL DEFAULT 1 CHECK (correlator_shards BETWEEN 1 AND 1024),
link_shards int NOT NULL DEFAULT 1 CHECK (link_shards BETWEEN 1 AND 1024),
operator_hub uuid, -- FK below
created_at timestamptz NOT NULL DEFAULT now()
);

-- active: serves. suspended: intake and paging go on, management writes
-- are refused. deleting: refused everywhere until its rows are gone.
CREATE TYPE hub_state AS ENUM ('active', 'suspended', 'deleting');

-- The hubs of the installation, the registry every node loads. A hub is
-- the tenant's unit: its own spec, certificate, link sequence, allowlist,
-- audit chain, data keys, relays and host name. id is the cloud's id of
-- the hub when the cloud provisions it, else a UUIDv7 of init; a hub runs
-- before it enrols, and enrolment fills cloud_hub_id and tenant_id
-- (docs/operations.md §2). host (<host label>.<hub domain>) and
-- mail_domain name it to the front door (docs/architecture.md §11;
-- lookup_hub_by_host, lookup_hub_by_mail_domain, §11), given by the
-- cloud's provisioning or init --host. auth: the OIDC issuer of its logins
-- with the organization and the tenant a login must name (keys issuer,
-- org, tenant; an absent key isn't required), from the provisioning; a
-- standalone installation writes its [auth] here at the start.
-- Its events go to lanes partitions from lane_base on (modulo the
-- installation's partitions: hub_lanes, §4); correlator_shard and
-- link_shard choose its correlator and link owner. The creation assigns
-- them (docs/architecture.md §4 Installations, Partitions): a hub with
-- lanes = partitions has lane_base 0, any other the partition that the
-- fewest hubs' lanes include, and each shard is the one with the fewest
-- hubs, the lowest of a tie; none of the four changes afterwards
-- (hub_layout), as a change would move the hub's open alerts and timers
-- to another owner. retention_tier is the list partition of its events
-- (§5) and sets their horizon (docs/compliance.md §2), from the
-- installation and the hub's limits (hub_layout): standard on a standalone
-- installation, whose Settings retention alone sets it; on a managed one
-- d30, d90 or d396 by limits.retention_days (30, 90 or 396; absent: 396).
-- limits: what it may use (keys as the cloud's tenant.limits).
CREATE TABLE hub (
id uuid PRIMARY KEY,
cloud_hub_id uuid UNIQUE, -- the cloud's hub id, from enrolment
tenant_id uuid, -- the cloud's tenant, from enrolment
name text NOT NULL,
host text UNIQUE CHECK (host = lower(host)), -- the host name its UI, API and intake answer on
mail_domain text UNIQUE CHECK (mail_domain = lower(mail_domain)), -- the domain of its e-mail intake addresses
auth jsonb NOT NULL DEFAULT '{}' CHECK (jsonb_typeof(auth) = 'object'),
lanes int NOT NULL CHECK (lanes >= 1),
lane_base int NOT NULL DEFAULT 0 CHECK (lane_base >= 0),
correlator_shard int NOT NULL DEFAULT 0 CHECK (correlator_shard >= 0),
link_shard int NOT NULL DEFAULT 0 CHECK (link_shard >= 0),
retention_tier text NOT NULL DEFAULT 'standard' CHECK (retention_tier IN ('standard', 'd30', 'd90', 'd396')),
limits jsonb NOT NULL DEFAULT '{}' CHECK (jsonb_typeof(limits) = 'object'),
state hub_state NOT NULL DEFAULT 'active',
created_at timestamptz NOT NULL DEFAULT now(),
CHECK ((cloud_hub_id IS NULL) = (tenant_id IS NULL))
);

ALTER TABLE installation ADD FOREIGN KEY (operator_hub) REFERENCES hub(id);

-- A hub's layout lies within the installation's (lanes at most its
-- partitions, lane_base and the shards below their counts) and is fixed;
-- its retention tier follows the installation's kind and its limits.
CREATE FUNCTION hub_layout() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $$
DECLARE
i record;
days text := coalesce(NEW.limits->>'retention_days', '396');
BEGIN
SELECT kind, partitions, correlator_shards, link_shards INTO STRICT i FROM excubio.installation;
IF TG_OP = 'UPDATE' THEN
IF (NEW.lanes, NEW.lane_base, NEW.correlator_shard, NEW.link_shard)
IS DISTINCT FROM (OLD.lanes, OLD.lane_base, OLD.correlator_shard, OLD.link_shard) THEN
RAISE EXCEPTION 'a hub''s lanes, lane_base, correlator_shard and link_shard are fixed for its life';
END IF;
ELSIF NEW.lanes > i.partitions OR NEW.lane_base >= i.partitions
OR NEW.correlator_shard >= i.correlator_shards OR NEW.link_shard >= i.link_shards THEN
RAISE EXCEPTION 'the hub''s lanes and shards lie outside the installation''s partitions and shards';
END IF;
IF days NOT IN ('30', '90', '396') THEN
RAISE EXCEPTION 'retention_days is 30, 90 or 396, not %', days;
END IF;
NEW.retention_tier := CASE WHEN i.kind = 'standalone' THEN 'standard' ELSE 'd' || days END;
RETURN NEW;
END
$$;

CREATE TRIGGER hub_layout BEFORE INSERT OR UPDATE ON hub FOR EACH ROW EXECUTE FUNCTION hub_layout();

-- Every node holds the registry in memory and reads it again on
-- NOTIFY excubio_hub (docs/architecture.md §12): a change of the hubs or
-- the installation notifies with an empty payload, a change of a hub's
-- data keys with the hub's id, whose keys the node unwraps again.
CREATE FUNCTION registry_changed() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
PERFORM pg_notify('excubio_hub', '');
RETURN NULL;
END
$$;

CREATE FUNCTION data_keys_changed() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
PERFORM pg_notify('excubio_hub', NEW.hub_id::text);
RETURN NULL;
END
$$;

CREATE TRIGGER hub_registry AFTER INSERT OR UPDATE OR DELETE ON hub FOR EACH STATEMENT EXECUTE FUNCTION registry_changed();
CREATE TRIGGER installation_registry AFTER INSERT OR UPDATE ON installation FOR EACH STATEMENT EXECUTE FUNCTION registry_changed();

-- The reporting logins (docs/integrations.md §12): a login of
-- excubio_reporting reads the views of the hub its row names, whatever it
-- sets; a login without a row reads nothing. Written by the installation's
-- administrator (docs/operations.md §1).
CREATE TABLE reporting_login (
login name PRIMARY KEY,
hub_id uuid NOT NULL REFERENCES hub
);

-- A hub set deleting is unreadable at once, also to its reporting logins,
-- whose rows go (docs/compliance.md §5); hub_delete deletes its other rows
-- later.
CREATE FUNCTION hub_deleting() RETURNS trigger
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
BEGIN
DELETE FROM excubio.reporting_login r WHERE r.hub_id = NEW.id;
RETURN NULL;
END
$$;
CREATE TRIGGER hub_deleting AFTER UPDATE OF state ON hub FOR EACH ROW WHEN (NEW.state = 'deleting') EXECUTE FUNCTION hub_deleting();

-- Each hub's metered usage per UTC day (docs/architecture.md §12 Limits;
-- docs/pipeline.md §2): installation data about the hub, as the registry
-- is, so it carries hub and not hub_id and no hub scope; the
-- provisioning client reads every hub's rows in one query and sends them
-- (docs/api/cloud.yaml reportUsage), and a hub's API shows its own
-- (docs/api/hub.yaml getUsage). Every node adds the events its intake
-- stored and refused, by reason, every 5 s in one statement for all
-- hubs (refused_hub_rate: above limits.events_per_second; _daily_quota:
-- above three times limits.events_per_day; _source_rate: a Source above
-- pipeline.sourceRate). stored_in: the bytes stored that day, each event's
-- compressed payload and 600 bytes for its row, indexes and decision.
-- The gauges are measured every 5 min: cis of the active snapshot,
-- sources of the active revision, relays enrolled and not revoked
-- (hub_usage_gauges, §13), and stored_bytes, the stored_in of the days
-- within the hub's retention (limits.retention_days, else 396), an
-- estimate that needs no scan of the shared tables. quota_notice: the
-- highest share of limits.events_per_day the hub was told of that day
-- (80, 100; docs/pipeline.md §19), so each is given once. Rows are kept
-- 400 days: the cloud takes reports 35 days back, and stored_bytes sums
-- the longest retention.
CREATE TABLE hub_usage (
hub uuid NOT NULL REFERENCES hub ON DELETE CASCADE,
day date NOT NULL,
events_received bigint NOT NULL DEFAULT 0,
refused_hub_rate bigint NOT NULL DEFAULT 0,
refused_daily_quota bigint NOT NULL DEFAULT 0,
refused_source_rate bigint NOT NULL DEFAULT 0,
stored_in bigint NOT NULL DEFAULT 0,
cis bigint,
sources int,
relays int,
stored_bytes bigint,
quota_notice smallint NOT NULL DEFAULT 0 CHECK (quota_notice IN (0, 80, 100)),
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub, day)
);

-- The installation's client of the cloud's installation channel
-- (docs/operations.md §4; docs/api/cloud.yaml tag installation) on a
-- managed installation: one row once init --managed enrolled
-- the installation with its token. Its client certificate names
-- installation:<id>; key_sealed is its key, sealed under the deployment
-- key with the associated data installation_link:key, as it belongs to no
-- hub. poll_cursor: the cursor of the last poll (pollInstallation), 0
-- before the first, which lists every hub. usage_day: the last UTC day
-- whose usage the cloud took (reportUsage). failing_since: since when
-- every call on the channel failed (docs/pipeline.md §19). Written by the
-- node that holds the client's lock (class 13, docs/architecture.md §4).
CREATE TABLE installation_link (
singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),
installation_id uuid NOT NULL,
cert_pem text NOT NULL,
cert_expires_at timestamptz NOT NULL,
key_sealed bytea NOT NULL,
poll_cursor bigint NOT NULL DEFAULT 0 CHECK (poll_cursor >= 0),
usage_day date,
failing_since timestamptz,
enrolled_at timestamptz NOT NULL DEFAULT now()
);

-- Each hub the cloud placed on the installation: its desired state as the
-- last poll gave it (an InstallationHub) and when it came, and how far
-- the client got. next_at: when the client applies the desired state
-- next, NULL once it is applied and reported; a new state, a refused
-- link and a failure (after a backoff) set it. reported: what the cloud
-- took last, provisioned or failed, with the reason the
-- tenant's admins read; attempts: the failures in a row. enrolled_at: when
-- the client last stored the hub's certificate; link_refused_at: when the
-- cloud last refused it on the hub's link (written by the holder of the
-- hub's link shard), which makes the client enrol the hub again. hub is
-- the cloud's id of the hub, which is its id here too. Installation data,
-- as hub_usage: no hub_id, no hub scope, and the row outlives the hub's
-- own row until the cloud took the report of its deletion.
CREATE TABLE installation_hub (
hub uuid PRIMARY KEY,
desired jsonb NOT NULL CHECK (jsonb_typeof(desired) = 'object'),
received_at timestamptz NOT NULL DEFAULT now(),
next_at timestamptz DEFAULT now(),
reported text CHECK (reported IN ('provisioned', 'failed')),
reason text,
attempts int NOT NULL DEFAULT 0,
enrolled_at timestamptz,
link_refused_at timestamptz
);

-------------------------------------------------------------------------------
-- 1. Identity and access
-------------------------------------------------------------------------------

-- Replica of the cloud's teams of the hub's tenant (docs/architecture.md
-- §3). Written only by the cloud link. Spec files reference teams by slug.
CREATE TABLE team (
hub_id uuid NOT NULL REFERENCES hub,
slug text NOT NULL CHECK (slug ~ '^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$'),
name text NOT NULL,
mail text, -- notification address
idp_group text, -- IdP group whose members are the team
replica_seq bigint NOT NULL, -- link sequence of the last change
PRIMARY KEY (hub_id, slug)
);

-- Replica of the cloud's rotations; spec validation (L1) checks page
-- actions against it.
CREATE TABLE rotation (
hub_id uuid NOT NULL REFERENCES hub,
team text NOT NULL,
slug text NOT NULL,
name text NOT NULL,
PRIMARY KEY (hub_id, team, slug),
FOREIGN KEY (hub_id, team) REFERENCES team (hub_id, slug) ON DELETE CASCADE
);

-- Users of the hub UI and API: OIDC subjects, the local break-glass admin,
-- and service accounts (kind 'service', act through API tokens only).
-- The local admin's password is generated at init (docs/operations.md §2);
-- failed_logins and locked_until hold its lockout (docs/architecture.md §11).
CREATE TABLE app_user (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
kind text NOT NULL CHECK (kind IN ('oidc', 'local', 'service')),
issuer text,
subject text,
display_name text NOT NULL,
password_hash text, -- argon2, local only
failed_logins int NOT NULL DEFAULT 0, -- local only
locked_until timestamptz, -- local only
groups text[] NOT NULL DEFAULT '{}', -- from the last login's group claim
created_at timestamptz NOT NULL DEFAULT now(),
last_login_at timestamptz,
PRIMARY KEY (hub_id, id),
UNIQUE (hub_id, issuer, subject)
);

-- Role bindings (docs/architecture.md §10). The subject is a user or an IdP
-- group; the scope is a team or the whole hub (scope_team NULL). Bindings
-- of approver, admin and secret-admin are 'pending' until a second admin
-- confirms them; the creator cannot confirm. The local admin's bindings, and
-- the hub-wide admin bindings of `excubio-hub admin grant` (created_by
-- NULL; docs/cli.md §6), are 'active' at once while no active hub-wide
-- admin binding of an oidc user or a group exists; the sole admin's are
-- 'active' at once while they are the sole admin (docs/architecture.md §10).
CREATE TABLE role_binding (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
user_id uuid,
idp_group text,
role text NOT NULL CHECK (role IN ('viewer', 'responder', 'author', 'approver', 'operator', 'admin', 'secret-admin')),
scope_team text,
state text NOT NULL DEFAULT 'active' CHECK (state IN ('pending', 'active')),
created_by uuid,
created_at timestamptz NOT NULL DEFAULT now(),
confirmed_by uuid,
confirmed_at timestamptz,
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, user_id) REFERENCES app_user (hub_id, id) ON DELETE CASCADE,
FOREIGN KEY (hub_id, scope_team) REFERENCES team (hub_id, slug) ON DELETE CASCADE,
FOREIGN KEY (hub_id, created_by) REFERENCES app_user (hub_id, id),
FOREIGN KEY (hub_id, confirmed_by) REFERENCES app_user (hub_id, id),
CHECK ((user_id IS NULL) <> (idp_group IS NULL)),
CHECK (role NOT IN ('admin', 'secret-admin') OR scope_team IS NULL),
CHECK (confirmed_by IS NULL OR confirmed_by <> created_by)
);

-- API tokens (exk_…), stored as hashes. roles narrows the owner's roles.
CREATE TABLE api_token (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
user_id uuid NOT NULL,
name text NOT NULL,
token_hash bytea NOT NULL,
roles text[], -- NULL = all of the owner's roles
selector jsonb, -- NULL = no restriction (docs/architecture.md §10)
scopes text[], -- tickets: only these calls; NULL = roles apply
expires_at timestamptz,
last_used_at timestamptz,
revoked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, id),
UNIQUE (hub_id, token_hash),
FOREIGN KEY (hub_id, user_id) REFERENCES app_user (hub_id, id) ON DELETE CASCADE
);

-- Intake tokens (exi_…), one or more per Source name. The activation of a
-- revision without the Source revokes its tokens (revoked_at), so a Source
-- added again under the name starts without tokens.
CREATE TABLE intake_token (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
source text NOT NULL,
token_hash bytea NOT NULL,
created_by uuid,
created_at timestamptz NOT NULL DEFAULT now(),
last_used_at timestamptz,
revoked_at timestamptz,
PRIMARY KEY (hub_id, id),
UNIQUE (hub_id, token_hash),
FOREIGN KEY (hub_id, created_by) REFERENCES app_user (hub_id, id)
);

-- UI sessions (docs/architecture.md §11). expires_at is the end of the
-- session's longest life, counted from created_at; a session without a
-- request since last_seen_at for the idle time has ended too. A node
-- writes last_seen_at at most once a minute per session. Ended sessions
-- are deleted daily.
CREATE TABLE web_session (
hub_id uuid NOT NULL REFERENCES hub,
id bytea NOT NULL, -- SHA-256 of the cookie value
user_id uuid NOT NULL,
csrf_token text NOT NULL,
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
last_seen_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, user_id) REFERENCES app_user (hub_id, id) ON DELETE CASCADE
);

-- A sign-in of the hub UI by OIDC (docs/architecture.md §11 Sign-in):
-- started on the hub's host (startOidcLogin) with its state, PKCE
-- verifier, nonce and the UI path to return to, sealed under the hub's
-- data key, and the SHA-256 of the binding cookie ex_login, which only the
-- browser that started it holds. The IdP returns to the installation's
-- one callback (completeOidcLogin), which finds the login by the hub its
-- state names and the state's hash, once, signs the user in and sets the
-- SHA-256 of a code that hands the login over to the hub's host within
-- 60 s, once, from the same browser (redeemLoginHandoff, which deletes the
-- row). Expired rows are deleted with the ended sessions.
CREATE TABLE login_attempt (
hub_id uuid NOT NULL REFERENCES hub,
state_hash bytea NOT NULL,
pending_sealed bytea NOT NULL,
binding_hash bytea NOT NULL,
handoff_hash bytea,
user_id uuid,
expires_at timestamptz NOT NULL,
PRIMARY KEY (hub_id, state_hash),
UNIQUE (hub_id, handoff_hash),
FOREIGN KEY (hub_id, user_id) REFERENCES app_user (hub_id, id) ON DELETE CASCADE,
CHECK ((handoff_hash IS NULL) = (user_id IS NULL))
);

-- Idempotency keys of API writes per caller (user or token), kept 24 h;
-- semantics as docs/schema/cloud.sql idempotency_key.
CREATE TABLE idempotency_key (
hub_id uuid NOT NULL REFERENCES hub,
caller text NOT NULL, -- user:<id>, token:<id>
key text NOT NULL,
request_hash bytea NOT NULL,
status int,
response jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, caller, key)
);

CREATE INDEX idempotency_key_age ON idempotency_key (hub_id, created_at);

-------------------------------------------------------------------------------
-- 2. Spec: blobs, revisions, change sets (docs/spec-format.md)
-------------------------------------------------------------------------------

-- File contents, content-addressed (canonical TOML) within the hub: a
-- store shared by hubs would tell one hub whether another holds a file.
CREATE TABLE spec_blob (
hub_id uuid NOT NULL REFERENCES hub,
hash bytea NOT NULL,
content text NOT NULL,
PRIMARY KEY (hub_id, hash)
);

-- Immutable revisions. level is the routing level of the revision's
-- Settings "routing" (docs/spec-format.md §7).
CREATE TABLE revision (
hub_id uuid NOT NULL REFERENCES hub,
number bigint NOT NULL,
tree_hash bytea NOT NULL, -- hash over (path, blob hash) pairs
level int NOT NULL,
change_set bigint, -- NULL for r1 (empty spec)
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, number)
);

CREATE TABLE revision_file (
hub_id uuid NOT NULL REFERENCES hub,
revision bigint NOT NULL,
path text NOT NULL,
blob bytea NOT NULL,
kind text NOT NULL,
name text NOT NULL,
owner text NOT NULL, -- team slug from metadata.owner
PRIMARY KEY (hub_id, revision, path),
UNIQUE (hub_id, revision, kind, name),
FOREIGN KEY (hub_id, revision) REFERENCES revision (hub_id, number),
FOREIGN KEY (hub_id, blob) REFERENCES spec_blob (hub_id, hash)
);

-- One row per hub: its active revision. Moved by a merge.
CREATE TABLE active_revision (
hub_id uuid PRIMARY KEY REFERENCES hub,
revision bigint NOT NULL,
activated_at timestamptz NOT NULL, -- as in its activation_log row (§4)
activated_by uuid,
FOREIGN KEY (hub_id, revision) REFERENCES revision (hub_id, number),
FOREIGN KEY (hub_id, activated_by) REFERENCES app_user (hub_id, id)
);

-- draft: being edited; L0/L1 run on every write.
-- validating: submitted; L2 tests and L3 replay run as an operation.
-- failed: validation failed; edit to return to draft.
-- in_review: valid; waiting for the approvals in requirements.
-- merged: revision created (merged_revision).
-- closed: abandoned.
CREATE TYPE change_set_state AS ENUM ('draft', 'validating', 'failed', 'in_review', 'merged', 'closed');

CREATE TABLE change_set (
hub_id uuid NOT NULL REFERENCES hub,
number bigint NOT NULL,
title text NOT NULL,
author uuid NOT NULL,
base_revision bigint NOT NULL,
state change_set_state NOT NULL DEFAULT 'draft',
validation jsonb, -- diagnostics per level, test results
impact jsonb, -- replay summary per team (docs/spec-format.md §6)
requirements jsonb, -- required approvals and why
merged_revision bigint,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, number),
FOREIGN KEY (hub_id, author) REFERENCES app_user (hub_id, id),
FOREIGN KEY (hub_id, base_revision) REFERENCES revision (hub_id, number),
FOREIGN KEY (hub_id, merged_revision) REFERENCES revision (hub_id, number)
);

-- The overlay: changed files of a change set. blob NULL deletes the path.
CREATE TABLE change_set_file (
hub_id uuid NOT NULL REFERENCES hub,
change_set bigint NOT NULL,
path text NOT NULL,
blob bytea,
PRIMARY KEY (hub_id, change_set, path),
FOREIGN KEY (hub_id, change_set) REFERENCES change_set (hub_id, number) ON DELETE CASCADE,
FOREIGN KEY (hub_id, blob) REFERENCES spec_blob (hub_id, hash)
);

-- Reviews. A review counts only for the change set's current validation;
-- a new submit invalidates earlier approvals (stale = true). Reviewers are
-- users of kind oidc or local, never API tokens (docs/spec-format.md §6);
-- a reviewer who is the change set's author is the hub's sole admin, whose
-- self-approval counts only while it is allowed.
CREATE TABLE change_set_review (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
change_set bigint NOT NULL,
reviewer uuid NOT NULL,
verdict text NOT NULL CHECK (verdict IN ('approve', 'reject')),
for_team text, -- the requirement it satisfies
comment text,
stale boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, change_set) REFERENCES change_set (hub_id, number) ON DELETE CASCADE,
FOREIGN KEY (hub_id, reviewer) REFERENCES app_user (hub_id, id)
);

-- The built-in holiday regions of Calendars (docs/spec-format.md §3.17),
-- the same as the cloud's, installation-wide: written from the
-- installation's holiday file at a node's start (docs/operations.md §2),
-- each region with exactly the file's days; a region the file doesn't name
-- stays.
CREATE TABLE holiday_region (
code text PRIMARY KEY, -- e.g. DE-RP
name text NOT NULL
);

CREATE TABLE holiday (
region text NOT NULL REFERENCES holiday_region(code) ON DELETE CASCADE,
day date NOT NULL,
name text NOT NULL,
PRIMARY KEY (region, day)
);

-------------------------------------------------------------------------------
-- 3. Inventory (docs/pipeline.md §15)
-------------------------------------------------------------------------------

-- importing: being read, by the absurd task task_id; at most one per
-- source. accepted: passed the source's guards; the source's last good
-- import, at most one per source, and the only state with content: merges
-- read it, and nothing else does (snapshots are stored as versions, below,
-- and replay reads those). unchanged: the read gave the content of
-- the source's last good import (same content_hash); nothing is stored or
-- merged, and it counts as the source's newest import for
-- inventory.maxAge. rejected: failed the guards or the read, or its task
-- lost its claim (below); never merged. superseded: an older accepted
-- import; the transaction that accepts the next one sets it and clears its
-- content, and the row (counts, report) stays for the import history
-- until the inventory history's horizon (docs/compliance.md §2), as do
-- unchanged and rejected rows.
--
-- A node that dies leaves its import in importing. absurd gives the task
-- to another node once its claim has expired; the retry first sets the
-- row of the lost attempt to rejected (report: node lost), which frees
-- inventory_import_one_running, and reads again. Merges
-- (inventory_snapshot importing) and operations (§8, running) are tied to
-- their task the same way.
CREATE TYPE import_state AS ENUM ('importing', 'accepted', 'unchanged', 'rejected', 'superseded');

-- One row per import. The normalised records (CIs, aliases, services,
-- service aliases, CI–service links, maintenance windows) are one
-- zstd-compressed blob per import, not rows.
CREATE TABLE inventory_import (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
source text NOT NULL, -- InventorySource name
state import_state NOT NULL DEFAULT 'importing',
revision bigint NOT NULL, -- source definition in effect
counts jsonb NOT NULL DEFAULT '{}', -- records per kind
report jsonb, -- guard results, errors
content_hash bytea, -- SHA-256 of the normalised records in canonical order
content bytea, -- the records as zstd-compressed NDJSON; set only while accepted
started_at timestamptz NOT NULL DEFAULT now(),
finished_at timestamptz,
task_id uuid, -- absurd task of the attempt
CHECK ((state = 'accepted') = (content IS NOT NULL)),
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, revision) REFERENCES revision (hub_id, number)
);

-- One import of a source at a time; one last good import per source.
CREATE UNIQUE INDEX inventory_import_one_running ON inventory_import (hub_id, source) WHERE state = 'importing';
CREATE UNIQUE INDEX inventory_import_last_good ON inventory_import (hub_id, source) WHERE state = 'accepted';
-- The imports by their start, newest first (listInventoryImports).
CREATE INDEX inventory_import_started ON inventory_import (hub_id, started_at, id);

-- importing: the merge is being computed, by the absurd task task_id; at
-- most one merge at a time. active: the one in use (at most one).
-- superseded: an older snapshot, all of whose versions are kept.
-- expired: activated before the inventory history's horizon
-- (docs/compliance.md §2); its versions are partly dropped, so it can't be
-- loaded. rejected: failed the Settings inventory guards; never used,
-- nothing written.
CREATE TYPE snapshot_state AS ENUM ('importing', 'active', 'superseded', 'expired', 'rejected');

-- Installation-wide: a hub's snapshot numbers increase, with the gaps of
-- the other hubs' activations.
CREATE SEQUENCE inventory_snapshot_number;

CREATE TABLE inventory_snapshot (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
number bigint, -- from inventory_snapshot_number at activation; versions refer to it
state snapshot_state NOT NULL DEFAULT 'importing',
revision bigint NOT NULL, -- InventoryModel in effect (TeamMaps apply at enrichment, docs/pipeline.md §4)
imports uuid[] NOT NULL, -- the import of each source merged
counts jsonb NOT NULL DEFAULT '{}', -- rows per table in the snapshot
changes jsonb NOT NULL DEFAULT '{}', -- versions added and ended per table
report jsonb, -- per source: records, merged, ambiguous, placeholder values, unmapped classes
started_at timestamptz NOT NULL DEFAULT now(),
finished_at timestamptz,
activated_at timestamptz, -- as in its activation_log row (§4)
task_id uuid, -- absurd task of the merge
CHECK ((state IN ('importing', 'rejected')) = (number IS NULL)),
PRIMARY KEY (hub_id, id),
UNIQUE (hub_id, number),
FOREIGN KEY (hub_id, revision) REFERENCES revision (hub_id, number)
);

CREATE UNIQUE INDEX inventory_snapshot_one_active ON inventory_snapshot (hub_id) WHERE state = 'active';
CREATE UNIQUE INDEX inventory_snapshot_one_merge ON inventory_snapshot (hub_id) WHERE state = 'importing';

-- Snapshot versions (docs/pipeline.md §15), in current and history tables.
-- Each inv_* table holds the versions of the active snapshot, each with
-- valid_from, the number of the snapshot that introduced it. Its
-- inv_*_history table holds the ended versions with valid_to, the number of
-- the snapshot that ended it, and ended_at, that snapshot's activated_at.
-- Snapshot n holds the current rows with valid_from <= n and the history
-- rows with valid_from <= n < valid_to. The merge compares its result with
-- the active snapshot and, in the activating transaction, moves the
-- versions that were removed or changed to history (valid_to = n) and
-- inserts the new ones (valid_from = n). Which source records make up a CI
-- is not part of a version (inv_ci_record), so a source that lags behind
-- the others creates no versions. References between versions are by id
-- and hold in every snapshot by construction, so they are not foreign
-- keys.
--
-- History tables are partitioned by day of ended_at (UTC), each day
-- holding every hub's versions; the implementation creates partitions
-- ahead, and the retention job drops the partitions whose day lies wholly
-- before the inventory history's horizon (docs/compliance.md §2), both
-- through the functions of §11. Replay loads a snapshot and then reads the later
-- snapshots' changes in batches of snapshots, by valid_from and ended_at,
-- never one query per snapshot (docs/pipeline.md §15).

CREATE TABLE inv_ci (
hub_id uuid NOT NULL REFERENCES hub,
id text NOT NULL, -- source-qualified id (docs/pipeline.md §15 Merge step 5)
valid_from bigint NOT NULL,
name text NOT NULL,
class text NOT NULL, -- Excubio class (docs/pipeline.md §15)
type text, -- the source's class or type
subtype text,
grp text, -- the CI's own assignment group
grp_source text, -- the InventorySource grp came from; enrichment maps grp with its teamMap (docs/pipeline.md §4)
attrs jsonb NOT NULL DEFAULT '{}', -- attr_* values, without the prefix
PRIMARY KEY (hub_id, id)
);

CREATE INDEX inv_ci_from ON inv_ci (hub_id, valid_from);

CREATE TABLE inv_ci_history (
LIKE inv_ci INCLUDING DEFAULTS INCLUDING CONSTRAINTS,
valid_to bigint NOT NULL,
ended_at timestamptz NOT NULL,
CHECK (valid_to > valid_from)
) PARTITION BY RANGE (ended_at);

CREATE TABLE inv_ci_history_default PARTITION OF inv_ci_history DEFAULT;
CREATE INDEX inv_ci_history_from ON inv_ci_history (hub_id, valid_from);

-- The source records merged into each CI of the active snapshot, outside
-- the versions: the CI's sources in the CI view, and what keeps a CI's id
-- while any of its records remains (docs/pipeline.md §15). The activating
-- transaction rewrites the rows of the records that changed CI.
CREATE TABLE inv_ci_record (
hub_id uuid NOT NULL REFERENCES hub,
source text NOT NULL, -- InventorySource name
ref text NOT NULL, -- the record's id in its source
ci_id text NOT NULL,
PRIMARY KEY (hub_id, source, ref)
);

CREATE INDEX inv_ci_record_ci ON inv_ci_record (hub_id, ci_id);

-- Lower-cased aliases for node matching and identity: host names, FQDNs,
-- IP addresses, serials, VM UUIDs, references to other systems' ids.
-- Placeholder values are never aliases.
CREATE TABLE inv_alias (
hub_id uuid NOT NULL REFERENCES hub,
alias text NOT NULL,
ci_id text NOT NULL,
valid_from bigint NOT NULL,
kind text NOT NULL CHECK (kind IN ('fqdn', 'host', 'ip', 'serial', 'vm-uuid', 'ref')),
PRIMARY KEY (hub_id, alias, ci_id)
);

CREATE INDEX inv_alias_from ON inv_alias (hub_id, valid_from);

CREATE TABLE inv_alias_history (
LIKE inv_alias INCLUDING DEFAULTS INCLUDING CONSTRAINTS,
valid_to bigint NOT NULL,
ended_at timestamptz NOT NULL,
CHECK (valid_to > valid_from)
) PARTITION BY RANGE (ended_at);

CREATE TABLE inv_alias_history_default PARTITION OF inv_alias_history DEFAULT;
CREATE INDEX inv_alias_history_from ON inv_alias_history (hub_id, valid_from);

CREATE TABLE inv_service (
hub_id uuid NOT NULL REFERENCES hub,
id text NOT NULL,
valid_from bigint NOT NULL,
name text NOT NULL,
criticality int, -- higher is more critical
hours text CHECK (hours IN ('24x7', 'office')),
grp text, -- ITSM assignment group
grp_source text, -- as inv_ci.grp_source
itsm_ref text,
parent_id text, -- service hierarchy; attributes already inherited at merge
attrs jsonb NOT NULL DEFAULT '{}',
PRIMARY KEY (hub_id, id)
);

CREATE INDEX inv_service_from ON inv_service (hub_id, valid_from);

CREATE TABLE inv_service_history (
LIKE inv_service INCLUDING DEFAULTS INCLUDING CONSTRAINTS,
valid_to bigint NOT NULL,
ended_at timestamptz NOT NULL,
CHECK (valid_to > valid_from)
) PARTITION BY RANGE (ended_at);

CREATE TABLE inv_service_history_default PARTITION OF inv_service_history DEFAULT;
CREATE INDEX inv_service_history_from ON inv_service_history (hub_id, valid_from);

-- Lower-cased names under which events refer to a service (service hints):
-- its name, its itsm_ref and the sources' service aliases.
CREATE TABLE inv_service_alias (
hub_id uuid NOT NULL REFERENCES hub,
alias text NOT NULL,
service_id text NOT NULL,
valid_from bigint NOT NULL,
PRIMARY KEY (hub_id, alias, service_id)
);

CREATE INDEX inv_service_alias_from ON inv_service_alias (hub_id, valid_from);

CREATE TABLE inv_service_alias_history (
LIKE inv_service_alias INCLUDING DEFAULTS INCLUDING CONSTRAINTS,
valid_to bigint NOT NULL,
ended_at timestamptz NOT NULL,
CHECK (valid_to > valid_from)
) PARTITION BY RANGE (ended_at);

CREATE TABLE inv_service_alias_history_default PARTITION OF inv_service_alias_history DEFAULT;
CREATE INDEX inv_service_alias_history_from ON inv_service_alias_history (hub_id, valid_from);

CREATE TABLE inv_ci_service (
hub_id uuid NOT NULL REFERENCES hub,
ci_id text NOT NULL,
service_id text NOT NULL,
valid_from bigint NOT NULL,
PRIMARY KEY (hub_id, ci_id, service_id)
);

CREATE INDEX inv_ci_service_from ON inv_ci_service (hub_id, valid_from);

CREATE TABLE inv_ci_service_history (
LIKE inv_ci_service INCLUDING DEFAULTS INCLUDING CONSTRAINTS,
valid_to bigint NOT NULL,
ended_at timestamptz NOT NULL,
CHECK (valid_to > valid_from)
) PARTITION BY RANGE (ended_at);

CREATE TABLE inv_ci_service_history_default PARTITION OF inv_ci_service_history DEFAULT;
CREATE INDEX inv_ci_service_history_from ON inv_ci_service_history (hub_id, valid_from);

-- Maintenance windows from the sources. id is stable across snapshots
-- (hash of source, CI or service, and start). While its snapshot is active,
-- a window is also a downtime of origin inventory with the same id
-- (docs/pipeline.md §8).
CREATE TABLE inv_maintenance (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
valid_from bigint NOT NULL,
ci_id text,
service_id text,
starts_at timestamptz NOT NULL,
ends_at timestamptz NOT NULL CHECK (ends_at > starts_at),
reason text,
CHECK ((ci_id IS NULL) <> (service_id IS NULL)),
PRIMARY KEY (hub_id, id)
);

CREATE INDEX inv_maintenance_from ON inv_maintenance (hub_id, valid_from);

CREATE TABLE inv_maintenance_history (
LIKE inv_maintenance INCLUDING DEFAULTS INCLUDING CONSTRAINTS,
valid_to bigint NOT NULL,
ended_at timestamptz NOT NULL,
CHECK (valid_to > valid_from)
) PARTITION BY RANGE (ended_at);

CREATE TABLE inv_maintenance_history_default PARTITION OF inv_maintenance_history DEFAULT;
CREATE INDEX inv_maintenance_history_from ON inv_maintenance_history (hub_id, valid_from);

-------------------------------------------------------------------------------
-- 4. Processing state, alerts (docs/architecture.md §4, docs/pipeline.md §6–§11)
-------------------------------------------------------------------------------

-- Nodes of the installation, which serve all of its hubs; written by each
-- node at start and every 5 s; a node whose last_seen_at is older than 15 s
-- is shown as down in the status.
-- The spreading of partitions counts the nodes with a lock connection
-- instead (application_name excubio-lock:<name> in pg_stat_activity), which
-- the server ends with the node's session (docs/architecture.md §4). A
-- row is deleted when its node leaves the installation (docs/cli.md §6
-- leave, docs/api/hub.yaml removeNode), which also forgets the node's
-- channel heartbeat instances in every hub (docs/pipeline.md §5).
CREATE TABLE hub_node (
name text PRIMARY KEY, -- host name, or [server] node_name
version text NOT NULL,
started_at timestamptz NOT NULL,
last_seen_at timestamptz NOT NULL,
relay_address text -- host:port where relays reach the node ([server] relay_address); NULL: it takes no relays (docs/architecture.md §13)
);

-- Partition ownership with a fencing epoch, installation-wide: a partition
-- holds the events and commands of every hub whose lanes include it, in
-- one sequence. A node that takes the advisory lock of a partition
-- increments epoch; every step transaction of the partition first runs
-- SELECT 1 FROM partition_owner WHERE partition = $1 AND epoch = $2 FOR SHARE
-- and aborts without a row. A previous owner's in-flight step either commits
-- before the increment (which waits for its share lock) or aborts after it.
--
-- Order (docs/architecture.md §4): each step reads its clock with
-- step_clock (below), which holds the activation lock in shared mode only
-- around the read:
-- SELECT pg_advisory_lock_shared(<activation>);
-- T := greatest(clock_timestamp(), last_received_at + 1 µs,
-- (SELECT max(activated_at) FROM activation_log) + 1 µs);
-- SELECT pg_advisory_unlock_shared(<activation>);
-- with the latest activation of any hub. It then finds the hubs with work
-- in the partition and how many rows each has unnumbered, up to the
-- batch B (pending_hubs, §13), and shares B among the H hubs with rows:
-- if H <= B each gets up to s rows, s the largest share with
-- sum(min(rows, s)) <= B; else the first B hubs in the order of their ids
-- from next_hub on, wrapping around, one row each. next_hub then moves to
-- the hub after the last one that got rows. Hub by hub, each in a
-- savepoint and under the hub's scope (a slice), the step numbers the
-- hub's share of its events and commands with seq IS NULL: seq =
-- last_seq + 1, … and received_at = T, events before commands, each by
-- stored_at and id (an order that means nothing beyond the numbering), so
-- a hub's positions in the partition increase with gaps where other hubs'
-- items were numbered; it reads the hub's activations before T from
-- activation_log in a subsequent statement and processes the slice. A
-- slice that fails rolls back to its savepoint, and the next slice takes
-- its positions. Once everything numbered up to T is processed, the step
-- sets processed_to = T, also when it numbered nothing or left rows
-- unnumbered. Correlator shards number their hubs' commands the same way
-- (correlator_owner).
CREATE TABLE partition_owner (
partition int PRIMARY KEY, -- 0 … partitions-1
node text NOT NULL,
epoch bigint NOT NULL,
since timestamptz NOT NULL DEFAULT now(),
last_seq bigint NOT NULL DEFAULT 0, -- last position given
last_received_at timestamptz NOT NULL DEFAULT '-infinity', -- T of the last numbering
-- received_at up to which everything of the partition is processed;
-- the partition's timers due before it may fire. A hub's global
-- watermark is the lowest over its lanes (hub_lanes).
processed_to timestamptz NOT NULL DEFAULT '-infinity',
next_hub uuid -- the cursor of the fair share: the hub the next round starts at; no FK, a hub may go
);

-- The partitions of a hub's lanes (hub.lanes from hub.lane_base, modulo
-- the installation's partitions) and its correlator's partition
-- -(correlator_shard + 1): the owners a command for every owner goes to
-- (command), read from the registry, which isn't a hub's data.
CREATE FUNCTION hub_lanes(hub uuid) RETURNS SETOF int
LANGUAGE sql STABLE SET search_path = pg_catalog, pg_temp AS $$
SELECT (h.lane_base + l) % i.partitions FROM excubio.hub h, excubio.installation i, generate_series(0, h.lanes - 1) l
WHERE h.id = hub ORDER BY 1
$$;

CREATE FUNCTION hub_correlator(hub uuid) RETURNS int
LANGUAGE sql STABLE SET search_path = pg_catalog, pg_temp AS $$
SELECT -1 - h.correlator_shard FROM excubio.hub h WHERE h.id = hub
$$;

-- A step's clock T (above) after the partition's last_received_at, read
-- under the activation lock (class 2) in shared mode, which it releases
-- before it returns, also on an error, so the lock never outlives the
-- statement. It reads the activations of every hub, so it is one of the
-- lookup functions (§13): it returns the time and nothing of a hub. now
-- is a simulated clock that stands in for the database's, NULL for the
-- database's: with it, the time is a sandbox's (docs/pipeline.md §12),
-- the later of now and after, which a simulated clock may equal.
CREATE FUNCTION step_clock(after timestamptz, now timestamptz) RETURNS timestamptz
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE
t timestamptz;
BEGIN
PERFORM pg_advisory_lock_shared(2, 0);
BEGIN
t := greatest(coalesce(now, clock_timestamp()), after + CASE WHEN now IS NULL THEN interval '1 microsecond' ELSE interval '0' END,
(SELECT max(activated_at) FROM excubio.activation_log) + interval '1 microsecond');
EXCEPTION WHEN OTHERS OR query_canceled THEN
PERFORM pg_advisory_unlock_shared(2, 0);
RAISE;
END;
PERFORM pg_advisory_unlock_shared(2, 0);
RETURN t;
END
$$;

-- Every activation of a spec revision or an inventory snapshot, and
-- every start and end of a downtime (docs/architecture.md §4,
-- docs/pipeline.md §8). The activating transaction writes what it
-- activates, then takes pg_advisory_lock(<activation>) in a statement of
-- its own, then inserts its row here with activation_clock (§13):
-- activated_at = greatest(clock_timestamp(), L + 1 µs, A + 1 µs)
-- where L is the greatest last_received_at of partition_owner and
-- correlator_owner (every hub's numbering) and A the installation's latest
-- activated_at here, commits and releases the lock. So an activation is
-- never before an event already numbered, and a numbering after it gives
-- later times (partition_owner), also after a failover to a database
-- server whose clock is behind. The lock is the installation's because a
-- step's processed_to speaks for every hub of its partition. The revision
-- and snapshot an event or command of a hub is processed with are those
-- of the hub's latest row of each kind with activated_at < its
-- received_at, live and in replay; they are read here, never inferred
-- from active_revision or inventory_snapshot, and never another hub's.
-- Kept as long as events (docs/compliance.md §2).
CREATE TABLE activation_log (
hub_id uuid NOT NULL REFERENCES hub,
id bigint GENERATED ALWAYS AS IDENTITY,
kind text NOT NULL CHECK (kind IN ('revision', 'snapshot', 'downtime-start', 'downtime-end')),
ref text NOT NULL, -- revision number, snapshot id or downtime id
activated_at timestamptz NOT NULL,
PRIMARY KEY (hub_id, id)
);

CREATE INDEX activation_log_at ON activation_log (hub_id, kind, activated_at);
-- The latest of all hubs (step_clock) and of one hub.
CREATE INDEX activation_log_latest ON activation_log (activated_at);
CREATE INDEX activation_log_hub_latest ON activation_log (hub_id, activated_at);

-- Alert changes that don't come from the alert's own events, numbered into
-- the owner's sequence with its events (docs/architecture.md §4): the
-- alert's partition, or the hub's correlator, partition -(c + 1) of its
-- correlator shard c (hub_correlator; the alerts of its own kinds, group
-- changes, heartbeat instances, and calendar for the alerts it routes). origin person, api, cloud and itsm (a ticket closed in the
-- ITSM): state, not replayed; pipeline: derived from events or timers,
-- derived again in replay. Requests wait for applied_at and return result.
-- Kept as long as events (docs/compliance.md §2): replay reads the
-- commands of people and the cloud to flag what they changed.
-- An unack of origin cloud with params.only_cloud_ack undoes only an ack
-- that came from the cloud, checked when the command is applied: a
-- triggered incident leaves an ack made in the hub
-- (docs/architecture.md §5).
-- alert_id is NULL only for the kinds that select within their owner
-- (bulk-close, close-key, release, calendar), for group-merge (params
-- name both groups) and for forget of an instance without an alert. A
-- release goes to every owner of the hub, its lanes (hub_lanes) and its
-- correlator, when a downtime or a storm ends and releases the owner's
-- alerts that record it when it applies, so an alert that a step
-- suppressed after the end was written is released too; a calendar goes
-- to the same owners.
CREATE TABLE command (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
partition int NOT NULL, -- the owner; < 0 the hub's correlator
kind text NOT NULL CHECK (kind IN ('ack', 'unack', 'close', 'assign', 'bulk-close', 'close-key', 'release', 'calendar', 'group-detach', 'group-move', 'group-merge', 'forget', 'ticket')),
alert_id uuid,
params jsonb NOT NULL DEFAULT '{}', -- bulk-close: operation id and the ids of the alerts matched; close-key: the pattern and its event's id and occurred_at; release: downtime id or storm key; Calendar name, target group, reason; ticket: the ITSM ticket id the alert's ticket_ref takes
origin text NOT NULL CHECK (origin IN ('person', 'api', 'cloud', 'itsm', 'pipeline')),
actor text, -- user, token, person from the cloud, or the producing event or timer
stored_at timestamptz NOT NULL DEFAULT now(),
seq bigint, -- NULL until numbered
received_at timestamptz,
applied_at timestamptz,
result jsonb, -- what changed, or why nothing did
PRIMARY KEY (hub_id, id),
UNIQUE (hub_id, partition, seq),
CONSTRAINT command_check CHECK (alert_id IS NOT NULL OR kind IN ('bulk-close', 'close-key', 'release', 'calendar', 'group-merge', 'forget'))
);

CREATE INDEX command_unnumbered ON command (partition, hub_id, stored_at) WHERE seq IS NULL;
CREATE INDEX command_pending ON command (partition, hub_id, seq) WHERE seq IS NOT NULL AND applied_at IS NULL;
-- The retention job's deletes (docs/compliance.md §2).
CREATE INDEX command_applied ON command (hub_id, stored_at) WHERE applied_at IS NOT NULL;

CREATE TYPE alert_state AS ENUM ('open', 'acknowledged', 'closed');
CREATE TYPE severity AS ENUM ('unknown', 'normal', 'warning', 'minor', 'major', 'critical');

-- Installation-wide: a hub's alert versions increase, with gaps.
CREATE SEQUENCE alert_version_seq;

-- The lifecycle of one (namespace, key). Facts (team, service, oncall,
-- notify) are those of the latest decision, denormalised for lists and
-- selectors, which compile to SQL over these columns
-- (docs/spec-format.md §2). Times are those of the event, command or timer
-- that caused the change, never the clock at commit (docs/architecture.md
-- §4). The attributes heartbeat, storm and expect are
-- the second part of key for alerts of those kinds (docs/pipeline.md §5,
-- §7, §17). Closed alerts are deleted by the retention job
-- (docs/compliance.md §2).
CREATE TABLE alert (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
namespace text NOT NULL, -- Source name or keyNamespace; 'excubio' for own kinds
key text NOT NULL,
kind text NOT NULL CHECK (kind IN ('event', 'heartbeat', 'storm', 'group', 'expect', 'self')),
source text,
channel text,
partition int NOT NULL, -- hash of (namespace, key) mod partitions; -1 for kinds group, expect, heartbeat and storm (the correlator)
routed_by text NOT NULL CHECK (routed_by IN ('partition', 'correlator')), -- decided at open and reopen (docs/pipeline.md §16)
version bigint NOT NULL DEFAULT nextval('alert_version_seq'), -- renewed on every change; follow-up keys (docs/pipeline.md §10), the change feed (changed_xid)
state alert_state NOT NULL DEFAULT 'open',
severity severity NOT NULL,
title text NOT NULL,
description text,
node text,
check_name text,
ci text,
service_hint text, -- the mapping's service field
-- l.<key> attributes, without the prefix; every value is a string.
labels jsonb NOT NULL DEFAULT '{}'
CHECK (jsonb_typeof(labels) = 'object' AND NOT jsonb_path_exists(labels, '$.* ? (@.type() != "string")')),
-- inv.* attributes at the latest decision, flat, keys without "inv.",
-- string values: {"found": "true", "ci.class": "firewall",
-- "ci.attr.os": "linux"}. NULL: every inv.* attribute absent.
inv jsonb
CHECK (inv IS NULL OR (jsonb_typeof(inv) = 'object' AND NOT jsonb_path_exists(inv, '$.* ? (@.type() != "string")'))),
team text,
service text,
oncall boolean,
notify boolean,
-- Suppression sources, each written by the partition
-- (docs/architecture.md §4). suppression is the first by precedence
-- (docs/pipeline.md §9).
downtime_id uuid, -- the downtime this alert is suppressed by (FK below)
storm_key text, -- key of the storm alert (namespace excubio) this alert is suppressed by; set by the partition before the correlator opens that alert
suppression text NOT NULL GENERATED ALWAYS AS (CASE
WHEN downtime_id IS NOT NULL THEN 'downtime'
WHEN storm_key IS NOT NULL THEN 'storm'
ELSE 'none' END) STORED,
group_alert uuid, -- the group this alert is a member of (FK below)
group_role text CHECK (group_role IN ('cause', 'member')),
dropped text, -- reason of a drop action
first_seen timestamptz NOT NULL,
last_seen timestamptz NOT NULL,
count int NOT NULL DEFAULT 1,
reopens int NOT NULL DEFAULT 0,
expires_after interval, -- from the mapping's expires; refreshed by duplicates
acked_at timestamptz,
acked_by text, -- person name from the cloud, or a hub user
owner text, -- assigned hub user or team slug (docs/ui.md §2); not a routing attribute
owner_at timestamptz,
closed_at timestamptz,
close_reason text CHECK (close_reason IN ('clear', 'close-key', 'expired', 'auto-close', 'person', 'bulk-close', 'source', 'ticket', 'storm-end', 'members-closed', 'merged', 'forgotten', 'rule-removed')), -- docs/pipeline.md §6
close_detail text, -- rule name, user, operation id, closing event; for display
ticket_ref text, -- ITSM ticket id
source_id text, -- the source's own id (OBM event id, fingerprint)
calendars text[] NOT NULL DEFAULT '{}', -- the Calendars the latest decision read; the calendar trigger's query (docs/pipeline.md §9)
close_event uuid, -- the event that closed it (close reasons clear, close-key)
close_occurred_at timestamptz, -- that event's occurred_at; the late-problem guard (docs/pipeline.md §6)
-- The change feed (docs/api/hub.yaml listAlerts, changed_after): the
-- transaction of the latest change, set by alert_changed_xid with every
-- new version. A version can commit after a higher one, so the feed
-- serves only changes whose transaction is below
-- pg_snapshot_xmin(pg_current_snapshot()), which every transaction still
-- running is at or above, in (changed_xid, version) order; no change can
-- then commit behind a position already served.
changed_xid xid8 NOT NULL DEFAULT pg_current_xact_id(),
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, group_alert) REFERENCES alert (hub_id, id) ON DELETE SET NULL (group_alert)
);

-- One open or acknowledged alert per namespace and key in a hub; a reopen
-- reuses the closed row of the key.
CREATE UNIQUE INDEX alert_open_key ON alert (hub_id, namespace, key) WHERE state <> 'closed';
-- Close-key search over open keys (docs/pipeline.md §6): an anchored
-- literal prefix as key LIKE 'prefix%' needs the pattern operator class,
-- since alert_open_key uses the database collation.
CREATE INDEX alert_open_key_prefix ON alert (hub_id, namespace, key text_pattern_ops) WHERE state <> 'closed';
-- The same under closeKeyIgnoreCase: lower(key) LIKE 'prefix%'.
CREATE INDEX alert_open_key_lower_prefix ON alert (hub_id, namespace, lower(key) text_pattern_ops) WHERE state <> 'closed';
CREATE INDEX alert_key_closed ON alert (hub_id, namespace, key, closed_at) WHERE state = 'closed';
-- The open alerts of a Source in a partition, counted when an event would
-- open another (pipeline.maxOpenPerSource, docs/pipeline.md §6).
CREATE INDEX alert_open_source ON alert (hub_id, partition, source) WHERE state <> 'closed';
CREATE INDEX alert_feed ON alert (hub_id, changed_xid, version);
CREATE INDEX alert_state_team ON alert (hub_id, state, team, severity);
CREATE INDEX alert_closed ON alert (hub_id, closed_at) WHERE state = 'closed';
-- The orders of listAlerts by time (docs/api/hub.yaml), with the id
-- that breaks ties, so a cursor's page starts as a range of the index.
CREATE INDEX alert_first_seen ON alert (hub_id, first_seen, id);
CREATE INDEX alert_last_seen ON alert (hub_id, last_seen, id);
CREATE INDEX alert_source_id ON alert (hub_id, source_id);
CREATE INDEX alert_labels ON alert USING gin (labels);
CREATE INDEX alert_by_group ON alert (hub_id, group_alert) WHERE group_alert IS NOT NULL;
-- The alerts a downtime or a storm suppresses (their release) and those of
-- a ticket (an incident's are found through action_by_target); the open
-- alerts whose decision read a Calendar (calendars @> ARRAY[name]).
CREATE INDEX alert_by_downtime ON alert (hub_id, downtime_id) WHERE downtime_id IS NOT NULL;
CREATE INDEX alert_by_storm ON alert (hub_id, storm_key) WHERE storm_key IS NOT NULL;
CREATE INDEX alert_by_ticket ON alert (hub_id, ticket_ref) WHERE ticket_ref IS NOT NULL;
CREATE INDEX alert_open_calendars ON alert USING gin (calendars) WHERE state <> 'closed';

CREATE FUNCTION alert_changed_xid() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $$
BEGIN
NEW.changed_xid := pg_current_xact_id();
RETURN NEW;
END
$$;

CREATE TRIGGER alert_changed_xid BEFORE UPDATE OF version ON alert
FOR EACH ROW EXECUTE FUNCTION alert_changed_xid();

-- ITSM tickets. With a TicketProfile groupBy, several alerts share a ticket:
-- the ticket task looks up the open ticket of (profile, group_key) under
-- this unique index, so alerts of different partitions join the same one.
-- A run's task inserts the row as creating (created_by: that run) and
-- creates the ticket in the ITSM; the other runs of the group wait for it
-- to be open; when the creating run has ended without it, the next of them
-- takes the create over (created_by). Should the creating node die in
-- between, the run's next attempt creates it again; for sm9, whose
-- creates carry no key the ITSM deduplicates by, create_key marks a
-- create sent without a known outcome, which is looked up by the
-- profile's keyField or, without one, fails the ticket instead of being
-- sent again (docs/integrations.md §5). The runs of a ticket have its ref
-- as target_ref. polled_at: the last poll of an sm9 ticket for a close
-- upstream.
CREATE TABLE ticket (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
profile text NOT NULL,
group_key text NOT NULL, -- joined groupBy values; the alert id without groupBy
ref text, -- ITSM ticket id, once created
state text NOT NULL CHECK (state IN ('creating', 'open', 'resolved', 'released', 'closed-upstream', 'failed')), -- released: its last alert closed with onAlertClose annotate or none (docs/pipeline.md §10); failed: its create isn't sent again
opened_at timestamptz NOT NULL DEFAULT now(),
closed_at timestamptz,
created_by uuid, -- FK below
polled_at timestamptz,
create_key text, -- the idempotency key of the create sent, which a run taking the create over sends again
PRIMARY KEY (hub_id, id)
);

CREATE UNIQUE INDEX ticket_open_group ON ticket (hub_id, profile, group_key) WHERE state IN ('creating', 'open');
CREATE INDEX ticket_ref ON ticket (hub_id, ref) WHERE ref IS NOT NULL;

-- Every state change of an alert with its cause: open, reopen, ack, unack,
-- severity change, suppression change, close. History for the alert view,
-- the audit and DORA evidence (docs/compliance.md §4). at is the
-- received_at of the causing event or command, or the due time of the
-- timer (docs/architecture.md §4); ordinal orders the transitions of one
-- alert that share it (a close and a reopen in one step).
CREATE TABLE alert_transition (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
alert_id uuid NOT NULL,
at timestamptz NOT NULL,
from_state alert_state, -- NULL on open
to_state alert_state NOT NULL,
severity severity NOT NULL,
suppression text NOT NULL,
cause text NOT NULL CHECK (cause IN ('event', 'close-key', 'timer', 'rule', 'person', 'cloud', 'ticket', 'bulk-close', 'group')),
cause_ref text, -- event id, rule name, user, incident id, operation id
detail text, -- close reason, reopen count
ordinal int NOT NULL DEFAULT 0,
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, alert_id) REFERENCES alert (hub_id, id) ON DELETE CASCADE
);

CREATE INDEX alert_transition_alert ON alert_transition (hub_id, alert_id, at, ordinal);

-- Annotations: notes by people, action outcomes, write-back confirmations.
CREATE TABLE alert_annotation (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
alert_id uuid NOT NULL,
kind text NOT NULL CHECK (kind IN ('note', 'action', 'writeback', 'cloud', 'assign')),
author text NOT NULL, -- user, 'excubio', or a person from the cloud
text text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, alert_id) REFERENCES alert (hub_id, id) ON DELETE CASCADE
);

CREATE INDEX alert_annotation_alert ON alert_annotation (hub_id, alert_id);

-- Heartbeat state per Heartbeat name (spec) or channel, and instance (the
-- joined groupBy values; '' without groupBy; the node for a channel
-- heartbeat, docs/pipeline.md §5). Written only by the correlator, from
-- the beats in its inbox (docs/architecture.md §4); since is the
-- received_at of the beat, or the due time of the timer, that changed
-- state.
CREATE TABLE heartbeat_state (
hub_id uuid NOT NULL REFERENCES hub,
name text NOT NULL,
instance text NOT NULL DEFAULT '',
state text NOT NULL CHECK (state IN ('unknown', 'up', 'missing')),
last_beat_at timestamptz,
alert_id uuid, -- open missing-heartbeat alert
since timestamptz NOT NULL,
PRIMARY KEY (hub_id, name, instance),
FOREIGN KEY (hub_id, alert_id) REFERENCES alert (hub_id, id) ON DELETE SET NULL (alert_id)
);

-- Active and past storms (docs/pipeline.md §7). The partition whose count
-- crosses the threshold inserts the row (ON CONFLICT DO NOTHING on
-- storm_active), so later new alerts of the scope are suppressed at once;
-- the correlator opens the storm alert and ends the storm
-- (docs/architecture.md §4). absorbed is written once, by the correlator
-- when the storm ends: the alerts that carried its storm_key.
CREATE TABLE storm (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
rule text NOT NULL,
scope jsonb NOT NULL, -- scope attribute values
alert_id uuid, -- set by the correlator
started_at timestamptz NOT NULL,
ended_at timestamptz,
absorbed int NOT NULL DEFAULT 0,
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, alert_id) REFERENCES alert (hub_id, id) ON DELETE SET NULL (alert_id)
);

CREATE UNIQUE INDEX storm_active ON storm (hub_id, rule, scope) WHERE ended_at IS NULL;

-- Alert groups (docs/pipeline.md §16). The group itself is an alert of kind
-- group (alert_id); its members point to it with alert.group_alert.
-- forming: waiting for the pattern's wait; open: routed, accepting members
-- until accepts_until; closed: all members closed, or merged into another.
CREATE TABLE alert_group (
hub_id uuid NOT NULL REFERENCES hub,
alert_id uuid NOT NULL,
pattern text NOT NULL,
state text NOT NULL CHECK (state IN ('forming', 'open', 'closed')),
group_values jsonb NOT NULL DEFAULT '{}', -- values of the pattern's groupBy attributes
first_at timestamptz NOT NULL, -- first problem of the first member
accepts_until timestamptz NOT NULL, -- first_at + the pattern's window
cause_alert uuid,
involved text[] NOT NULL DEFAULT '{}', -- involved team slugs
merged_into uuid,
overflow int NOT NULL DEFAULT 0, -- alerts not taken beyond maxGroupSize
PRIMARY KEY (hub_id, alert_id),
FOREIGN KEY (hub_id, alert_id) REFERENCES alert (hub_id, id) ON DELETE CASCADE,
FOREIGN KEY (hub_id, cause_alert) REFERENCES alert (hub_id, id) ON DELETE SET NULL (cause_alert),
FOREIGN KEY (hub_id, merged_into) REFERENCES alert (hub_id, id) ON DELETE SET NULL (merged_into)
);

CREATE INDEX alert_group_open ON alert_group (hub_id, pattern) WHERE state <> 'closed';
CREATE INDEX alert_group_by_cause ON alert_group (hub_id, cause_alert) WHERE cause_alert IS NOT NULL;
CREATE INDEX alert_group_by_merged ON alert_group (hub_id, merged_into) WHERE merged_into IS NOT NULL;
-- The groups by their first problem (listGroups).
CREATE INDEX alert_group_first ON alert_group (hub_id, first_at, alert_id);

-- Every choice of a group's probable cause (docs/pipeline.md §16), written
-- by the correlator with the received_at of the inbox entry, command or
-- timer that changed it. With alert_group_member it is the group history
-- that replay reads (docs/pipeline.md §12): the member with the cause of a
-- time has the role cause, the others member.
CREATE TABLE alert_group_cause (
hub_id uuid NOT NULL REFERENCES hub,
group_alert uuid NOT NULL,
at timestamptz NOT NULL,
ordinal int NOT NULL DEFAULT 0, -- orders the choices of one group that share at
cause_alert uuid NOT NULL, -- no reference: the member may have left retention
PRIMARY KEY (hub_id, group_alert, at, ordinal),
FOREIGN KEY (hub_id, group_alert) REFERENCES alert_group (hub_id, alert_id) ON DELETE CASCADE
);

-- Membership history: left_at set on close, detach or move. role is the
-- member's current or last role; its history is alert_group_cause.
-- manual: changed by a person (docs/pipeline.md §16). attrs: the member's
-- selector attributes as of its latest change the correlator took, from
-- which it chooses the cause, the severity and the roles, so that they
-- don't depend on how far the member's partition is ahead.
CREATE TABLE alert_group_member (
hub_id uuid NOT NULL REFERENCES hub,
group_alert uuid NOT NULL,
alert_id uuid NOT NULL,
role text NOT NULL CHECK (role IN ('cause', 'member')),
joined_at timestamptz NOT NULL,
left_at timestamptz,
manual text, -- detach, move or merge, with the user
attrs jsonb NOT NULL DEFAULT '{}',
PRIMARY KEY (hub_id, group_alert, alert_id, joined_at),
FOREIGN KEY (hub_id, group_alert) REFERENCES alert_group (hub_id, alert_id) ON DELETE CASCADE,
FOREIGN KEY (hub_id, alert_id) REFERENCES alert (hub_id, id) ON DELETE CASCADE
);

CREATE INDEX alert_group_member_alert ON alert_group_member (hub_id, alert_id);

-- Open expectations of ExpectRules (docs/pipeline.md §17), per rule and
-- the joined values of its correlate attributes.
CREATE TABLE expectation (
hub_id uuid NOT NULL REFERENCES hub,
rule text NOT NULL,
instance text NOT NULL,
started_at timestamptz NOT NULL, -- received_at of the start event
due_at timestamptz NOT NULL,
alert_id uuid, -- open expect alert, after the due time
PRIMARY KEY (hub_id, rule, instance),
FOREIGN KEY (hub_id, alert_id) REFERENCES alert (hub_id, id) ON DELETE SET NULL (alert_id)
);

-- Correlator ownership with a fencing epoch, as partition_owner (§4
-- above), installation-wide: one row per correlator shard, written by
-- init, which serves the hubs whose correlator_shard it is (§0), its
-- advisory lock (class 4) keyed by the shard. Shard c numbers its hubs'
-- commands as partition -(c + 1), its batch shared among them as a
-- partition's (next_hub its cursor). A step of the shard finds the hubs
-- with input up to their global watermark, timers due by it, unnumbered
-- commands or an activation since their correlator_progress
-- (correlator_hubs, §13), shares its batch among those with input, and
-- works on each in a savepoint under its scope; a hub with nothing to do
-- is not visited.
CREATE TABLE correlator_owner (
shard int PRIMARY KEY CHECK (shard >= 0),
node text NOT NULL,
epoch bigint NOT NULL,
since timestamptz NOT NULL DEFAULT now(),
last_seq bigint NOT NULL DEFAULT 0, -- numbering of its hubs' commands (partition -(shard + 1)), as partition_owner
last_received_at timestamptz NOT NULL DEFAULT '-infinity',
next_hub uuid -- the cursor of the fair share, as partition_owner's
);

-- How far a hub's correlator has worked (docs/architecture.md §4
-- Correlator): everything of the hub received up to processed_to has been
-- correlated. Written by each shard step that visits the hub: the hub's
-- global watermark when it took all the hub's input up to it, else 1 µs
-- before the received_at of the hub's next input. A hub the shard doesn't
-- visit, having nothing to correlate, keeps its row. A node keeps a hub's
-- previous inventory snapshot until processed_to has passed the
-- activation of the next.
CREATE TABLE correlator_progress (
hub_id uuid PRIMARY KEY REFERENCES hub,
processed_to timestamptz NOT NULL
);

-- Work for the correlator (docs/architecture.md §4), written in the step
-- transaction that produced it: lifecycle changes of the alerts it routes
-- (with the alert's attributes as of the change), beats, events an
-- ExpectRule observes, storm starts and the maintenance events of Sources
-- (docs/pipeline.md §8). Each entry carries the producing
-- partition, the event's or command's position and received_at, and an
-- ordinal within it. Processed in (received_at, partition, seq, ordinal)
-- order up to the hub's global watermark, interleaved with the
-- correlator's commands; deleted after.
CREATE TABLE correlator_inbox (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
partition int NOT NULL,
seq bigint, -- NULL until numbered (partition -1 only)
ordinal int NOT NULL DEFAULT 0,
received_at timestamptz,
kind text NOT NULL CHECK (kind IN ('alert-change', 'beat', 'observation', 'storm-start', 'downtime')),
ref uuid NOT NULL, -- alert-change: the alert, or the event of a duplicate that counts for a hold (docs/pipeline.md §9); beat, observation, downtime: the event; storm-start: the storm
attrs jsonb, -- alert-change: the alert's selector attributes and state as of the change
processed_at timestamptz,
CHECK (partition < 0 OR (seq IS NOT NULL AND received_at IS NOT NULL)),
PRIMARY KEY (hub_id, id)
);

CREATE INDEX correlator_inbox_pending ON correlator_inbox (hub_id, received_at, partition, seq, ordinal) WHERE processed_at IS NULL;

-- Sliding-window counts of new alerts per StormRule and scope, one row per
-- partition and minute, so partitions never contend for a row. A
-- partition's step adds to its own row and, for a storm's start, sums the
-- window over the committed rows of all partitions; the correlator, for a
-- storm's end, sums only the minutes that ended at or before the hub's
-- global watermark (docs/pipeline.md §7). Rows older than the longest window are
-- deleted.
CREATE TABLE storm_count (
hub_id uuid NOT NULL REFERENCES hub,
rule text NOT NULL,
scope jsonb NOT NULL,
partition int NOT NULL,
minute timestamptz NOT NULL,
count int NOT NULL,
PRIMARY KEY (hub_id, rule, scope, partition, minute)
);

-- Downtimes of every origin (docs/pipeline.md §8): person (created by an
-- oidc or local user), automation (by a service user), schedule
-- (DowntimeSchedule occurrence), source (a maintenance event of the Source
-- named in source), inventory (a maintenance window of the active snapshot, with the inv_maintenance id;
-- written when the snapshot activates and ended when a later one no longer
-- has it). A downtime is in force between effective_from and
-- effective_to, which are positions in the order, set under the
-- activation lock like activated_at and recorded in activation_log
-- (docs/pipeline.md §8); starts_at and ends_at are what was asked for.
-- Suppressed alerts point here (alert.downtime_id); the end releases them
-- by command (docs/architecture.md §4). Kept as long as events
-- (docs/compliance.md §2).
CREATE TABLE downtime (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
origin text NOT NULL CHECK (origin IN ('person', 'automation', 'schedule', 'source', 'inventory')),
source text, -- for origin source
CHECK ((origin = 'source') = (source IS NOT NULL)),
selector jsonb, -- structured selector
cis text[], -- CI names or ids
services text[], -- origin inventory: service ids; also their descendants
CHECK (selector IS NOT NULL OR cis IS NOT NULL OR services IS NOT NULL),
starts_at timestamptz NOT NULL,
ends_at timestamptz NOT NULL CHECK (ends_at > starts_at),
reason text NOT NULL,
notify boolean NOT NULL DEFAULT false,
schedule text, -- DowntimeSchedule name, for occurrences
created_by uuid, -- NULL for schedule occurrences
created_at timestamptz NOT NULL DEFAULT now(),
ended_early_at timestamptz,
ended_by uuid, -- who ended it early
end_reason text, -- required when ended early
effective_from timestamptz, -- NULL until its start is activated
effective_to timestamptz, -- NULL until its end is activated
needs_admin boolean NOT NULL DEFAULT false, -- a one-off downtime that needed admin to create: ending it needs admin too, and its start and end raise a self-alert
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, created_by) REFERENCES app_user (hub_id, id),
FOREIGN KEY (hub_id, ended_by) REFERENCES app_user (hub_id, id)
);

CREATE INDEX downtime_window ON downtime (hub_id, starts_at, ends_at);
CREATE INDEX downtime_in_force ON downtime (hub_id, effective_from) WHERE effective_from IS NOT NULL AND effective_to IS NULL;

ALTER TABLE alert ADD FOREIGN KEY (hub_id, downtime_id) REFERENCES downtime (hub_id, id) ON DELETE SET NULL (downtime_id);

-- Timers (docs/architecture.md §4). A partition runs the auto-close,
-- expiry and hold timers of its alerts once its processed_to has passed
-- due_at; a hold trigger of an alert the correlator routes goes to its
-- inbox. The hub's correlator (partition -(c + 1) of its shard c) runs all
-- others, and those of its own alerts, once the hub's global watermark has
-- passed due_at; its timers that change alerts of partitions write
-- commands.
CREATE TABLE timer (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
partition int NOT NULL,
due_at timestamptz NOT NULL,
kind text NOT NULL CHECK (kind IN ('heartbeat', 'auto-close', 'expiry', 'storm-end', 'downtime-start', 'downtime-end', 'calendar', 'digest', 'webhook-digest', 'hold', 'group-wait', 'expect')),
ref text NOT NULL, -- heartbeat: name and instance; auto-close, expiry: alert id; storm-end: storm id; downtime-start, downtime-end: downtime id; calendar: Calendar name; digest: digest key; webhook-digest: Webhook name; hold: alert id (the earliest end of its held runs' for); group-wait: group alert id; expect: rule and instance
PRIMARY KEY (hub_id, id),
UNIQUE (hub_id, kind, ref)
);

-- The timers due in an owner, of all its hubs (pending_hubs,
-- correlator_hubs) and of one.
CREATE INDEX timer_due ON timer (partition, due_at, hub_id);
CREATE INDEX timer_hub_due ON timer (hub_id, partition, due_at);

-------------------------------------------------------------------------------
-- 5. Events (docs/pipeline.md §2–§3)
-------------------------------------------------------------------------------

-- Every received event, normalised. Intake maps the payload with the
-- revision active when it stores the event (mapped_revision), which gives
-- the key and so the partition, and inserts the row with seq and
-- received_at NULL; the partition's next step numbers it
-- (docs/architecture.md §4). Partitioned by month of stored_at (UTC), and
-- each month by the retention tier of the event's hub (§0), which intake
-- writes with the event: the hubs of a tier share their months'
-- partitions. The retention job creates the partitions of this month and
-- the next for each tier, and drops a tier's month once it lies wholly
-- before the tier's horizon, deleting what the default partition holds
-- before it (docs/compliance.md §2), through the functions of §11. processed_at NULL: not yet run through the
-- pipeline. Outcomes: docs/pipeline.md §2, §3, §5, §6. text and jsonb can't
-- hold NUL characters; mapping replaces them (docs/pipeline.md §3), and
-- the raw payload in event_payload keeps them.
CREATE TABLE event (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
stored_at timestamptz NOT NULL DEFAULT now(), -- start of the intake transaction; partition key, and the order in which a numbering gives its events positions, which means nothing beyond it
seq bigint, -- position in the partition's sequence
received_at timestamptz, -- set with seq; orders all processing
mapped_revision bigint NOT NULL, -- revision whose Source mapping produced the fields
occurred_at timestamptz,
spooled_at timestamptz, -- when a sender or the SNMP spool held it
source text NOT NULL,
channel text NOT NULL,
namespace text NOT NULL,
partition int NOT NULL,
copy_hash bytea NOT NULL, -- sender message id or raw payload hash
copy_by_id boolean NOT NULL, -- copy_hash is a sender message id: compared within maxSpoolAge, else copyWindow (docs/pipeline.md §6)
key text, -- NULL on mapping errors
close_key text,
role text CHECK (role IN ('problem', 'resolution', 'info', 'downtime-start', 'downtime-end')),
severity severity,
title text,
node text,
check_name text,
ci text,
service_hint text,
labels jsonb NOT NULL DEFAULT '{}' -- string values, as alert.labels
CHECK (jsonb_typeof(labels) = 'object' AND NOT jsonb_path_exists(labels, '$.* ? (@.type() != "string")')),
outcome text CHECK (outcome IN ('opened', 'duplicate', 'cleared', 'clear-unmatched', 'reopened', 'late', 'copy', 'info', 'stale', 'limited', 'beat', 'downtime', 'mapping-error', 'rejected', 'error')),
alert_id uuid, -- no FK: alerts outlive and predate partitions
error text,
processed_at timestamptz,
description text, -- the mapping's description, for the alert
expires interval, -- the mapping's expires, for the alert's expires_after
close_key_ignore_case boolean NOT NULL DEFAULT false, -- the mapping's closeKeyIgnoreCase
close_key_syntax text CHECK (close_key_syntax IN ('glob', 'obm')), -- the Source's closeKeySyntax; set with close_key
duplicates_new boolean NOT NULL DEFAULT false, -- its duplicates take the new severity and fields whatever the Source's policy: an ETI value (docs/integrations.md §2)
matched jsonb, -- what an event that opened no alert matched, for the event view (docs/pipeline.md §13): event (the original of a copy, the resolution before a late problem), alert (the key's alert; for a late problem the alert a close key closed), heartbeats, downtime, limit (the Source's open alerts in the partition)
sender text, -- the sender's address as intake saw it, the one allowFrom judges (through a relay: as the relay forwarded it); NULL for events the hub made and for e-mail fetched over IMAP
relay_id uuid, -- the relay it came through; no FK: events outlive relays
retention_tier text NOT NULL, -- the hub's retention_tier when stored
PRIMARY KEY (hub_id, id, stored_at, retention_tier),
CHECK ((seq IS NULL) = (received_at IS NULL))
) PARTITION BY RANGE (stored_at);

CREATE TABLE event_default PARTITION OF event DEFAULT;
CREATE INDEX event_unnumbered ON event (partition, hub_id, stored_at) WHERE seq IS NULL;
CREATE INDEX event_pending ON event (hub_id, partition, seq) WHERE seq IS NOT NULL AND processed_at IS NULL;
CREATE INDEX event_alert ON event (hub_id, alert_id);
CREATE INDEX event_copy ON event (hub_id, namespace, copy_hash, received_at);
-- Resolutions remembered by the late-problem guard (docs/pipeline.md §6);
-- close-key resolutions are found through close_occurred_at of the closed
-- alerts (alert_key_closed).
CREATE INDEX event_resolution ON event (hub_id, namespace, key, received_at) WHERE role = 'resolution';

-- Raw payloads, kept shorter than events (docs/compliance.md §2), and
-- partitioned as events are. Replay needs them.
CREATE TABLE event_payload (
hub_id uuid NOT NULL REFERENCES hub,
event_id uuid NOT NULL,
stored_at timestamptz NOT NULL,
retention_tier text NOT NULL, -- the event's
content_type text NOT NULL, -- application/json: the channel's variables; else the payload as received (message/rfc822)
payload bytea NOT NULL, -- zstd-compressed
PRIMARY KEY (hub_id, event_id, stored_at, retention_tier)
) PARTITION BY RANGE (stored_at);

CREATE TABLE event_payload_default PARTITION OF event_payload DEFAULT;

-- Watermark per obm-upstream Source (docs/integrations.md §3), written in
-- the transaction that stores a page's events. time_changed is OBM's clock.
CREATE TABLE upstream_cursor (
hub_id uuid NOT NULL REFERENCES hub,
source text NOT NULL, -- the Source's name
time_changed timestamptz NOT NULL, -- largest time_changed read
reconciled_at timestamptz, -- last comparison with OBM's active list
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, source)
);

-------------------------------------------------------------------------------
-- 6. Routing decisions and actions (docs/pipeline.md §9–§10)
-------------------------------------------------------------------------------

-- One decision per alert change (docs/pipeline.md §9). triggers: the
-- change's own trigger first, and change when the decision also changed a
-- fact. decided_at is the received_at of the causing event or command, or
-- the due time of the timer; ordinal orders the decisions of one alert
-- that share it.
CREATE TABLE routing_decision (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
alert_id uuid NOT NULL,
triggers text[] NOT NULL CHECK (cardinality(triggers) >= 1 AND triggers <@ ARRAY['open', 'change', 'close', 'release', 'calendar', 'hold', 'group']),
revision bigint NOT NULL,
level int NOT NULL,
snapshot uuid,
group_alert uuid, -- the alert's group at the decision; members are in trace
team text,
service text,
oncall boolean,
notify boolean,
actions jsonb NOT NULL, -- ordered list: identity, parameters, rule, and started | continued | held | suppressed | dropped; suppressed_by: downtime | storm | shadow | link (a page of an ActionRule for a self-alert about the link, docs/pipeline.md §19)
trace jsonb NOT NULL, -- rules evaluated with their order, whether they matched, the values read, the first condition that failed, an ActionRule's actions and the map a Classify's value went through; suppression; attrs: the attributes routed, which route-only replay routes again (docs/pipeline.md §12); inventory: the snapshot, whether the node, CI or hint matched several CIs or services, and the sources of the CI's and the service's groups, which replay maps with each revision's TeamMaps
decided_at timestamptz NOT NULL,
ordinal int NOT NULL DEFAULT 0,
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, alert_id) REFERENCES alert (hub_id, id) ON DELETE CASCADE,
FOREIGN KEY (hub_id, revision) REFERENCES revision (hub_id, number),
FOREIGN KEY (hub_id, snapshot) REFERENCES inventory_snapshot (hub_id, id)
);

CREATE INDEX routing_decision_alert ON routing_decision (hub_id, alert_id, decided_at, ordinal);
CREATE INDEX routing_decision_decided ON routing_decision (hub_id, decided_at);

-- held: waiting for its rule's hold condition; at the hold trigger that
-- meets it, it is cancelled and a run of the next number starts; a close,
-- an ack or a decision that no longer holds it cancels it
-- (docs/pipeline.md §9).
-- pending: to start, or an attach waiting for its group alert's page.
-- active: started; follows the alert. ended: its target ended (incident
-- resolved, ticket resolved or closed, alert closed). failed: the start
-- failed after its retries. cancelled: held and cancelled, or an attach
-- whose member's own page ran instead.
CREATE TYPE action_state AS ENUM ('held', 'pending', 'active', 'ended', 'failed', 'cancelled');

-- Action runs (docs/pipeline.md §10). identity is the action's type and
-- target within the alert (page:<team>/<rotation>, attach:<group alert>,
-- ticket:<profile>, notify:<mode>:<recipients hash>, webhook:<name>,
-- fallback:<team>/<rotation> (the SMS of a self-alert about the link,
-- which the local fallback channel sends while it is active, pending until
-- it is sent and ended when the alert closes; no task, nothing goes up
-- the link: docs/pipeline.md §19),
-- writeback). A decision continues the alert's open run of an identity
-- (held, pending, active) instead of starting one; after a run ended, the
-- next decision with the identity starts run + 1. Suppressed actions
-- start no run; drop is recorded in the decision only. Follow-ups
-- (changes, the close, a reopening) carry the idempotency key plus the
-- alert version; a page run's are its messages (action_message).
CREATE TABLE action (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
alert_id uuid NOT NULL,
identity text NOT NULL,
run int NOT NULL DEFAULT 1,
type text NOT NULL CHECK (type IN ('page', 'attach', 'notify', 'ticket', 'writeback', 'webhook', 'fallback')),
params jsonb NOT NULL, -- as in the decision that started it
state action_state NOT NULL DEFAULT 'pending',
hold jsonb, -- held: the rule and its condition
started_by uuid NOT NULL,
last_decision uuid NOT NULL, -- latest decision that contained it
target_ref text, -- incident id, ticket id
idempotency_key text NOT NULL, -- alert id, identity, run
task_id uuid, -- absurd task of the start
attempts int NOT NULL DEFAULT 0,
last_error text,
updated_at timestamptz NOT NULL DEFAULT now(),
-- page: the page request, written with the run and sent unchanged on
-- every attempt and resend, so that it matches its idempotency key
request jsonb,
PRIMARY KEY (hub_id, id),
UNIQUE (hub_id, idempotency_key),
UNIQUE (hub_id, alert_id, identity, run),
FOREIGN KEY (hub_id, alert_id) REFERENCES alert (hub_id, id) ON DELETE CASCADE,
FOREIGN KEY (hub_id, started_by) REFERENCES routing_decision (hub_id, id) ON DELETE CASCADE,
FOREIGN KEY (hub_id, last_decision) REFERENCES routing_decision (hub_id, id) ON DELETE CASCADE
);

CREATE UNIQUE INDEX action_open_run ON action (hub_id, alert_id, identity) WHERE state IN ('held', 'pending', 'active');
CREATE INDEX action_open ON action (hub_id, state) WHERE state IN ('held', 'pending', 'failed');
-- The runs of an incident or a ticket, for the link's updates and the
-- ITSM's callbacks.
CREATE INDEX action_by_target ON action (hub_id, target_ref) WHERE target_ref IS NOT NULL;
-- The references a closed alert's delete cascades through
-- (docs/compliance.md §2).
CREATE INDEX action_started_by ON action (hub_id, started_by);
CREATE INDEX action_last_decision ON action (hub_id, last_decision);

ALTER TABLE ticket ADD FOREIGN KEY (hub_id, created_by) REFERENCES action (hub_id, id) ON DELETE SET NULL (created_by);

-- The up messages of a page run, in the order they are sent
-- (docs/architecture.md §5 Up): seq 0 is the run's page request; each
-- follow-up is appended in the step that decided it. kind page: a page
-- request, the run's first or, after the alert opened again, one with the
-- alert as it reads then, which rejoins the run's incident while it is
-- unresolved and opens another otherwise; its answer sets the run's
-- incident (action.target_ref). kind update: an alert update (changed,
-- closed, or detached from the alert's group: in each of the alert's open
-- page and attach runs). kind response: an ack or un-ack made in the hub
-- (type, actor, at), sent to the run's incident as it is when the message
-- goes up, with that incident appended to the key. kind group: a group
-- alert's group update (cause, involved teams), kind merge: the merge of
-- its group into another (from, into), each in the group alert's open
-- page runs, so they follow its page request. kind fallback: the report
-- of the pages the local fallback channel sent for the run's page
-- requests (docs/api/cloud.yaml fallbackDeliveries; key
-- fallback/<page key>/<last send id>), appended once the link is back; a
-- 422 link.page_unknown confirms it without retrying. body is sent
-- unchanged on every
-- attempt, so that it matches
-- idempotency_key. The run's tasks send the first unconfirmed message
-- and then the next, so a message goes up only after the cloud confirmed
-- every one before it. A replica load that finds the cloud lacking a
-- message clears confirmed_at of that message and of every later one of
-- the run, and they are sent again in order with their keys.
-- A run isn't ended while it has an unconfirmed message.
-- The ticket, webhook and writeback runs (docs/pipeline.md §10) use the
-- same outbox towards their target, sent in order by the run's task and
-- confirmed by the target's answer: kind start (ticket: the ticket to
-- create or join), change (the alert changed or opened again), close (the
-- alert closed), ack and unack (writeback: who acknowledged), event (a
-- webhook event: id, type, time and the alert as the hub API shows it,
-- docs/integrations.md §8).
CREATE TABLE action_message (
hub_id uuid NOT NULL REFERENCES hub,
action_id uuid NOT NULL,
seq int NOT NULL,
kind text NOT NULL CHECK (kind IN ('page', 'update', 'response', 'group', 'merge', 'start', 'change', 'close', 'ack', 'unack', 'event', 'fallback')),
idempotency_key text NOT NULL,
body jsonb NOT NULL,
confirmed_at timestamptz,
PRIMARY KEY (hub_id, action_id, seq),
UNIQUE (hub_id, idempotency_key),
FOREIGN KEY (hub_id, action_id) REFERENCES action (hub_id, id) ON DELETE CASCADE
);

CREATE INDEX action_message_unconfirmed ON action_message (hub_id, action_id, seq) WHERE confirmed_at IS NULL;

-- The e-mails of notify runs (docs/pipeline.md §10, docs/integrations.md
-- §7): one row per recipient of the action (team:<slug> or an address, as
-- the run's params name them; the alert's team is written as its
-- team:<slug>, the shadow mailbox of a team in shadow mode as
-- shadow:<address>, docs/migration.md §2) and message of the run (start,
-- change, close), with the alert as the e-mail shows it, written in the
-- step that decided it. An immediate run's task sends its rows in order,
-- one e-mail each. A digest
-- run's rows carry digest_key (recipient and interval), the ref of the
-- timer of kind digest that sends every row of the key due by then as one
-- e-mail, grouped by team, service and severity. address is where it went:
-- a team recipient resolves to the team's mail address of the replica
-- (team.mail) when it is sent. The hygiene report counts the sent rows
-- (docs/pipeline.md §18).
CREATE TABLE notify_mail (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
action_id uuid NOT NULL,
recipient text NOT NULL,
digest_key text,
kind text NOT NULL CHECK (kind IN ('start', 'change', 'close')),
body jsonb NOT NULL,
idempotency_key text NOT NULL, -- the run's or follow-up's key and the recipient
created_at timestamptz NOT NULL, -- the decided_at of its decision or change
sent_at timestamptz,
address text,
last_error text,
PRIMARY KEY (hub_id, id),
UNIQUE (hub_id, idempotency_key),
FOREIGN KEY (hub_id, action_id) REFERENCES action (hub_id, id) ON DELETE CASCADE
);

CREATE INDEX notify_mail_unsent ON notify_mail (hub_id, action_id, created_at) WHERE sent_at IS NULL;
CREATE INDEX notify_mail_digest ON notify_mail (hub_id, digest_key, created_at) WHERE sent_at IS NULL AND digest_key IS NOT NULL;
CREATE INDEX notify_mail_sent ON notify_mail (hub_id, sent_at) WHERE sent_at IS NOT NULL;
CREATE INDEX notify_mail_action ON notify_mail (hub_id, action_id);

-- Manual pages from the hub (docs/pipeline.md §10), with or without an
-- alert. Each is a run of its own: its page request is an up message of
-- the link with idempotency key manual/<id> (docs/architecture.md §5),
-- and it goes through the local fallback channel like a page run
-- (fallback_send). pending: the page request waits for the cloud. sent:
-- the cloud confirmed it (incident_id). failed: the cloud refused it
-- (422); a self-alert names it. Kept as long as closed alerts
-- (docs/compliance.md §2).
CREATE TABLE manual_page (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
team text NOT NULL,
rotation text NOT NULL,
title text NOT NULL,
text text,
alert_id uuid, -- the alert the page is about, for its view; the alert is not changed
created_by uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
state text NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'sent', 'failed')),
incident_id uuid,
task_id uuid, -- absurd task of the page request
last_error text,
severity text NOT NULL DEFAULT 'major' CHECK (severity IN ('warning', 'minor', 'major', 'critical')), -- of the incident (docs/on-call.md §9)
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, alert_id) REFERENCES alert (hub_id, id) ON DELETE SET NULL (alert_id),
FOREIGN KEY (hub_id, created_by) REFERENCES app_user (hub_id, id)
);

CREATE INDEX manual_page_alert ON manual_page (hub_id, alert_id) WHERE alert_id IS NOT NULL;

-------------------------------------------------------------------------------
-- 7. Cloud link and replicas (docs/architecture.md §5)
-------------------------------------------------------------------------------

-- One row per enrolled hub: enrolment and link state (the cloud's tenant
-- and hub ids are on the hub's row, §0). key_sealed is the client key's
-- PEM sealed under a data key of the hub (docs/operations.md §6): a
-- format byte 1, the data_key id (4 bytes, big-endian), then the nonce and
-- ciphertext with the hub's id and "cloud_link.key_sealed" as associated
-- data.
CREATE TABLE cloud_link (
hub_id uuid PRIMARY KEY REFERENCES hub,
cert_pem text NOT NULL,
key_sealed bytea, -- client key, sealed (above); NULL after revoke or db restore until enrol
cert_expires_at timestamptz NOT NULL,
watch_key_sealed bytea NOT NULL, -- private Watch key under the data key; all nodes sign with it
-- The down stream (docs/architecture.md §5): the node holding the hub's
-- link lock (class 3), the epoch the cloud gave its stream (written when the
-- stream opens and checked by every commit of updates), and the stream
-- position committed so far.
node text,
stream_epoch bigint NOT NULL DEFAULT 0,
link_epoch uuid, -- the cloud's link epoch; NULL before the first replica load
last_seq bigint NOT NULL DEFAULT 0, -- last committed down-stream sequence
confirmed_seq bigint NOT NULL DEFAULT 0, -- last sent with the stream cursor
connected boolean NOT NULL DEFAULT false,
state_since timestamptz NOT NULL DEFAULT now(),
anchor_seq bigint NOT NULL DEFAULT 0, -- the last audit.anchor entry the cloud recorded (docs/compliance.md §3.2)
watch_key_data_key int, -- the data key that sealed watch_key_sealed; NULL while the hub has no Watch key (empty)
fallback_since timestamptz -- since when the local fallback channel is active (docs/architecture.md §7); NULL while it isn't
);

-- Incidents, deliveries, responses and shifts as received from the cloud,
-- for reporting and the alert view. Personal data is limited to the person's
-- display name and id; a person update from the cloud replaces the name in
-- every replica (pseudonymisation, docs/compliance.md §5).
CREATE TABLE incident_replica (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
team text NOT NULL,
rotation text NOT NULL,
kind text NOT NULL,
state text NOT NULL,
title text NOT NULL,
triggered_at timestamptz NOT NULL,
acked_at timestamptz,
acked_by text,
resolved_at timestamptz,
alert_count int NOT NULL,
seq bigint NOT NULL,
PRIMARY KEY (hub_id, id)
);

CREATE TABLE delivery_replica (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
incident_id uuid NOT NULL,
person_id uuid, -- NULL for synthetic test deliveries
person_name text,
medium text NOT NULL,
carrier text,
status text NOT NULL,
attempt int NOT NULL,
sent_at timestamptz, -- NULL while queued or throttled
final_at timestamptz,
by_fallback boolean NOT NULL DEFAULT false,
PRIMARY KEY (hub_id, id)
);

CREATE TABLE response_replica (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
incident_id uuid NOT NULL,
person_id uuid,
person_name text,
channel text NOT NULL,
type text NOT NULL,
at timestamptz NOT NULL,
PRIMARY KEY (hub_id, id)
);

-- Readiness per rotation as the cloud computes it (docs/on-call.md §1–§2),
-- for the cutover readiness (docs/migration.md §4). No personal data.
CREATE TABLE rotation_readiness (
hub_id uuid NOT NULL REFERENCES hub,
team text NOT NULL,
rotation text NOT NULL,
people int NOT NULL, -- people across the layers
unreachable int NOT NULL,
untested int NOT NULL, -- people without an acknowledged test page
gap_hours_14d numeric NOT NULL, -- hours without anyone on call in the next 14 days
meets_minimums boolean NOT NULL,
missing text[] NOT NULL DEFAULT '{}', -- the tenant minimums it misses
seq bigint NOT NULL,
PRIMARY KEY (hub_id, team, rotation)
);

CREATE TABLE shift_replica (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
team text NOT NULL,
rotation text NOT NULL,
person_id uuid, -- NULL for gaps
person_name text,
starts_at timestamptz NOT NULL,
ends_at timestamptz NOT NULL,
source text NOT NULL CHECK (source IN ('layer', 'override', 'absence-cover', 'gap', 'punch')),
PRIMARY KEY (hub_id, id)
);

-- SMS sent through the local fallback channel (docs/architecture.md §7),
-- one row per page run or manual page, person and attempt; reported to the
-- cloud as deliveries with by_fallback once the link is back
-- (report_key: the up message that carries it, unknown reported as
-- failed; reported_at: when the cloud recorded it or refused it for good
-- with 422 link.page_unknown). The hub binds as transmitter and
-- requests no delivery
-- receipts. smpp_ref is the submit_sm_resp message_id as received. sent:
-- the SMSC accepted the submit. failed: the SMSC refused it other than by
-- throttling. unknown: the connection dropped before the submit's
-- response. capped: not sent, the person had 5 SMS (sent or unknown,
-- summaries left out) within 15 minutes; a page that is capped for a
-- person isn't sent to them. Only failed and unknown sends are retried,
-- 5 minutes after the last attempt, as a new row; summary: the SMS that
-- counts a person's capped pages, sent 15 minutes after the first of them
-- that no summary counted yet (summary_id of the capped rows), again
-- every 5 minutes while it fails. page_key: the idempotency key of the
-- page request the send stands for (a page run's message, or
-- manual/<id>); NULL for the SMS of a self-alert about the link, which a
-- run of type fallback sends and the cloud never gets. status_at is when
-- the status was learned.
CREATE TABLE fallback_send (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
action_id uuid, -- the page run
team text NOT NULL,
rotation text NOT NULL,
person_id uuid NOT NULL,
number_label text NOT NULL,
smpp_ref text, -- NULL without the submit's response
status text NOT NULL CHECK (status IN ('sent', 'failed', 'unknown', 'capped')),
sent_at timestamptz NOT NULL,
status_at timestamptz NOT NULL,
reported_at timestamptz,
manual_page_id uuid,
summary boolean NOT NULL DEFAULT false, -- the summary SMS for pages over the cap; neither run then
page_key text,
summary_id uuid, -- capped: the summary that counted it
report_key text, -- the idempotency key of the report that carries it
CHECK (summary OR ((action_id IS NULL) <> (manual_page_id IS NULL))),
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, action_id) REFERENCES action (hub_id, id) ON DELETE CASCADE,
FOREIGN KEY (hub_id, manual_page_id) REFERENCES manual_page (hub_id, id) ON DELETE CASCADE,
FOREIGN KEY (hub_id, summary_id) REFERENCES fallback_send (hub_id, id) ON DELETE SET NULL (summary_id)
);

CREATE INDEX fallback_send_unreported ON fallback_send (hub_id, sent_at) WHERE reported_at IS NULL;
CREATE INDEX fallback_send_person ON fallback_send (hub_id, person_id, sent_at);
CREATE INDEX fallback_send_page ON fallback_send (hub_id, page_key) WHERE page_key IS NOT NULL;
CREATE INDEX fallback_send_action ON fallback_send (hub_id, action_id) WHERE action_id IS NOT NULL;
CREATE INDEX fallback_send_manual_page ON fallback_send (hub_id, manual_page_id) WHERE manual_page_id IS NOT NULL;
CREATE INDEX fallback_send_summary ON fallback_send (hub_id, summary_id) WHERE summary_id IS NOT NULL;

-- Local fallback channel cache (docs/architecture.md §7): current and next
-- person per rotation with one number each (docs/api/cloud.yaml
-- HubFallbackCache entries), sealed under a data key of the hub as
-- cloud_link.key_sealed is: a format byte 1, the data_key id (4 bytes,
-- big-endian), then the nonce and ciphertext of the entries' JSON with the
-- hub's id and "fallback_cache:<team>/<rotation>" as associated data. A person update
-- replaces the name in it; the deletion of the cache, its rotation or its
-- team deletes it, as it does the rotation's shifts and readiness.
CREATE TABLE fallback_cache (
hub_id uuid NOT NULL REFERENCES hub,
team text NOT NULL,
rotation text NOT NULL,
entries bytea NOT NULL, -- sealed JSON
valid_until timestamptz NOT NULL,
PRIMARY KEY (hub_id, team, rotation)
);

-------------------------------------------------------------------------------
-- 8. Operations, replay, bundles
-------------------------------------------------------------------------------

-- Long requests run as absurd tasks; this row is what the API polls.
-- Deleted 30 days after they finish; a change set's validation stays while
-- the change set is open (docs/compliance.md §2).
CREATE TYPE operation_state AS ENUM ('queued', 'running', 'succeeded', 'failed', 'cancelled');

CREATE TABLE operation (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
kind text NOT NULL CHECK (kind IN ('validate', 'replay', 'bulk-close', 'inventory-import', 'export', 'bundle-import', 'audit-verify', 'shadow-import')),
state operation_state NOT NULL DEFAULT 'queued',
params jsonb NOT NULL,
progress jsonb,
result jsonb, -- replay: mode (route-only, full), the range replayed (from, to, events), diff summary; bulk close: count
error text,
created_by uuid,
created_at timestamptz NOT NULL DEFAULT now(),
finished_at timestamptz,
task_id uuid, -- absurd task; running ends failed when it loses its claim (§3, inventory_import)
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, created_by) REFERENCES app_user (hub_id, id)
);

-- The file of an export operation (docs/api/hub.yaml createExport,
-- downloadOperationResult): NDJSON, one row of the export's reporting
-- view per line; deleted with its operation. The content is in
-- operation_file_part, parts of at most 1 MiB written in order, so that
-- neither writing nor serving the file holds it whole in a node's memory;
-- this row, written after the last part, marks the file complete.
CREATE TABLE operation_file (
hub_id uuid NOT NULL REFERENCES hub,
operation_id uuid NOT NULL,
content_type text NOT NULL,
parts int NOT NULL, -- parts 0 to parts - 1
bytes bigint NOT NULL,
PRIMARY KEY (hub_id, operation_id),
FOREIGN KEY (hub_id, operation_id) REFERENCES operation (hub_id, id) ON DELETE CASCADE
);

CREATE TABLE operation_file_part (
hub_id uuid NOT NULL REFERENCES hub,
operation_id uuid NOT NULL,
part int NOT NULL CHECK (part >= 0),
content bytea NOT NULL,
PRIMARY KEY (hub_id, operation_id, part),
FOREIGN KEY (hub_id, operation_id) REFERENCES operation (hub_id, id) ON DELETE CASCADE
);

-- At most one replay of a hub runs at a time, a preview's (replay) or a
-- submit's (validate); validations queue (docs/pipeline.md §12).
CREATE UNIQUE INDEX operation_one_replay ON operation (hub_id) WHERE kind IN ('replay', 'validate') AND state = 'running';

-- Per-alert-key differences of a replay; deleted with the operation.
CREATE TABLE replay_diff (
hub_id uuid NOT NULL REFERENCES hub,
operation_id uuid NOT NULL,
alert_key text NOT NULL, -- <namespace>/<key>
first_event timestamptz NOT NULL,
classes text[] NOT NULL, -- page-added, page-removed, rotation-changed, ticket-added, …
teams text[] NOT NULL, -- affected teams (old and new)
flags text[] NOT NULL DEFAULT '{}', -- order-sensitive, manual, truncated (docs/pipeline.md §12)
baseline jsonb NOT NULL,
candidate jsonb NOT NULL,
PRIMARY KEY (hub_id, operation_id, alert_key, first_event),
FOREIGN KEY (hub_id, operation_id) REFERENCES operation (hub_id, id) ON DELETE CASCADE
);

-- Shadow comparison cases (docs/migration.md §2): one per pair of an
-- alert Excubio decided and the incumbent's record, or one side alone. The
-- cutover check counts the incumbent-only and person-differs cases of a
-- team without an explanation. The incumbent's side comes from the
-- imports below; a new import of a range writes the range's cases anew
-- and keeps the explanation of a case whose alert, source event and class
-- are unchanged. id is a UUIDv7 of at, so the IDs order the cases by
-- time.
CREATE TABLE shadow_case (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
team text NOT NULL,
class text NOT NULL CHECK (class IN ('match', 'excubio-only', 'incumbent-only', 'team-differs', 'person-differs', 'grouped', 'release')),
at timestamptz NOT NULL,
source_event_id text,
fuzzy boolean NOT NULL DEFAULT false,
alert_id uuid,
excubio jsonb, -- team, action, rotation, person, count
incumbent jsonb,
explanation text,
explained_by uuid,
explained_at timestamptz,
node text,
check_name text,
CHECK ((explanation IS NULL) = (explained_at IS NULL)),
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, explained_by) REFERENCES app_user (hub_id, id)
);

CREATE INDEX shadow_case_team ON shadow_case (hub_id, team, class, at);

-- The ranges for which the incumbent's side was imported (importShadow,
-- docs/migration.md §2): the report and the cutover readiness count only
-- the time these cover. Kept as events (docs/compliance.md §2): a node's
-- housekeeping deletes the cases and records whose at, and the imports
-- whose to_at, lie before the event retention.
CREATE TABLE shadow_import (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
from_at timestamptz NOT NULL,
to_at timestamptz NOT NULL CHECK (to_at > from_at),
records int NOT NULL,
imported_by uuid,
imported_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, id),
FOREIGN KEY (hub_id, imported_by) REFERENCES app_user (hub_id, id)
);

CREATE INDEX shadow_import_range ON shadow_import (hub_id, from_at, to_at);

-- The incumbent's records of the imports, one per line of an import
-- (ShadowRecord, docs/api/hub.yaml): an import replaces the records of
-- earlier imports within its range, and the comparison of a range reads
-- them. person is the cloud's person ID as excubioctl resolved it.
CREATE TABLE shadow_record (
hub_id uuid NOT NULL REFERENCES hub,
import_id uuid NOT NULL,
line int NOT NULL,
at timestamptz NOT NULL,
source_event_id text,
node text,
check_name text,
team text NOT NULL,
action text NOT NULL CHECK (action IN ('page', 'e-mail', 'ticket', 'none')),
count int NOT NULL DEFAULT 0 CHECK (count >= 0),
person uuid,
PRIMARY KEY (hub_id, import_id, line),
FOREIGN KEY (hub_id, import_id) REFERENCES shadow_import (hub_id, id) ON DELETE CASCADE
);

CREATE INDEX shadow_record_at ON shadow_record (hub_id, at);

-- Signed trap packs (docs/operations.md §5).
CREATE TABLE bundle (
hub_id uuid NOT NULL REFERENCES hub,
name text NOT NULL,
version text NOT NULL,
key_id text NOT NULL,
manifest jsonb NOT NULL,
mibs bytea NOT NULL,
rules text NOT NULL,
imported_by uuid,
imported_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, name, version),
FOREIGN KEY (hub_id, imported_by) REFERENCES app_user (hub_id, id)
);

-------------------------------------------------------------------------------
-- 9. Reporting views (docs/integrations.md §12)
-------------------------------------------------------------------------------

-- The views run with the privileges and the row-level security of who
-- reads them (security_invoker): a node under its hub's scope, a reporting
-- login under its reporting_login row (§11). They don't show hub_id; the
-- joins match it.

CREATE SCHEMA IF NOT EXISTS reporting_v1;

CREATE VIEW reporting_v1.events WITH (security_invoker) AS
SELECT id, received_at, occurred_at, source, channel, namespace, key, role,
severity::text AS severity, node, check_name, outcome, alert_id
FROM excubio.event;

CREATE VIEW reporting_v1.alerts WITH (security_invoker) AS
SELECT id, namespace, key, kind, source, channel, state::text AS state, severity::text AS severity, title,
node, check_name, ci, team, service, oncall, notify, suppression, dropped,
first_seen, last_seen, count, reopens, acked_at, acked_by, closed_at, close_reason,
-- the incident of the alert's latest page run with one
(SELECT r.target_ref::uuid FROM excubio.action r
WHERE r.hub_id = a.hub_id AND r.alert_id = a.id AND r.type = 'page' AND r.target_ref IS NOT NULL
ORDER BY r.id DESC LIMIT 1) AS incident_id,
ticket_ref, source_id, group_alert, group_role
FROM excubio.alert a;

CREATE VIEW reporting_v1.alert_groups WITH (security_invoker) AS
SELECT g.alert_id AS id, g.pattern, g.state, g.first_at, g.cause_alert, g.involved,
g.merged_into, a.team, a.severity::text AS severity, a.closed_at,
(SELECT count(*) FROM excubio.alert_group_member m WHERE m.hub_id = g.hub_id AND m.group_alert = g.alert_id) AS members
FROM excubio.alert_group g JOIN excubio.alert a ON a.hub_id = g.hub_id AND a.id = g.alert_id;

CREATE VIEW reporting_v1.alert_transitions WITH (security_invoker) AS
SELECT id, alert_id, at, from_state::text AS from_state, to_state::text AS to_state,
severity::text AS severity, suppression, cause, detail
FROM excubio.alert_transition;

CREATE VIEW reporting_v1.routing_decisions WITH (security_invoker) AS
SELECT id, alert_id, triggers, revision, level, snapshot, group_alert, team, service, oncall,
notify, actions, decided_at
FROM excubio.routing_decision;

CREATE VIEW reporting_v1.incidents WITH (security_invoker) AS
SELECT id, team, rotation, kind, state, title, triggered_at, acked_at, acked_by,
resolved_at, alert_count,
extract(epoch FROM acked_at - triggered_at) AS ack_seconds
FROM excubio.incident_replica;

CREATE VIEW reporting_v1.deliveries WITH (security_invoker) AS
SELECT id, incident_id, person_name, medium, carrier, status, attempt, sent_at, final_at, by_fallback
FROM excubio.delivery_replica;

CREATE VIEW reporting_v1.responses WITH (security_invoker) AS
SELECT id, incident_id, person_name, channel, type, at
FROM excubio.response_replica;

CREATE VIEW reporting_v1.shifts WITH (security_invoker) AS
SELECT id, team, rotation, person_name, starts_at, ends_at, source
FROM excubio.shift_replica;

CREATE VIEW reporting_v1.heartbeats WITH (security_invoker) AS
SELECT name, instance, state, last_beat_at, since
FROM excubio.heartbeat_state;

-- Pre-aggregated daily counts per UTC day, kept for 10 years; written by
-- the retention job before it drops or deletes anything, once per day, an
-- hour after the day ended (docs/compliance.md §2): events received that
-- day by Source and their alert's team (empty without one), alerts first
-- seen that day, and page and ticket runs started by that day's
-- decisions, by the alert's Source (its namespace for the hub's own
-- kinds) and team.
CREATE TABLE daily_stats (
hub_id uuid NOT NULL REFERENCES hub,
day date NOT NULL,
source text NOT NULL,
team text NOT NULL DEFAULT '',
events bigint NOT NULL,
alerts bigint NOT NULL,
pages bigint NOT NULL,
tickets bigint NOT NULL,
PRIMARY KEY (hub_id, day, source, team)
);

CREATE VIEW reporting_v1.daily_stats WITH (security_invoker) AS
SELECT day, source, team, events, alerts, pages, tickets FROM excubio.daily_stats;

-------------------------------------------------------------------------------
-- 10. Secrets and audit (docs/architecture.md §11, docs/compliance.md §3)
-------------------------------------------------------------------------------

-- Each hub's data keys, wrapped by the installation's deployment key with
-- the hub's id and the key's id as associated data (docs/operations.md
-- §6). Everything a data key seals has the hub's id in its associated
-- data, so a sealed value moved to another hub doesn't open.
CREATE TABLE data_key (
hub_id uuid NOT NULL REFERENCES hub,
id int NOT NULL,
wrapped bytea NOT NULL,
deployment_key text NOT NULL, -- fingerprint of the wrapping key
created_at timestamptz NOT NULL DEFAULT now(),
retired_at timestamptz,
PRIMARY KEY (hub_id, id)
);

CREATE TRIGGER data_key_registry AFTER INSERT OR UPDATE ON data_key FOR EACH ROW EXECUTE FUNCTION data_keys_changed();

-- Secret values by Secret name; write-only through the API. A new value is
-- a new version; actions use the latest.
CREATE TABLE secret_version (
hub_id uuid NOT NULL REFERENCES hub,
name text NOT NULL,
version int NOT NULL,
data_key int NOT NULL,
sealed bytea NOT NULL, -- AES-256-GCM, the hub, name and version as associated data
created_by uuid,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, name, version),
FOREIGN KEY (hub_id, data_key) REFERENCES data_key (hub_id, id),
FOREIGN KEY (hub_id, created_by) REFERENCES app_user (hub_id, id)
);

-- Hash-chained audit log of each hub (docs/compliance.md §3). seq is
-- gap-free within the hub; hash =
-- SHA-256(prev_hash || canonical entry); the first entry after a
-- checkpoint has the checkpoint's hash as prev_hash, the very first 32
-- zero bytes. The nodes may only read and append (§11). A writer takes
-- the hub's advisory transaction lock of class 5 (docs/architecture.md §4)
-- before it reads the head, so entries are appended in the order their
-- transactions commit; expiry is audit_expire. The canonical form:
-- docs/compliance.md §3.2. actor is an id, never a name: the
-- app_user id (user, service: the API token's id is in details), the
-- cloud's person id (cloud), the component (system), the operating system
-- account that ran a server subcommand (local). Names are resolved on
-- display. The hourly anchors are entries of action audit.anchor.
CREATE TABLE audit_event (
hub_id uuid NOT NULL REFERENCES hub,
seq bigint NOT NULL,
at timestamptz NOT NULL DEFAULT now(),
actor_kind text NOT NULL CHECK (actor_kind IN ('user', 'service', 'system', 'cloud', 'local')),
actor text NOT NULL,
action text NOT NULL, -- e.g. change_set.merge, alert.bulk_close
object text NOT NULL,
reason text,
request_id text,
details jsonb NOT NULL DEFAULT '{}',
prev_hash bytea NOT NULL,
hash bytea NOT NULL,
PRIMARY KEY (hub_id, seq)
);

-- A hub's anchors (docs/compliance.md §3.2), which anchor_hubs (§13) and
-- the anchoring read.
CREATE INDEX audit_event_anchor ON audit_event (hub_id, seq) WHERE action = 'audit.anchor';
-- The entries by time: listAudit's since and until.
CREATE INDEX audit_event_at ON audit_event (hub_id, at);

-- The installation's own audit log, chained as audit_event is, of what
-- concerns no single hub: the creation of a hub, its names and sign-in
-- (hub.front_door, hub.auth), the operator hub (installation.operator_hub),
-- and authentication failures at a host of no
-- hub (auth.failed, at most one a minute, docs/compliance.md §3).
CREATE TABLE installation_audit (
seq bigint PRIMARY KEY,
at timestamptz NOT NULL DEFAULT now(),
actor_kind text NOT NULL CHECK (actor_kind IN ('user', 'service', 'system', 'cloud', 'local')),
actor text NOT NULL,
action text NOT NULL, -- e.g. hub.create
object text NOT NULL,
reason text,
request_id text,
details jsonb NOT NULL DEFAULT '{}',
prev_hash bytea NOT NULL,
hash bytea NOT NULL
);

-- The audit retention of the installation's hubs: one row, written only
-- by the owner, from [audit] retention of the node configuration
-- (docs/operations.md §2).
CREATE TABLE audit_policy (
id boolean PRIMARY KEY DEFAULT true CHECK (id),
keep interval NOT NULL DEFAULT interval '5 years' CHECK (keep >= interval '1 year'),
set_at timestamptz NOT NULL DEFAULT now()
);

INSERT INTO audit_policy DEFAULT VALUES;

-- One row per expiry, written by audit_expire: the last expired entry
-- (seq, hash), so a chain that starts anywhere else fails verification.
CREATE TABLE audit_checkpoint (
hub_id uuid NOT NULL REFERENCES hub,
seq bigint NOT NULL,
hash bytea NOT NULL,
expired bigint NOT NULL, -- entries deleted
keep interval NOT NULL, -- the retention applied
at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, seq)
);

-- Audit sinks with their delivery cursor (outbox over audit_event.seq).
CREATE TABLE audit_sink (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
kind text NOT NULL CHECK (kind IN ('syslog', 'https')),
target text NOT NULL,
credentials text, -- Secret name
cursor_seq bigint NOT NULL DEFAULT 0,
last_error text,
enabled boolean NOT NULL DEFAULT true,
PRIMARY KEY (hub_id, id)
);

-------------------------------------------------------------------------------
-- 11. Roles
-------------------------------------------------------------------------------

-- Roles, all without login; the deployment makes logins their members
-- (docs/operations.md §1):
-- * excubio_hub_owner owns the schemas excubio, reporting_v1 and absurd
-- and everything in them but the lookup functions, and runs the
-- migrations (excubio-hub db migrate, or serve at start with the
-- owner's login). It serves nothing.
-- * excubio_hub_app is the nodes (excubio-hub serve): SELECT, INSERT,
-- UPDATE and DELETE on every table of excubio, except audit_event,
-- which it may only read and append to, audit_policy, audit_checkpoint
-- and installation_audit, which it may only read (it appends to the
-- last), and reporting_login and the partitions of the partitioned
-- tables, on which it has nothing (it reaches them through their
-- parent); the sequences; the functions below and the lookup
-- functions (§13). No DDL and no TRUNCATE: partitions and the audit
-- log's expiry go through the functions below, which run as
-- excubio_hub_owner. A node refuses to serve as a login that is a
-- superuser, has BYPASSRLS or is a member of excubio_hub_owner or
-- excubio_hub_lookup. The migrations also grant it SELECT on
-- public._sqlx_migrations (sqlx's record of them, outside this
-- schema), which a node's readiness compares with its own.
-- * excubio_hub_lookup owns the lookup functions (§13) and may read,
-- across hubs, only the columns they need. No login is a member of it.
-- * excubio_reporting reads the views of reporting_v1, the columns of
-- the tables they show and nothing else, and only the rows of the hub
-- its login's reporting_login row names (§13, docs/integrations.md §12).
-- No role has BYPASSRLS, and FORCE applies the policies to the owner too.
-- Schema absurd (vendored, not part of this reference) gets the same from
-- the migrations: excubio_hub_app has USAGE on it, the DML on its tables,
-- including those of queues created later, and executes its functions.
-- The migrations create absurd's queue "actions" as excubio_hub_owner, so
-- a node creates no tables.

GRANT USAGE ON SCHEMA excubio TO excubio_hub_app, excubio_hub_lookup, excubio_reporting;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA excubio TO excubio_hub_app;
REVOKE UPDATE, DELETE ON audit_event, installation_audit FROM excubio_hub_app;
REVOKE INSERT, UPDATE, DELETE ON audit_policy, audit_checkpoint FROM excubio_hub_app;
REVOKE ALL ON reporting_login FROM excubio_hub_app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA excubio TO excubio_hub_app;
ALTER DEFAULT PRIVILEGES FOR ROLE excubio_hub_owner IN SCHEMA excubio
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO excubio_hub_app;
ALTER DEFAULT PRIVILEGES FOR ROLE excubio_hub_owner IN SCHEMA excubio
GRANT USAGE, SELECT ON SEQUENCES TO excubio_hub_app;

GRANT USAGE ON SCHEMA reporting_v1 TO excubio_reporting;
GRANT SELECT ON ALL TABLES IN SCHEMA reporting_v1 TO excubio_reporting;
ALTER DEFAULT PRIVILEGES FOR ROLE excubio_hub_owner IN SCHEMA reporting_v1
GRANT SELECT ON TABLES TO excubio_reporting;
-- The hub's exports read the views too (docs/api/hub.yaml createExport).
GRANT USAGE ON SCHEMA reporting_v1 TO excubio_hub_app;
GRANT SELECT ON ALL TABLES IN SCHEMA reporting_v1 TO excubio_hub_app;
ALTER DEFAULT PRIVILEGES FOR ROLE excubio_hub_owner IN SCHEMA reporting_v1
GRANT SELECT ON TABLES TO excubio_hub_app;

-- The partition width of a partitioned table: a month for event and
-- event_payload (§5), a day for the inventory history (§3); NULL for any
-- other table.
CREATE FUNCTION partition_width(parent text) RETURNS interval
LANGUAGE sql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$
SELECT CASE
WHEN parent IN ('event', 'event_payload') THEN interval '1 month'
WHEN parent IN ('inv_ci_history', 'inv_alias_history', 'inv_service_history',
'inv_service_alias_history', 'inv_ci_service_history',
'inv_maintenance_history') THEN interval '1 day'
END
$$;

-- Creates the partition of parent that holds at, when missing:
-- <parent>_<yyyymmdd> of its first day, in UTC. The months of event and
-- event_payload are partitioned by retention tier (§5): for them, tier
-- names the tier whose partition <parent>_<yyyymmdd>_<tier> it creates
-- too; for the inventory history it is NULL. Nobody but the owner has
-- privileges on a partition: rows are reached through their parent and
-- its policies (§13).
CREATE FUNCTION partition_create(parent text, at timestamptz, tier text) RETURNS void
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp SET timezone = 'UTC' AS $$
DECLARE
width interval := excubio.partition_width(parent);
tiered boolean := parent IN ('event', 'event_payload');
lo timestamptz;
month text;
BEGIN
IF width IS NULL THEN
RAISE EXCEPTION 'excubio.% has no partitions by time', parent;
END IF;
IF tiered <> (tier IS NOT NULL) OR tier !~ '^[a-z][a-z0-9]{0,15}$' THEN
RAISE EXCEPTION 'excubio.% takes %', parent, CASE WHEN tiered THEN 'a retention tier' ELSE 'no retention tier' END;
END IF;
lo := date_trunc(CASE WHEN width = interval '1 month' THEN 'month' ELSE 'day' END, at);
month := parent || '_' || to_char(lo, 'YYYYMMDD');
EXECUTE format('CREATE TABLE IF NOT EXISTS excubio.%I PARTITION OF excubio.%I FOR VALUES FROM (%L) TO (%L)%s',
month, parent, lo, lo + width, CASE WHEN tiered THEN ' PARTITION BY LIST (retention_tier)' ELSE '' END);
EXECUTE format('REVOKE ALL ON excubio.%I FROM excubio_hub_app, excubio_reporting', month);
IF tiered THEN
EXECUTE format('CREATE TABLE IF NOT EXISTS excubio.%I PARTITION OF excubio.%I FOR VALUES IN (%L)', month || '_' || tier, month, tier);
EXECUTE format('REVOKE ALL ON excubio.%I FROM excubio_hub_app, excubio_reporting', month || '_' || tier);
END IF;
END
$$;

-- Drops the partitions of parent that end at or before horizon; returns
-- their number. For event and event_payload, those of the retention tier
-- tier, and a month once none of its tiers is left. The default partition
-- stays.
CREATE FUNCTION partition_drop(parent text, horizon timestamptz, tier text) RETURNS int
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp SET timezone = 'UTC' AS $$
DECLARE
width interval := excubio.partition_width(parent);
tiered boolean := parent IN ('event', 'event_payload');
p text;
n int := 0;
BEGIN
IF width IS NULL THEN
RAISE EXCEPTION 'excubio.% has no partitions by time', parent;
END IF;
IF tiered <> (tier IS NOT NULL) THEN
RAISE EXCEPTION 'excubio.% takes %', parent, CASE WHEN tiered THEN 'a retention tier' ELSE 'no retention tier' END;
END IF;
FOR p IN
SELECT c.relname FROM pg_inherits i JOIN pg_class c ON c.oid = i.inhrelid
WHERE i.inhparent = format('excubio.%I', parent)::regclass AND c.relname ~ ('^' || parent || '_[0-9]{8}$')
LOOP
IF to_date(right(p, 8), 'YYYYMMDD')::timestamptz + width <= horizon THEN
IF tiered THEN
IF to_regclass(format('excubio.%I', p || '_' || tier)) IS NOT NULL THEN
EXECUTE format('DROP TABLE excubio.%I', p || '_' || tier);
n := n + 1;
END IF;
IF NOT EXISTS (SELECT FROM pg_inherits i WHERE i.inhparent = format('excubio.%I', p)::regclass) THEN
EXECUTE format('DROP TABLE excubio.%I', p);
END IF;
ELSE
EXECUTE format('DROP TABLE excubio.%I', p);
n := n + 1;
END IF;
END IF;
END LOOP;
RETURN n;
END
$$;

-- Deletes the oldest audit entries of the current hub (excubio.hub_id),
-- those older than audit_policy.keep (at least a year), as a prefix of
-- its chain that leaves the newest entry, and records the last deleted
-- one in audit_checkpoint; returns their number. Runs as
-- excubio_hub_owner, under the hub's policy. The caller can't choose the
-- retention.
CREATE FUNCTION audit_expire() RETURNS bigint
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE
hub uuid := NULLIF(current_setting('excubio.hub_id', true), '')::uuid;
keep interval;
head bigint;
last_seq bigint;
last_hash bytea;
n bigint;
BEGIN
IF hub IS NULL THEN
RAISE EXCEPTION 'audit_expire runs under a hub (excubio.hub_id)';
END IF;
SELECT p.keep INTO STRICT keep FROM excubio.audit_policy p;
IF keep < interval '1 year' THEN
RAISE EXCEPTION 'audit entries are kept at least a year, not %', keep;
END IF;
SELECT max(e.seq) INTO head FROM excubio.audit_event e WHERE e.hub_id = hub;
SELECT coalesce(min(e.seq), head) - 1 INTO last_seq FROM excubio.audit_event e WHERE e.hub_id = hub AND e.at >= now() - keep;
SELECT e.hash INTO last_hash FROM excubio.audit_event e WHERE e.hub_id = hub AND e.seq = last_seq;
IF last_hash IS NULL THEN
RETURN 0;
END IF;
DELETE FROM excubio.audit_event e WHERE e.hub_id = hub AND e.seq <= last_seq;
GET DIAGNOSTICS n = ROW_COUNT;
INSERT INTO excubio.audit_checkpoint (hub_id, seq, hash, expired, keep) VALUES (hub, last_seq, last_hash, n, keep);
RETURN n;
END
$$;

REVOKE EXECUTE ON FUNCTION partition_create(text, timestamptz, text), partition_drop(text, timestamptz, text), audit_expire() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION partition_create(text, timestamptz, text), partition_drop(text, timestamptz, text), audit_expire() TO excubio_hub_app;

-- Deletes at most budget rows of a hub in state deleting from the tables
-- that hold hub rows (those with a hub_id, §13), and returns their number
-- (docs/compliance.md §5). A call that finds none left deletes the hub's
-- reporting logins, its row (hub_usage goes with it) and its place as the
-- operator hub, and returns 0; the caller calls it, each call its own
-- transaction, until then. The tables are taken in name order; one whose
-- rows other rows still reference is passed over until those are gone, so
-- no list of tables needs keeping. Events and payloads, whose partitions
-- the hubs share, are deleted by row. Runs as excubio_hub_owner under the
-- hub's policy: the app role can delete neither the audit log nor its
-- checkpoints.
CREATE FUNCTION hub_delete(target uuid, budget int) RETURNS bigint
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE
t text;
n bigint;
total bigint := 0;
blocked int := 0;
BEGIN
IF NOT EXISTS (SELECT FROM excubio.hub h WHERE h.id = target AND h.state = 'deleting') THEN
RAISE EXCEPTION 'hub_delete needs a hub in state deleting';
END IF;
IF budget < 1 THEN
RAISE EXCEPTION 'hub_delete deletes at least one row a call';
END IF;
PERFORM set_config('excubio.hub_id', target::text, true);
FOR t IN
SELECT c.relname FROM pg_class c JOIN pg_attribute a ON a.attrelid = c.oid AND a.attname = 'hub_id' AND NOT a.attisdropped
WHERE c.relnamespace = 'excubio'::regnamespace AND c.relkind IN ('r', 'p') AND NOT c.relispartition AND c.relname <> 'reporting_login'
ORDER BY c.relname
LOOP
EXIT WHEN total >= budget;
BEGIN
EXECUTE format('DELETE FROM excubio.%I x WHERE x.hub_id = $1 AND (x.tableoid, x.ctid) IN '
'(SELECT y.tableoid, y.ctid FROM excubio.%I y WHERE y.hub_id = $1 LIMIT $2)', t, t) USING target, budget - total;
GET DIAGNOSTICS n = ROW_COUNT;
total := total + n;
EXCEPTION WHEN foreign_key_violation THEN
blocked := blocked + 1;
END;
END LOOP;
IF total = 0 THEN
IF blocked > 0 THEN
RAISE EXCEPTION 'hub_delete: the rows of % tables are referenced by rows it doesn''t delete', blocked;
END IF;
DELETE FROM excubio.reporting_login r WHERE r.hub_id = target;
UPDATE excubio.installation SET operator_hub = NULL WHERE operator_hub = target;
DELETE FROM excubio.hub h WHERE h.id = target;
END IF;
RETURN total;
END
$$;

REVOKE EXECUTE ON FUNCTION hub_delete(uuid, int) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION hub_delete(uuid, int) TO excubio_hub_app;

-------------------------------------------------------------------------------
-- 12. Relays (docs/architecture.md §13, docs/operations.md §12)
-------------------------------------------------------------------------------

-- Each hub's relay CA, one row per hub, created with its first relay
-- enrolment token: an ECDSA P-256 key valid 10 years that signs the
-- relays' client certificates and the nodes' relay listener certificates.
-- key_sealed is the key's PEM sealed under a data key as
-- cloud_link.key_sealed is, with the hub's id and "relay_ca.key_sealed" as
-- associated data.
CREATE TABLE relay_ca (
hub_id uuid PRIMARY KEY REFERENCES hub,
cert_pem text NOT NULL,
key_sealed bytea NOT NULL,
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);

-- One-time relay enrolment tokens (exr_…), valid 24 h, stored as SHA-256
-- hashes. created_by NULL: issued by excubio-hub relay enrol-token on a
-- node (docs/cli.md §6). Enrolment sets used_at and creates the relay of
-- the token's name in one transaction.
CREATE TABLE relay_enrol_token (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
name text NOT NULL, -- the relay's name
token_hash bytea NOT NULL,
created_by uuid,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL,
used_at timestamptz,
revoked_at timestamptz,
PRIMARY KEY (hub_id, id),
UNIQUE (hub_id, token_hash),
FOREIGN KEY (hub_id, created_by) REFERENCES app_user (hub_id, id)
);

-- Enrolled relays. cert_sha256 is the SHA-256 of the current
-- certificate's DER; prev_cert_sha256 that of the one before a renewal,
-- taken until the relay first connects with the current one, then set
-- NULL. hello and heartbeat are the relay's last frames of that type
-- (version, spool id, allowlist and listeners; the spool's state), written
-- by the node that received them; refused is the code of the last bye a
-- node answered it with, NULL once a connection is taken again.
CREATE TABLE relay (
hub_id uuid NOT NULL REFERENCES hub,
id uuid NOT NULL,
name text NOT NULL,
cert_pem text NOT NULL,
cert_sha256 bytea NOT NULL,
prev_cert_sha256 bytea,
cert_expires_at timestamptz NOT NULL,
enrolled_at timestamptz NOT NULL DEFAULT now(),
hello jsonb,
heartbeat jsonb,
refused text CHECK (refused IN ('relay.update_required', 'relay.unknown')),
last_contact_at timestamptz,
revoked_at timestamptz,
PRIMARY KEY (hub_id, id),
UNIQUE (hub_id, name)
);

-- A node's control connection of a relay, while it holds it: the node
-- inserts the row when it takes the connection, sets seen_at every 30 s
-- and deletes the row when the connection ends. A row whose seen_at is
-- older than 90 s is of a node that died with it, and is not counted.
CREATE TABLE relay_session (
hub_id uuid NOT NULL REFERENCES hub,
relay_id uuid NOT NULL,
node text NOT NULL,
connected_at timestamptz NOT NULL DEFAULT now(),
seen_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, relay_id, node),
FOREIGN KEY (hub_id, relay_id) REFERENCES relay (hub_id, id) ON DELETE CASCADE
);

-- The high-water mark of a relay's spool (docs/architecture.md §13
-- Datagrams): the highest position whose datagram is stored. A
-- transaction that stores datagrams of the spool first locks its row
-- (inserted with mark 0 when missing, then SELECT … FOR UPDATE), drops the
-- positions at or below mark, stores the others as events and sets mark
-- to the highest, and commits before the node acknowledges it.
CREATE TABLE relay_spool (
hub_id uuid NOT NULL REFERENCES hub,
relay_id uuid NOT NULL,
spool_id uuid NOT NULL,
mark bigint NOT NULL DEFAULT 0 CHECK (mark >= 0),
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (hub_id, relay_id, spool_id),
FOREIGN KEY (hub_id, relay_id) REFERENCES relay (hub_id, id) ON DELETE CASCADE
);

-------------------------------------------------------------------------------
-- 13. Hub scope: row-level security and lookup functions
-------------------------------------------------------------------------------

-- The hub: every transaction on hub data first sets the setting
-- excubio.hub_id for the transaction only: SET LOCAL excubio.hub_id =
-- '<uuid>', or set_config('excubio.hub_id', '<uuid>', true). A step that
-- works on several hubs sets it again before each hub's work. The policy
-- hub_isolation shows and accepts only rows of that hub to the nodes and
-- the owner; without it (unset or empty) a query sees no hub rows and can
-- write none. It binds the setting, so it is not the policy of the
-- reporting logins, who may set any setting: theirs, reporting, binds the
-- login (session_user) through reporting_login.
--
-- The partitions of a partitioned table have no policies of their own;
-- nobody but the owner has privileges on them (partition_create, and the
-- block below for the default partitions), so a query that names a
-- partition is refused instead of reading past its parent's policies.
--
-- Work whose hub isn't known yet (a request by its host name, a mail by
-- its domain), the steps' search for work across the hubs of a partition
-- or a correlator shard and the node's loops over the hubs find their
-- hubs through the SECURITY DEFINER functions below, owned by
-- excubio_hub_lookup. They return hub ids, times and counts, nothing
-- else; the work then runs in its own transaction or under SET of its
-- hub. Each function pins its search_path and names its tables with the
-- schema.

DO $$
DECLARE t text;
BEGIN
FOR t IN
SELECT c.relname FROM pg_class c JOIN pg_attribute a ON a.attrelid = c.oid AND a.attname = 'hub_id' AND NOT a.attisdropped
WHERE c.relnamespace = 'excubio'::regnamespace AND c.relkind IN ('r', 'p') AND NOT c.relispartition AND c.relname <> 'reporting_login'
ORDER BY c.relname
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', t);
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY', t);
EXECUTE format(
'CREATE POLICY hub_isolation ON %I TO excubio_hub_app, excubio_hub_owner '
'USING (hub_id = NULLIF(current_setting(''excubio.hub_id'', true), '''')::uuid)', t);
END LOOP;
-- What the reporting views read, for the hub of the reading login.
FOREACH t IN ARRAY ARRAY['event', 'alert', 'action', 'alert_group', 'alert_group_member', 'alert_transition',
'routing_decision', 'incident_replica', 'delivery_replica', 'response_replica', 'shift_replica',
'heartbeat_state', 'daily_stats']
LOOP
EXECUTE format(
'CREATE POLICY reporting ON %I FOR SELECT TO excubio_reporting '
'USING (hub_id = (SELECT r.hub_id FROM excubio.reporting_login r WHERE r.login = session_user))', t);
END LOOP;
-- What the lookup functions read across hubs.
FOREACH t IN ARRAY ARRAY['activation_log', 'event', 'command', 'timer', 'correlator_inbox', 'correlator_progress',
'audit_event', 'audit_sink', 'cloud_link', 'inventory_snapshot', 'relay', 'active_revision'] LOOP
EXECUTE format('CREATE POLICY lookup ON %I FOR SELECT TO excubio_hub_lookup USING (true)', t);
END LOOP;
-- The default partitions, created before the grants of §11.
FOR t IN
SELECT c.relname FROM pg_class c
WHERE c.relnamespace = 'excubio'::regnamespace AND c.relkind IN ('r', 'p') AND c.relispartition ORDER BY c.relname
LOOP
EXECUTE format('REVOKE ALL ON %I FROM excubio_hub_app', t);
END LOOP;
END $$;

-- A reporting login reads its own row and nothing else; the installation's
-- administrator writes the rows (the owner, to whom the policies don't
-- apply here: no FORCE).
ALTER TABLE reporting_login ENABLE ROW LEVEL SECURITY;
CREATE POLICY own_login ON reporting_login FOR SELECT TO excubio_reporting USING (login = session_user);
GRANT SELECT (login, hub_id) ON reporting_login TO excubio_reporting;

-- The columns the reporting views show, with hub_id, which the views'
-- joins and the policies compare.
GRANT SELECT (hub_id, id, received_at, occurred_at, source, channel, namespace, key, role, severity, node, check_name,
outcome, alert_id) ON event TO excubio_reporting;
GRANT SELECT (hub_id, id, namespace, key, kind, source, channel, state, severity, title, node, check_name, ci, team,
service, oncall, notify, suppression, dropped, first_seen, last_seen, count, reopens, acked_at, acked_by, closed_at,
close_reason, ticket_ref, source_id, group_alert, group_role) ON alert TO excubio_reporting;
GRANT SELECT (hub_id, id, alert_id, type, target_ref) ON action TO excubio_reporting;
GRANT SELECT (hub_id, alert_id, pattern, state, first_at, cause_alert, involved, merged_into) ON alert_group TO excubio_reporting;
GRANT SELECT (hub_id, group_alert) ON alert_group_member TO excubio_reporting;
GRANT SELECT (hub_id, id, alert_id, at, from_state, to_state, severity, suppression, cause, detail) ON alert_transition TO excubio_reporting;
GRANT SELECT (hub_id, id, alert_id, triggers, revision, level, snapshot, group_alert, team, service, oncall, notify,
actions, decided_at) ON routing_decision TO excubio_reporting;
GRANT SELECT (hub_id, id, team, rotation, kind, state, title, triggered_at, acked_at, acked_by, resolved_at,
alert_count) ON incident_replica TO excubio_reporting;
GRANT SELECT (hub_id, id, incident_id, person_name, medium, carrier, status, attempt, sent_at, final_at, by_fallback)
ON delivery_replica TO excubio_reporting;
GRANT SELECT (hub_id, id, incident_id, person_name, channel, type, at) ON response_replica TO excubio_reporting;
GRANT SELECT (hub_id, id, team, rotation, person_name, starts_at, ends_at, source) ON shift_replica TO excubio_reporting;
GRANT SELECT (hub_id, name, instance, state, last_beat_at, since) ON heartbeat_state TO excubio_reporting;
GRANT SELECT (hub_id, day, source, team, events, alerts, pages, tickets) ON daily_stats TO excubio_reporting;

-- What the lookup functions read.
GRANT SELECT (id, host, mail_domain, lanes, lane_base, correlator_shard, link_shard, state, cloud_hub_id) ON hub TO excubio_hub_lookup;
GRANT SELECT (partitions) ON installation TO excubio_hub_lookup;
GRANT SELECT (partition, last_received_at, processed_to) ON partition_owner TO excubio_hub_lookup;
GRANT SELECT (shard, last_received_at) ON correlator_owner TO excubio_hub_lookup;
GRANT SELECT (hub_id, kind, activated_at) ON activation_log TO excubio_hub_lookup;
GRANT SELECT (hub_id, seq, at, action) ON audit_event TO excubio_hub_lookup;
GRANT SELECT (hub_id, enabled) ON audit_sink TO excubio_hub_lookup;
GRANT SELECT (hub_id, anchor_seq, connected, state_since, cert_expires_at, watch_key_data_key) ON cloud_link TO excubio_hub_lookup;
GRANT SELECT (hub_id, revision) ON active_revision TO excubio_hub_lookup;
GRANT SELECT (hub_id, partition, seq) ON event TO excubio_hub_lookup;
GRANT SELECT (hub_id, partition, seq, received_at, applied_at) ON command TO excubio_hub_lookup;
GRANT SELECT (hub_id, partition, due_at) ON timer TO excubio_hub_lookup;
GRANT SELECT (hub_id, received_at, processed_at) ON correlator_inbox TO excubio_hub_lookup;
GRANT SELECT (hub_id, processed_to) ON correlator_progress TO excubio_hub_lookup;
GRANT SELECT (hub_id, number, state, counts) ON inventory_snapshot TO excubio_hub_lookup;
GRANT SELECT (hub_id, revoked_at) ON relay TO excubio_hub_lookup;

-- The hub that answers on a host name (the front door): hub.host is
-- unique and lower-case, so a name names one hub; NULL for none.
CREATE FUNCTION lookup_hub_by_host(host_name text) RETURNS uuid
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT h.id FROM excubio.hub h WHERE h.host = lower(host_name)
$$;

-- The hub of an e-mail intake address's domain; NULL for none.
CREATE FUNCTION lookup_hub_by_mail_domain(domain_name text) RETURNS uuid
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT h.id FROM excubio.hub h WHERE h.mail_domain = lower(domain_name)
$$;

-- The hubs whose link to the cloud is up, for the installation's metrics
-- (docs/integrations.md §11): cloud_link.connected while a node holds the
-- lock of the hub's link shard (class 3, docs/architecture.md §4), so a
-- stream whose holder lost the lock counts as down before the next holder
-- records its takeover (link_up, as a hub's own series reads it).
CREATE FUNCTION link_up(shard int, connected boolean) RETURNS boolean
LANGUAGE sql STABLE SET search_path = pg_catalog, pg_temp AS $$
SELECT connected AND EXISTS (
SELECT 1 FROM pg_locks k
WHERE k.locktype = 'advisory' AND k.granted AND k.objsubid = 2 AND k.classid = 3::oid AND k.objid = shard::oid
AND k.database = (SELECT d.oid FROM pg_database d WHERE d.datname = current_database()))
$$;

CREATE FUNCTION connected_hubs() RETURNS SETOF uuid
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT l.hub_id FROM excubio.cloud_link l JOIN excubio.hub h ON h.id = l.hub_id
WHERE excubio.link_up(h.link_shard, l.connected)
$$;

-- What the heartbeats to Watch report (docs/architecture.md §9), for every
-- hub enrolled with a Watch key and not being deleted, in one call a turn:
-- the cloud's id of the hub, when its link certificate (and with it the
-- Watch key, which enrolment writes in the same transaction) last changed,
-- its active revision, its pipeline lag over its lanes (NULL while one was
-- never processed) and its link's state (link_up) with its change. The
-- sealed Watch key and the spec are read under the hub's own setting, by a
-- node that doesn't hold them for this identity or revision yet.
CREATE FUNCTION watch_states()
RETURNS TABLE (hub_id uuid, cloud_hub_id uuid, identity_at timestamptz, revision bigint, pipeline_lag_seconds float8,
link_up boolean, link_since timestamptz)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
WITH lag AS (
SELECT h.id, CASE WHEN bool_or(p.processed_to = '-infinity') THEN NULL
ELSE greatest(extract(epoch FROM now() - min(p.processed_to))::float8, 0) END AS seconds
FROM excubio.hub h CROSS JOIN excubio.installation i CROSS JOIN generate_series(0, h.lanes - 1) l
JOIN excubio.partition_owner p ON p.partition = (h.lane_base + l) % i.partitions
GROUP BY h.id
)
SELECT h.id, h.cloud_hub_id, c.cert_expires_at, a.revision, lag.seconds, excubio.link_up(h.link_shard, c.connected), c.state_since
FROM excubio.hub h JOIN excubio.cloud_link c ON c.hub_id = h.id
LEFT JOIN excubio.active_revision a ON a.hub_id = h.id
LEFT JOIN lag ON lag.id = h.id
WHERE h.cloud_hub_id IS NOT NULL AND c.watch_key_data_key IS NOT NULL AND h.state <> 'deleting'
ORDER BY h.id
$$;

-- The hubs with work in a partition's step from the previous step's clock
-- after to its clock due (§4 partition_owner), by id: those with
-- unnumbered events or commands of the partition, with their number up to
-- batch, which the fair share divides; those with timers of the partition
-- due by then, and those whose lanes include the partition with an
-- activation in between, which the step passes for the hub's alerts of the
-- partition, with 0. The hubs with unnumbered rows are found by skipping
-- through the index from hub to hub, so a hub's storm costs one probe. A
-- hub being deleted has no work.
CREATE FUNCTION pending_hubs(part int, after timestamptz, due timestamptz, batch int)
RETURNS TABLE (hub_id uuid, unnumbered int)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
WITH RECURSIVE e AS (
(SELECT x.hub_id FROM excubio.event x WHERE x.partition = part AND x.seq IS NULL ORDER BY x.hub_id LIMIT 1)
UNION ALL
SELECT (SELECT x.hub_id FROM excubio.event x WHERE x.partition = part AND x.seq IS NULL AND x.hub_id > e.hub_id ORDER BY x.hub_id LIMIT 1)
FROM e WHERE e.hub_id IS NOT NULL
), c AS (
(SELECT x.hub_id FROM excubio.command x WHERE x.partition = part AND x.seq IS NULL ORDER BY x.hub_id LIMIT 1)
UNION ALL
SELECT (SELECT x.hub_id FROM excubio.command x WHERE x.partition = part AND x.seq IS NULL AND x.hub_id > c.hub_id ORDER BY x.hub_id LIMIT 1)
FROM c WHERE c.hub_id IS NOT NULL
), rows AS (
SELECT h.hub_id, least(batch,
(SELECT count(*) FROM (SELECT FROM excubio.event x WHERE x.partition = part AND x.hub_id = h.hub_id AND x.seq IS NULL LIMIT batch) n)
+ (SELECT count(*) FROM (SELECT FROM excubio.command x WHERE x.partition = part AND x.hub_id = h.hub_id AND x.seq IS NULL LIMIT batch) n))::int AS n
FROM (SELECT e.hub_id FROM e WHERE e.hub_id IS NOT NULL UNION SELECT c.hub_id FROM c WHERE c.hub_id IS NOT NULL) h
), other AS (
SELECT t.hub_id FROM excubio.timer t WHERE t.partition = part AND t.due_at <= due
UNION
SELECT a.hub_id FROM excubio.activation_log a JOIN excubio.hub h ON h.id = a.hub_id, excubio.installation i
WHERE a.activated_at > after AND a.activated_at < due AND (part - h.lane_base + i.partitions) % i.partitions < h.lanes
)
SELECT u.hub_id, max(u.n) FROM (SELECT * FROM rows UNION ALL SELECT other.hub_id, 0 FROM other) u
WHERE NOT EXISTS (SELECT FROM excubio.hub d WHERE d.id = u.hub_id AND d.state = 'deleting')
GROUP BY u.hub_id ORDER BY u.hub_id
$$;

-- The hubs of a correlator shard with work in its step (§4
-- correlator_owner), by id, each with its global watermark (the lowest
-- processed_to of its lanes), its correlator_progress (-infinity without
-- a row), its unnumbered commands of the shard's partition and its input
-- up to the watermark (inbox entries, timers due and numbered commands),
-- each counted up to batch, and whether it activated something after its
-- progress up to the watermark or has no progress yet. A hub with none of
-- these is left out.
CREATE FUNCTION correlator_hubs(shard int, batch int)
RETURNS TABLE (hub_id uuid, watermark timestamptz, done timestamptz, unnumbered int, input int, activated boolean)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
WITH h AS (
SELECT h.id,
(SELECT min(o.processed_to) FROM excubio.partition_owner o WHERE (o.partition - h.lane_base + i.partitions) % i.partitions < h.lanes) AS wm,
(SELECT p.processed_to FROM excubio.correlator_progress p WHERE p.hub_id = h.id) AS done
FROM excubio.hub h, excubio.installation i WHERE h.correlator_shard = shard AND h.state <> 'deleting'
), w AS (
SELECT h.id, h.wm, coalesce(h.done, '-infinity') AS done,
(SELECT count(*) FROM (SELECT FROM excubio.command c WHERE c.partition = -1 - shard AND c.hub_id = h.id AND c.seq IS NULL LIMIT batch) n)::int AS unnumbered,
((SELECT count(*) FROM (SELECT FROM excubio.correlator_inbox x WHERE x.hub_id = h.id AND x.processed_at IS NULL AND x.received_at <= h.wm LIMIT batch) n)
+ (SELECT count(*) FROM (SELECT FROM excubio.timer t WHERE t.hub_id = h.id AND t.partition = -1 - shard AND t.due_at <= h.wm LIMIT batch) n)
+ (SELECT count(*) FROM (SELECT FROM excubio.command c WHERE c.partition = -1 - shard AND c.hub_id = h.id AND c.seq IS NOT NULL
AND c.applied_at IS NULL AND c.received_at <= h.wm LIMIT batch) n))::int AS input,
(h.done IS NULL OR EXISTS (SELECT FROM excubio.activation_log a WHERE a.hub_id = h.id AND a.activated_at > h.done AND a.activated_at <= h.wm)) AS activated
FROM h
)
SELECT w.id, w.wm, w.done, w.unnumbered, w.input, w.activated FROM w WHERE w.unnumbered > 0 OR w.input > 0 OR w.activated ORDER BY w.id
$$;

-- What the node's loops over the hubs look at first, so an idle hub costs
-- them nothing (docs/architecture.md §12): the time of each hub's latest
-- revision activation, whose spec a node loads again only when it
-- changed; the hubs with an enabled audit sink; and the hubs whose audit
-- chain is due an anchor (entries and no anchor within every) or has an
-- anchor the cloud hasn't recorded (cloud_link.anchor_seq).
CREATE FUNCTION revision_activations() RETURNS TABLE (hub_id uuid, activated_at timestamptz)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT h.id, (SELECT max(a.activated_at) FROM excubio.activation_log a WHERE a.hub_id = h.id AND a.kind = 'revision')
FROM excubio.hub h ORDER BY h.id
$$;

CREATE FUNCTION audit_sink_hubs() RETURNS SETOF uuid
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT DISTINCT s.hub_id FROM excubio.audit_sink s WHERE s.enabled ORDER BY 1
$$;

CREATE FUNCTION anchor_hubs(every interval) RETURNS TABLE (hub_id uuid, due boolean, unsent boolean)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT w.id, w.due, w.unsent FROM (
SELECT h.id,
EXISTS (SELECT FROM excubio.audit_event e WHERE e.hub_id = h.id)
AND coalesce((SELECT e.at FROM excubio.audit_event e WHERE e.hub_id = h.id AND e.action = 'audit.anchor' ORDER BY e.seq DESC LIMIT 1)
<= now() - every, true) AS due,
EXISTS (SELECT FROM excubio.audit_event e, excubio.cloud_link l
WHERE e.hub_id = h.id AND e.action = 'audit.anchor' AND l.hub_id = h.id AND e.seq > l.anchor_seq) AS unsent
FROM excubio.hub h) w
WHERE w.due OR w.unsent ORDER BY w.id
$$;

-- The time of an activation (§4 activation_log), taken under the
-- activation lock: after the clock, every partition's and correlator
-- shard's last numbering and the installation's latest activation. now
-- stands in for the database's clock, as in step_clock.
CREATE FUNCTION activation_clock(now timestamptz) RETURNS timestamptz
LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT greatest(coalesce(now, clock_timestamp()),
(SELECT max(o.last_received_at) FROM excubio.partition_owner o) + interval '1 microsecond',
(SELECT max(o.last_received_at) FROM excubio.correlator_owner o) + interval '1 microsecond',
(SELECT max(a.activated_at) FROM excubio.activation_log a) + interval '1 microsecond')
$$;

-- Every hub's gauges for its usage (§0 hub_usage): the CIs of its active
-- snapshot and its relays enrolled and not revoked.
CREATE FUNCTION hub_usage_gauges() RETURNS TABLE (hub_id uuid, cis bigint, relays int)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT h.id,
(SELECT (s.counts->>'cis')::bigint FROM excubio.inventory_snapshot s
WHERE s.hub_id = h.id AND s.state = 'active' ORDER BY s.number DESC LIMIT 1),
(SELECT count(*)::int FROM excubio.relay r WHERE r.hub_id = h.id AND r.revoked_at IS NULL)
FROM excubio.hub h
$$;

-- excubio_hub_lookup owns the lookup functions and step_clock (§4), which
-- reads every hub's activations (CREATE on the schema is needed for the
-- change of owner only), and only excubio_hub_app may call them.
GRANT CREATE ON SCHEMA excubio TO excubio_hub_lookup;
ALTER FUNCTION lookup_hub_by_host(text) OWNER TO excubio_hub_lookup;
ALTER FUNCTION lookup_hub_by_mail_domain(text) OWNER TO excubio_hub_lookup;
ALTER FUNCTION connected_hubs() OWNER TO excubio_hub_lookup;
ALTER FUNCTION watch_states() OWNER TO excubio_hub_lookup;
ALTER FUNCTION pending_hubs(int, timestamptz, timestamptz, int) OWNER TO excubio_hub_lookup;
ALTER FUNCTION correlator_hubs(int, int) OWNER TO excubio_hub_lookup;
ALTER FUNCTION activation_clock(timestamptz) OWNER TO excubio_hub_lookup;
ALTER FUNCTION revision_activations() OWNER TO excubio_hub_lookup;
ALTER FUNCTION audit_sink_hubs() OWNER TO excubio_hub_lookup;
ALTER FUNCTION anchor_hubs(interval) OWNER TO excubio_hub_lookup;
ALTER FUNCTION hub_usage_gauges() OWNER TO excubio_hub_lookup;
ALTER FUNCTION step_clock(timestamptz, timestamptz) OWNER TO excubio_hub_lookup;
REVOKE EXECUTE ON FUNCTION lookup_hub_by_host(text), lookup_hub_by_mail_domain(text), connected_hubs(), watch_states(),
pending_hubs(int, timestamptz, timestamptz, int), correlator_hubs(int, int), activation_clock(timestamptz),
step_clock(timestamptz, timestamptz), revision_activations(), audit_sink_hubs(), anchor_hubs(interval),
hub_usage_gauges() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION lookup_hub_by_host(text), lookup_hub_by_mail_domain(text), connected_hubs(), watch_states(),
pending_hubs(int, timestamptz, timestamptz, int), correlator_hubs(int, int), activation_clock(timestamptz),
step_clock(timestamptz, timestamptz), revision_activations(), audit_sink_hubs(), anchor_hubs(interval),
hub_usage_gauges() TO excubio_hub_app;
REVOKE CREATE ON SCHEMA excubio FROM excubio_hub_lookup;