VGSF CONSTITUTION BOOK II — PART C: PLATFORM ARCHITECTURE
Chapter 2 of 6 in this Part
P2 — Database Architecture
Document record
| Field | Value |
|---|---|
| Constitutional Series | P — Platform Architecture |
| Source Documents | FOUNDATION_G9_DATABASE_CONSTITUTION.md · FOUNDATION_G8_REGISTRY_GOVERNANCE_MODEL.md |
| Source Path | dharma_erp/01_CONSTITUTION/doctrine/G9_CONSTITUTIONAL_TECHNICAL_ARCHITECTURE/ · dharma_erp/01_CONSTITUTION/doctrine/G8_PLATFORM_ARCHITECTURE/ |
| Version | 1.0 |
| Certified | Ratified — G9_CONSTITUTIONALLY_ACCEPTED (98/100) |
| Certifying Program | Constitutional Architecture Council — G9 phase |
| REF Domain | N/A — Database Doctrine (applies to all REF domains) |
| Classification Triple | N/A — Constitutional Technical Architecture |
| Amendment | G8A-05 adds Federation Registry class to Registry Governance Model |
| Position in Book | Part C, Chapter 2 of 6 chapters in this Part |
⚠ STACK-DECISION CURRENCY BANNER — ADR-0003 (supersedes ADR-0002), Primary Steward verdict, 2026-06-26.
Frontend: Next.js (React) — one app, all audiences. ERP pages: Server Components (data-sovereign). Donor/Audit/Board: Client Components. Public: SSG. Backend: FastAPI · PostgreSQL · asyncpg raw SQL, no ORM (Backend Option D). Source of truth:03_PLATFORM/docs/decisions/ADR-0003-Greenfield-Stack-Decision.md.
P1 established the constitutional philosophy and the ten platform laws. P2 now specifies the first and most foundational implementation layer: the database — the substrate in which every domain record lives, where conservation laws are enforced, and where entity sovereignty is maintained.
§1 — PostgreSQL: The Constitutional Mandate
PostgreSQL 16+ is constitutionally mandated as the primary domain record store. This is not a technology preference; it is a constitutional determination arising from five requirements that no other evaluated database satisfies simultaneously:
Requirement 1 — Row-Level Security (RLS): Multi-entity data sovereignty requires that entity A's records are invisible to entity B's sessions at the database layer — not merely at the application layer. PostgreSQL's native RLS enforces this at the database level. When app.current_entity_id is set for a session, every query against a constitutional table automatically filters to that entity's records. No application-layer filtering code can achieve equivalent security guarantees: a bug in application filtering exposes data; a RLS policy has no such vulnerability.
Requirement 2 — Database-Level Triggers: The No-Delete invariant (Law G8-2, Law G9-2) must fire for every database session — including direct psql connections, migration scripts, and administrative sessions. PostgreSQL triggers satisfy this requirement. An application-layer no-delete guard, by contrast, is bypassed by any direct database access.
Requirement 3 — pgaudit Extension: The constitutional audit architecture requires a database-level audit layer beneath the application audit middleware. pgaudit captures every SQL statement executed against the database, including statements made by direct connections that bypass the application. This is the fourth audit layer and the one that is most resistant to circumvention.
Requirement 4 — Schema Namespacing: Each constitutional domain occupies its own PostgreSQL schema. ref001.parties, ref002.relationships, ref003.places — domain boundary enforcement at the schema layer prevents accidental cross-domain coupling and makes it impossible for application code to join across domains without an explicit, reviewed cross-schema query.
Requirement 5 — ACID Transactions: Cross-domain operations (for example, creating an Event that simultaneously creates an Obligation and records an Authority grant) must be atomic. PostgreSQL's ACID guarantees ensure that a cross-domain operation either completes fully or leaves no partial state. Distributed databases (CockroachDB, 58/100) cannot provide equivalent ACID guarantees across the constitutional domain boundary.
§2 — The Domain Schema Architecture
Each constitutional domain occupies a distinct PostgreSQL schema:
ref001 — Identity (Party, Person, Organization, AI_SYSTEM)
ref002 — Relationship
ref003 — Place
ref004 — Event
ref005 — Resource
ref006 — Document
ref007 — Obligation
ref008 — Authority
ref009 — Interaction
ref009c1 — Communication (REF009.C1 certified specialization)
ref010 — Case (AGGREGATE-ROOT)
ref011 — Schedule
ref013 — Knowledge
ref014 — Initiative (AGGREGATE-ROOT)
ref006x1 — Policy (extension of REF006)
ref006x2 — Directive (extension of REF006)
ref006x3 — License (extension of REF006)
ref006x4 — Mandate (extension of REF006)
ref007x1 — Financial Obligation (extension of REF007)
ref008x1 — Financial Authority (extension of REF008)
ref008x2 — Governance Authority (extension of REF008)
con_project — Project Composite (CON-PROJECT)
con_campaign — Campaign Composite (CON-CAMPAIGN)
drv_measurement — Measurement Derived (DRV-MEASUREMENT)
audit — Audit log (cross-domain, append-only)
registry — Global and domain registries (controlled vocabularies)
federation — Federation tables (GPI, inter-entity records)Constitutional Rule: Cross-schema foreign keys are not permitted at the database layer. Cross-domain references are expressed as UUID columns carrying the ID of the referenced record from another schema. Joins across schemas are performed at the application layer with explicit authority checks. This rule enforces domain boundary separation at the database level.
§3 — The Constitutional Base Columns
Every domain table carries the constitutional base columns. There is no ORM base class (the ERP uses no ORM — raw asyncpg + hand-authored DDL); the base columns are a mandatory column block included verbatim in every domain table's hand-authored DDL. These mandatory audit fields appear on every constitutional record:
-- Constitutional base columns — included in the CREATE TABLE of EVERY domain table.
-- No migration may remove these columns from any table.
-- (Shown standalone; in practice these lines are pasted into each domain DDL file.)
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
entity_id UUID NOT NULL,
-- ↑ Tenant isolation key — RLS policy filters on this field
lifecycle_status TEXT NOT NULL DEFAULT 'ACTIVE',
-- ↑ Values from registry: ACTIVE, INACTIVE, ARCHIVED, HISTORICAL, SUSPENDED
-- (enforced by a CHECK constraint / FK to the Lifecycle Status Registry)
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
created_by UUID NOT NULL,
-- ↑ References ref001.parties.id — the Party who created this record
updated_at TIMESTAMPTZ,
updated_by UUID,
version INTEGER NOT NULL DEFAULT 1,
-- ↑ Optimistic locking — prevents concurrent write conflicts
basis_document_id UUID
-- ↑ References ref006.documents.id — the Document that authorized the creation
-- ↑ Required for authority-bearing records (REF008, REF007, etc.)
-- ↑ Optional for operational records (REF004 events, REF009 interactions)§4 — Row-Level Security Architecture
Row-Level Security (RLS) enforces entity data sovereignty at the database layer. Every constitutional domain table has RLS enabled and carries an entity isolation policy:
-- Enable RLS on every domain table (example: ref001.parties)
ALTER TABLE ref001.parties ENABLE ROW LEVEL SECURITY;
ALTER TABLE ref001.parties FORCE ROW LEVEL SECURITY;
-- FORCE ensures the policy applies even to the table owner
-- Entity isolation policy
CREATE POLICY entity_isolation ON ref001.parties
USING (entity_id = current_setting('app.current_entity_id')::uuid);
-- Application code sets this variable at session start:
-- SET LOCAL app.current_entity_id = '...';
-- (Set within the transaction; cleared when transaction ends)Constitutional Rule: FORCE ROW LEVEL SECURITY is mandatory. Without it, the table owner (typically the application database user) bypasses RLS — creating a privilege escalation path. FORCE ensures the policy applies to all sessions without exception.
Constitutional Rule: The app.current_entity_id session variable is set by the API middleware before any database query executes. It is set within a transaction (using SET LOCAL) so it is automatically cleared when the transaction completes, preventing session reuse attacks.
Federation Access Rule: Federation queries that legitimately require cross-entity access use a dedicated federation database user with a separate RLS policy:
-- Federation policy: allows access to GPI-resolved records only
CREATE POLICY federation_access ON ref001.parties
FOR SELECT
TO federation_user
USING (gpi_id IS NOT NULL AND gpi_id = ANY(
SELECT gpi_id FROM federation.authorized_gpi_access
WHERE requesting_entity_id = current_setting('app.current_entity_id')::uuid
));§5 — The No-Delete Trigger
The No-Delete Trigger is the database-level enforcement of Law G8-2 and Law G9-2. It fires for every database session, including direct database connections that bypass the application layer:
-- Universal no-delete trigger function
CREATE OR REPLACE FUNCTION constitutional_no_delete()
RETURNS TRIGGER AS $$
BEGIN
RAISE EXCEPTION
'Constitutional violation: DELETE is prohibited on table %. '
'Use lifecycle_transition(status => ARCHIVED) or lifecycle_transition(status => HISTORICAL). '
'Record ID: %. Entity: %',
TG_TABLE_NAME,
OLD.id,
OLD.entity_id;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
-- Applied to every constitutional domain table
-- (Example: ref001.parties; same pattern for all domain schemas)
CREATE TRIGGER no_delete_parties
BEFORE DELETE ON ref001.parties
FOR EACH ROW
EXECUTE FUNCTION constitutional_no_delete();Constitutional Rule: The no-delete trigger is applied as part of the domain schema migration (Migration Rule M3 — see §7). No migration may drop or disable this trigger. Corrections to records must be made through UPDATE (to correct a data error) or lifecycle transition (to end-of-life a record). The reason for the record's ARCHIVED or HISTORICAL status is recorded in the change history table.
§6 — The Three Database-Level Audit Layers
The G9 Database Constitution specifies three database-level audit mechanisms, operating beneath the application audit middleware:
Layer 1 — No-Delete Trigger (Constitutional Guard)
Described in §5. Prevents all deletion; produces an exception with full context when a DELETE is attempted.
Layer 2 — pgaudit Extension (SQL Statement Capture)
pgaudit captures every SQL statement executed against the database:
-- pgaudit configuration (postgresql.conf)
shared_preload_libraries = 'pgaudit'
pgaudit.log = 'ddl, write'
-- 'ddl' captures schema changes (CREATE TABLE, ALTER TABLE, DROP TABLE)
-- 'write' captures INSERT, UPDATE, DELETE, TRUNCATE
-- This combination captures every data-modifying operation at the database level
pgaudit.log_relation = on
-- Logs the relation (table) name for every captured statement
pgaudit.log_parameter = on
-- Logs bind parameters (prevents obfuscation through parameterized queries)pgaudit records are written to the PostgreSQL log — a separate file from the application log, controlled by the database administrator, not the application. This separation ensures the application cannot suppress or modify its own audit record.
Layer 3 — Append-Only Audit Table
The application audit middleware writes to audit.action_log. This table is protected by RLS policies that prohibit UPDATE and DELETE:
-- Audit schema and table
CREATE SCHEMA IF NOT EXISTS audit;
CREATE TABLE audit.action_log (
log_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
entity_id UUID NOT NULL,
actor_party_id UUID NOT NULL, -- REF001 Party who performed the action
action_type TEXT NOT NULL, -- 'CREATE', 'UPDATE', 'LIFECYCLE_TRANSITION', 'VIEW_SENSITIVE'
domain TEXT NOT NULL, -- 'REF001', 'REF007', etc.
record_id UUID NOT NULL, -- ID of the affected record
action_timestamp TIMESTAMPTZ NOT NULL DEFAULT now(),
request_id TEXT, -- Correlation ID from X-Request-ID header
authority_grant_id UUID, -- REF008 grant under which the action was authorized
changes_json JSONB, -- Before/after diff for UPDATE operations
ip_address INET, -- Client IP (from API middleware)
user_agent TEXT -- Client user agent
);
-- Append-only protection: UPDATE and DELETE are constitutionally prohibited
ALTER TABLE audit.action_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE audit.action_log FORCE ROW LEVEL SECURITY;
CREATE POLICY no_update_audit ON audit.action_log
FOR UPDATE USING (FALSE);
CREATE POLICY no_delete_audit ON audit.action_log
FOR DELETE USING (FALSE);
CREATE POLICY insert_audit ON audit.action_log
FOR INSERT WITH CHECK (TRUE);
CREATE POLICY select_audit ON audit.action_log
FOR SELECT USING (entity_id = current_setting('app.current_entity_id')::uuid);§7 — The Migration Doctrine
Database migrations are governed by six migration rules (M1–M6):
Migration Rule M1 — Forward Only: No migration may undo a previous migration. No reverse/downgrade operation may be defined that drops a table or removes data. Migrations are hand-authored .sql DDL files, one per domain, named and numbered so they apply in a deterministic forward order (no ORM, no Alembic). Applying the ordered DDL files in sequence against the certified schema is the constitutional migration procedure; there is no auto-generated, reversible migration graph.
Migration Rule M2 — No DROP TABLE: No migration may contain DROP TABLE for a constitutional domain table. The table contains institutional records; records are permanent. A table that is no longer needed for the current domain scope is emptied through lifecycle transitions, not dropped.
Migration Rule M3 — Trigger Applied: Every migration that creates a new domain table must include the application of the no-delete trigger. A table without the no-delete trigger is constitutionally incomplete.
Migration Rule M4 — RLS Enabled: Every migration that creates a new domain table must include ENABLE ROW LEVEL SECURITY and FORCE ROW LEVEL SECURITY and the entity isolation policy. A table without RLS is constitutionally non-compliant.
Migration Rule M5 — Reviewed: Every migration is reviewed by a second engineer before application to any environment above M1 (development). The review confirms: no DROP TABLE, no disabling of triggers, no disabling of RLS, no raw SQL with user-controlled input, no removal of constitutional fields.
Migration Rule M6 — Zero-Downtime at M2+: From M2 onward, migrations that lock tables for more than 1 second are prohibited. Additive changes (new columns with defaults, new indexes with CONCURRENTLY) are constitutional. Blocking changes require a multi-step migration plan approved by the Primary Steward.
Hand-Authored DDL File Template
Each migration is a hand-authored .sql file (no Alembic). Files are numbered per domain so they apply in deterministic forward order — e.g. ref004/0007_add_event_outcome_column.sql. Every file opens with the constitutional-basis comment block and is forward-only (no reverse/downgrade section exists):
-- ============================================================================
-- [DOMAIN] — [description]
-- File: ref004/0007_<description>.sql Applied after: ref004/0006_*.sql
-- Authored: [date] Author: [engineer name]
--
-- Constitutional review (Migration Rules M1–M6):
-- [ ] M1 Forward-only — no DROP/destructive operation; no reverse section
-- [ ] M2 No DROP TABLE on a constitutional domain table
-- [ ] M3 No-delete trigger applied (if this file creates a new table)
-- [ ] M4 RLS ENABLE + FORCE + entity_isolation policy (if new table)
-- [ ] No column removal from the constitutional base columns
-- [ ] M6 Zero-downtime verified (M2+: additive only; CREATE INDEX CONCURRENTLY)
-- [ ] M5 Reviewed by: [reviewer name]
-- ============================================================================
BEGIN;
-- All operations here are additive; never destructive.
-- Example (additive column add — constitutional):
ALTER TABLE ref004.events
ADD COLUMN IF NOT EXISTS outcome_summary TEXT;
-- New tables must, in the same file, include the constitutional base columns,
-- ENABLE + FORCE ROW LEVEL SECURITY, the entity_isolation policy, and the
-- no-delete trigger (Rules M3, M4 — see §4 and §5).
COMMIT;
-- Constitutional note: there is NO downgrade. These DDL files are forward-only.
-- To correct a change, author a new, higher-numbered forward DDL file.§8 — The Historical Replay Architecture
The constitutional database must support temporal queries — the ability to reconstruct the state of any domain record at any point in its history. This is not optional: it is required by the audit architecture (Law G8-4) and by the institutional permanence doctrine (Law G8-2).
Change History Table
Every domain table has a corresponding change history table:
-- Change history table (example: ref001.party_history)
CREATE TABLE ref001.party_history (
history_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
party_id UUID NOT NULL REFERENCES ref001.parties(id),
entity_id UUID NOT NULL,
changed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
changed_by UUID NOT NULL, -- REF001 Party ID
change_type TEXT NOT NULL, -- 'CREATE', 'UPDATE', 'LIFECYCLE_TRANSITION'
previous_values JSONB NOT NULL, -- Complete snapshot of the record BEFORE the change
new_values JSONB NOT NULL -- Complete snapshot of the record AFTER the change
);
-- History tables are also append-only
ALTER TABLE ref001.party_history ENABLE ROW LEVEL SECURITY;
ALTER TABLE ref001.party_history FORCE ROW LEVEL SECURITY;
CREATE POLICY no_update_party_history ON ref001.party_history FOR UPDATE USING (FALSE);
CREATE POLICY no_delete_party_history ON ref001.party_history FOR DELETE USING (FALSE);Temporal Query Model
-- Reconstruct state of a Party record as of a specific date
-- Used for historical reporting, audit review, and federation reconciliation
WITH history_as_of AS (
SELECT new_values, changed_at,
ROW_NUMBER() OVER (ORDER BY changed_at DESC) as rn
FROM ref001.party_history
WHERE party_id = '...'
AND changed_at <= '2025-03-15 00:00:00+05:30' -- As-of date
)
SELECT new_values
FROM history_as_of
WHERE rn = 1;§9 — The Registry Governance Model
Law G8-6 requires that no classification field uses free text. All classification fields reference governed registries. The registry architecture establishes four registry classes:
Four Registry Classes
Class 1 — Global Registries: Values governed by the Dharma ERP Constitutional Architecture Council. Shared across all entities and all federation members. Not configurable at the entity level.
| Registry Code | Name | Examples |
|---|---|---|
| REG-01 | Country Registry | ISO 3166-1 country codes + constitutional metadata |
| REG-02 | Currency Registry | ISO 4217 currency codes |
| REG-03 | Language Registry | BCP 47 language codes |
| REG-04 | Lifecycle Status Registry | ACTIVE, INACTIVE, ARCHIVED, HISTORICAL, SUSPENDED |
| REG-05 | Timezone Registry | IANA timezone identifiers |
Class 2 — Domain Registries: Values governed by the domain constitution (R-ARCH). One registry per domain per classification field. Default values established in G3.5 domain constitutions; entity may add local values within constraints.
Examples:
party_type: PERSON, ORGANIZATION, AI_SYSTEM (REF001)relationship_type: MEMBER_OF, EMPLOYED_BY, MENTORED_BY, DONOR_OF (REF002)event_type: TEMPLE_PROGRAMME, OUTREACH_EVENT, GOVERNANCE_MEETING (REF004)document_type: POLICY, DIRECTIVE, GRANT_REPORT, MINUTES (REF006)obligation_type: FINANCIAL_COMMITMENT, DONOR_PLEDGE, GRANT_OBLIGATION (REF007)grant_type: MANAGEMENT_AUTHORITY, FINANCIAL_APPROVAL_AUTHORITY, GOVERNANCE_AUTHORITY (REF008)
Class 3 — Entity Registries: Values governed by the entity (Primary Steward). Local vocabulary for entity-specific classification. Entity values must not conflict with Global or Domain registry values. Entity registry values are only valid within that entity's data.
Class 4 — Federation Registries: Values governed by the Federation Council. Cross-entity vocabulary for federation operations. Added by G8A-05. Applies at M4+.
Registry Governance Model
Ownership: Each registry has a single constitutional owner (CAC for Global, R-ARCH for Domain, Entity Primary Steward for Entity, Federation Council for Federation).
Versioning: Registry changes are versioned. Each registry entry carries version, effective_from, effective_to (NULL = currently active), and retired_by (the program or authority that retired this value).
Change Process:
- Change request submitted to registry owner
- Registry owner reviews for constitutional compliance
- If approved: new value added with
effective_from= current date; or existing value retired witheffective_to= current date and replacement value added - Registry consumers notified of change (notification type: REGISTRY_CHANGE)
- Dependent domain records that used the retired value are NOT retroactively changed — they retain their historical registry value as their permanent record
Constitutional Rule — Retirement Only: Registry values are never deleted. A registry value that should no longer be used is retired by setting effective_to to the retirement date. Historical records that carry the retired value remain valid and searchable through historical search.
Registry API
GET /api/v1/registries/{registry_code} List active registry values
GET /api/v1/registries/{registry_code}?as_of=2024-01-01 Historical registry state
GET /api/v1/registries/{registry_code}/{value_code} Single registry value detail
POST /api/v1/registries/{registry_code}/values Add new value (authorized)
PUT /api/v1/registries/{registry_code}/{value_code}/retire Retire a value (authorized)Constitutional Rule: Registry modification endpoints require a REF008-grant-id header carrying an active Management Authority grant scoped to REGISTRY_GOVERNANCE for the relevant registry class.
§10 — Distributed Database Rejection
The constitutional requirement for database-level conservation laws — specifically, that balance = Σ(recorded transitions) holds without exception — cannot be satisfied by distributed database architectures. The CAP theorem forces a distributed database to choose between Consistency and Availability under network partition. The conservation law is a consistency requirement: it cannot be relaxed under network partition without violating the invariant.
The constitutional verdict:
Distributed database (CockroachDB, PlanetScale, DynamoDB) as primary domain store:
CONSTITUTIONALLY PROHIBITED
Reason: CAP theorem conflicts with conservation law invariants;
no equivalent to PostgreSQL triggers across distributed nodes;
no equivalent RLS enforcement without application-layer filtering;
entity sovereignty cannot be enforced at the database layer.
Score: CockroachDB 58/100 (evaluated in G9)Federation at M4+ does not require a distributed database. Each entity maintains its own PostgreSQL instance. Federation operations are performed through the Federation Adapter Layer, which reads from and writes to each entity's own database through the constitutional API. The federation is a network of sovereign databases, not a distributed database.
Constitutional Colophon — P2
This chapter establishes the database architecture of the Constitutional ERP: PostgreSQL as constitutionally mandated substrate; schema-per-domain isolation; the constitutional base columns as the mandatory foundation for every domain table (carried in hand-authored DDL, no ORM); Row-Level Security as the entity sovereignty enforcement mechanism; the No-Delete Trigger as the database-level guard of the permanence doctrine; the three database-level audit layers; the six migration rules; the historical replay architecture; and the four-class registry governance model.
It operates within Part C under Law G9-1: PostgreSQL is constitutionally mandated and cannot be replaced without Constitutional Architecture Council resolution with equivalent evidence of compliance.
Readers proceeding to P3 — Backend Service Architecture should carry forward: every database constraint established here — no-delete trigger, RLS entity isolation, schema boundaries, registry governance — is a constitutional invariant that the backend service layer must enforce at the application level as well, so that the two layers together provide defense-in-depth rather than redundancy.
