gnomonlearn
Docs/PostgreSQL/RFC-0053

RFC-0053 · View-Mapping Layer

Versioned draft snapshot

RFCs, reference catalogs, and evidence reflect Spec 3b2e3e7a114fb826b1445d39a48756b8fff629cd. Counts and pending/status notes belong to that snapshot. Read the dated project update for later progress.

Source repositories are private during staging. Links marked “repository access required” need access to the linked repository.

Status Draft corpus. Reference catalogs and RDF projections have generation drift checks; Gnomon proofs and projection semantics remain unverified for release.

View the generated reference catalog →

Read design questions and decisions →


Reference catalog: the diagnostics, linked-RFC graph, defined terms, and normative-rule index for this RFC are in the reference catalog, generated from the structured Lean module. This document carries the prose: design rationale, entity-shape definitions in context, and migration notes.


1. Purpose

The Gnomon graph stores every entity in graph.resource with a JSONB data payload. This is the right tradeoff for schema flexibility and uniform operations, but it has costs: PostgreSQL has no column statistics on JSONB keys; ad-hoc queries pay an extraction tax (data->>'name'); LLMs and BI tools can’t introspect typed columns.

The view-mapping layer restores the relational query interface at the SQL layer without giving up the graph storage model. It compiles entity-type declarations into typed SQL views in module-scoped PG schemas. Each view is:

  • Filtered by kind (only the entity-type’s instances).
  • Typed via expression casts ((data->>'name')::TEXT AS name).
  • Backed by expression indexes for planner statistics.
  • Security-barrier’d to prevent RLS leakage.
  • Eligible for materialization (a Postgres materialized view) when query patterns demand it.

This RFC specifies the view-mapping layer formally. It is the read-side companion of the projection algebra (RFC-0049) — specifically, the materialize: view mode (RFC-0049 §10.3) that makes projections persistent SQL artifacts.

The view-mapping layer is the spine of Gnomon’s query interface for application modules: a savvi.studio.team.entity_type.team declaration produces a savvi_studio_team.team view that any caller (operations, BI tools, AI systems, the graph client’s queries namespace) can query as standard SQL.


2. Definitions

TermMeaning
Entity-type viewA read-only SQL view filtered to one entity-type’s kind, with typed column extraction.
Module schemaThe PG schema named after the declaring module’s namespace (savvi.studio.team → savvi_studio_team).
Expression indexA PG index over a JSONB extraction expression — gives the planner real selectivity statistics.
Security barrier viewA PG view created with WITH (security_barrier = true) — prevents the planner from pushing user-supplied predicates below the view’s WHERE clause.
INSTEAD OF triggerA PG trigger on a view that intercepts writes. Phase 2 of the view-mapping layer routes view writes through the gnomon pipeline.
Materialized viewA PG materialized view (a real table backed by a query) used for hot read paths. Owns its own RLS.
Field schemaThe typed field declarations on an entity-type. Each field maps to one extracted column.

3. Generation Algorithm

3.1 Inputs

For each entity-type declaration the compiler observes:

entity-type team {
  kind: savvi.studio.team.entity_type.team
  description: A team entity
  supertype: schema:Organization
  fields:
    name:          { type: text, required: true, sdo: schema:name }
    platform:      { type: text, required: true }
    currentStatus: { type: select, options: [Active, Inactive], default: Active }
    description:   { type: textarea, sdo: schema:description }
}

The relevant inputs to view-mapping are:

  • kind — the LTREE classifier
  • fields — the typed field schema
  • The declaring module’s namespace — used to derive the view’s PG schema

3.2 Output

For each entity-type, the compiler emits:

  1. A PG schema if not already present (CREATE SCHEMA IF NOT EXISTS savvi_studio_team).
  2. A view in that schema, kind-filtered, typed-extracted, security-barrier’d.
  3. Expression indexes on graph.resource for the typed fields.
  4. (Phase 2) INSTEAD OF triggers routing INSERT/UPDATE/DELETE through the gnomon pipeline.

Example for the team entity-type above:

-- Schema (created once, reused by all entity-types in this module)
CREATE SCHEMA IF NOT EXISTS savvi_studio_team;

-- Owned by the module's role per RFC-0051 §4.2
ALTER SCHEMA savvi_studio_team OWNER TO role_savvi_studio_team;

-- The entity-type view
CREATE OR REPLACE VIEW savvi_studio_team.team
WITH (security_barrier = true) AS
SELECT
    r.id,
    r.external_id,
    (r.data->>'name')::TEXT          AS name,
    (r.data->>'platform')::TEXT      AS platform,
    (r.data->>'currentStatus')::TEXT AS current_status,
    (r.data->>'description')::TEXT   AS description,
    r.creator_id,
    r.created_at,
    r.updated_at
FROM graph.resource r
WHERE r.kind = 'savvi.studio.team.entity_type.team'::LTREE
  AND r.deleted_at IS NULL;

-- Expression indexes on the underlying graph.resource for planner statistics
CREATE INDEX IF NOT EXISTS idx_team_name
    ON graph.resource ((data->>'name'))
    WHERE kind = 'savvi.studio.team.entity_type.team'::LTREE
      AND deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_team_platform
    ON graph.resource ((data->>'platform'))
    WHERE kind = 'savvi.studio.team.entity_type.team'::LTREE
      AND deleted_at IS NULL;

3.3 Output naming

Gnomon conceptPG identifier
Module namespace savvi.studio.teamSchema savvi_studio_team
Entity-type local name teamView savvi_studio_team.team
Field currentStatusColumn current_status (camelCase → snake_case)
Index on field nameidx_<table>_<field>

The dot-to-underscore and camelCase-to-snake_case conversions are deterministic and reversible. The compiler emits a manifest mapping (view-mapping.json) that records every Gnomon-name ↔ PG-identifier pair for tooling.


4. Type Mapping

Each Gnomon field type maps to a PG cast and an index strategy:

Gnomon field typePG castIndex strategy
text::TEXTB-tree expression index
textarea::TEXTB-tree (for prefix); GIN tsvector for full-text search
number::NUMERICB-tree expression index
integer::BIGINTB-tree expression index
boolean::BOOLEANPartial index (rare; booleans have low cardinality)
date::DATEB-tree expression index
datetime, timestamp, instant::TIMESTAMPTZB-tree expression index
select (enum-like)::TEXTB-tree expression index (cardinality-bounded)
reference (ID)::BIGINTB-tree expression index
json(no cast — stays JSONB)GIN on subpath
bytes::BYTEA(rarely indexed)
uuid::UUIDB-tree expression index
ltree::LTREEGiST expression index

This is RFC-0051 §10’s type mapping applied to the field-extraction context. New types added to the Gnomon type model (RFC-0006) MUST extend this table.

4.1 Index policy

Not every field gets an index automatically. The compiler emits indexes for fields where:

  • The field is marked indexed: true (RFC-0008 §6.3a) explicitly.
  • The field is required: true AND its type supports B-tree.
  • The field is referenced by a query’s WHERE clause (compile-time analysis of declared queries — Phase 1 limited; Phase 2 expands via projection-aware analysis).

Fields outside these categories do not get expression indexes by default. Authors who need fine control declare indexes explicitly via the field modifier indexed(gist), indexed(gin), indexed(partial: <expr>), etc.

4.2 Index naming

Index names follow the pattern idx_<table>_<field>. Conflicts (same name, different definition) produce M53010.


5. Security Barrier and RLS Inheritance (KP29)

5.1 security_barrier

Every entity-type view MUST be created WITH (security_barrier = true). This prevents the PG planner from pushing user-supplied predicates below the view’s WHERE clause, which could otherwise leak rows by evaluating user functions against data the RLS policy would exclude.

5.2 RLS inheritance

Standard PostgreSQL views CANNOT have RLS policies directly — only tables can. But views inherit RLS from their underlying tables. Querying savvi_studio_team.team engages the RLS policies on graph.resource (RFC-0051 §7.3) automatically:

  • The principal must have read permission on each underlying resource per graph.has_permission(...).
  • Resources the principal cannot read are filtered out at the underlying-table level.
  • The view sees only the principal-visible subset.

This is the right answer for most queries. The combination of security_barrier + base-table RLS is the SH3-aligned (KP29) security model.

5.3 Materialized view exception

When an entity-type’s read pattern justifies materialization (high read volume, low write rate, query patterns dominated by aggregates), the framework MAY materialize the view as a real table:

CREATE MATERIALIZED VIEW savvi_studio_team.team_materialized AS
SELECT ... FROM graph.resource r WHERE r.kind = ... ;

A materialized view IS a table and CAN have its own RLS policies — simpler, kind-specific policies that avoid the per-result graph.has_permission cost. The materialization owns its own RLS:

ALTER TABLE savvi_studio_team.team_materialized ENABLE ROW LEVEL SECURITY;

CREATE POLICY team_select ON savvi_studio_team.team_materialized
FOR SELECT USING (
  -- Direct kind-specific policy
  graph.has_permission_cached(graph.current_user_id(), 'identity.user', id, 'savvi.studio.team.entity_type.team', 1::SMALLINT)
);

Materialization decisions are driven by a separate materialize: live | cached | view | reactive slot on the underlying projection (RFC-0049 §10.3) plus a heat-tracking layer that this RFC does NOT specify (future work).


6. Phase 1: Read-Only Views

6.1 Scope

Phase 1 (the initial deployment) implements read-only entity-type views. Writes to graph.resource go through:

  • Templates (the user-visible authoring path — RFC-0039)
  • Mutations (high-level wrappers — RFC-0049 §12)
  • Operations (lower-level wrappers — RFC-0043)

Direct INSERT INTO savvi_studio_team.team is rejected by PostgreSQL because the view has no INSTEAD OF trigger yet.

6.2 Use cases

Phase 1 use cases:

  • Application read queries — SELECT * FROM savvi_studio_team.team WHERE platform = 'ios'.
  • AI/LLM introspection — LLMs see typed columns and standard SQL, not JSONB extraction.
  • BI tooling and analytics — connectors discover the view automatically.
  • Operational queries — debugging, support, monitoring scripts.

7. Phase 2: Write-Through via INSTEAD OF Triggers (KP31)

7.1 Scope

Phase 2 adds INSTEAD OF triggers on entity-type views. INSERT/UPDATE/DELETE on a view route through the gnomon pipeline (validation, hooks, events, audit, provenance) — not raw graph.resource DML.

7.2 INSERT trigger

CREATE OR REPLACE FUNCTION savvi_studio_team.team_insert()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
DECLARE
  v_resource_id BIGINT;
BEGIN
  -- Build the JSONB data payload from view columns
  v_resource_id := graph.create_resource(
    p_kind := 'savvi.studio.team.entity_type.team'::LTREE,
    p_external_id := NEW.external_id,
    p_data := jsonb_build_object(
      'name',          NEW.name,
      'platform',      NEW.platform,
      'currentStatus', NEW.current_status,
      'description',   NEW.description
    ),
    p_creator_id := NEW.creator_id
  );
  NEW.id := v_resource_id;
  RETURN NEW;
END;
$$;

CREATE TRIGGER team_insert_trigger
INSTEAD OF INSERT ON savvi_studio_team.team
FOR EACH ROW EXECUTE FUNCTION savvi_studio_team.team_insert();

UPDATE and DELETE triggers follow the same pattern: route through graph.update_resource and graph.delete_resource respectively.

7.3 Template-marker requirement

Phase 2’s INSTEAD OF triggers MUST set the template marker GUC (gnomon.template_marker) before invoking graph.create_resource — otherwise the SH2 RLS policy (RFC-0051 §7.3) rejects the insert. The marker form for view writes is view-mapping:<schema>.<view>:

-- Inside the trigger function
PERFORM set_config('gnomon.template_marker', 'view-mapping:savvi_studio_team.team', true);

This satisfies the template-mediated creation invariant (RFC-0050 §3) — view writes are a recognized creation path that emits provenance with template.instance_of pointing to a synthetic core.template.view-mapping template.

7.4 Validation

INSTEAD OF triggers MUST run the entity-type’s compile-time validation (required-field checks, enum-value checks, custom validation hooks) before invoking graph.create_resource. Validation failures abort the insert with a domain error.

This is the same validation contract as direct template invocations; the trigger simply applies it on the SQL boundary.


8. Cross-Module Joins

Application modules frequently need joins across entity-type views from different modules. For example: a query joining savvi_studio_team.team to savvi_studio_product.product via a team.assigned-to predicate.

8.1 The pattern

SELECT t.id, t.name, p.id, p.name
FROM savvi_studio_team.team t
JOIN graph.statement s ON s.subject_id = t.id
  AND s.predicate_id = graph.get_predicate_id('team.assigned-to')
JOIN savvi_studio_product.product p ON p.id = s.object_id;

The middle table is graph.statement — the universal edge table. This is the relational interface that the gnomon model preserves: cross-entity relations are joins through the statement table.

8.2 Pre-built join views (optional)

For frequently-joined entity-type pairs, modules MAY pre-declare join views via a view declaration:

view teamProductAssignment {
  meaning: "Teams and the products they're assigned to."
  joins:
    - from: team
      predicate: team.assigned-to
      to: product
}

The compiler emits:

CREATE OR REPLACE VIEW savvi_studio_team.team_product_assignment
WITH (security_barrier = true) AS
SELECT
  t.id AS team_id, t.name AS team_name,
  p.id AS product_id, p.name AS product_name
FROM savvi_studio_team.team t
JOIN graph.statement s ON s.subject_id = t.id
  AND s.predicate_id = graph.get_predicate_id('team.assigned-to')
JOIN savvi_studio_product.product p ON p.id = s.object_id;

Pre-built join views inherit RLS from each component view’s underlying RLS — both endpoints must be readable by the principal.


9. Lifecycle and Rebuilding

9.1 View regeneration on entity-type change

Adding a field to an entity-type recreates the view:

DROP VIEW savvi_studio_team.team;
CREATE OR REPLACE VIEW savvi_studio_team.team WITH (security_barrier = true) AS
SELECT ..., (r.data->>'newField')::TEXT AS new_field, ...
FROM graph.resource r WHERE r.kind = '...'::LTREE AND r.deleted_at IS NULL;

DROP VIEW cascades to dependent views; the install plan (RFC-0041) must regenerate dependent views in topological order.

For materialized views, the regeneration is more involved:

DROP MATERIALIZED VIEW savvi_studio_team.team_materialized;
-- ... regenerate from new declaration
REFRESH MATERIALIZED VIEW savvi_studio_team.team_materialized;

The install pipeline emits these statements as part of the install plan; the destructive operation gate (KP26) requires explicit acknowledgment.

9.2 Removing a field

Removing a field requires:

  1. Drop the view’s column (via view recreation).
  2. Drop the corresponding expression index (DROP INDEX idx_team_oldfield).
  3. Optionally migrate data: remove the JSON key from existing rows (data migration via RFC-0016’s core.migrations.RemoveField).

The data payload on graph.resource is unaffected by the view; only the view changes shape. Existing rows still carry the JSON key until a migration removes it.

9.3 Adding indexes

Adding indexed: true to a field emits a new expression index. Existing rows are indexed via PG’s standard CREATE INDEX (long-running on large tables; the install plan SHOULD use CREATE INDEX CONCURRENTLY for production deployments — KP26 destructive-op-gate-aware).


10. Invariants

  1. Every entity-type view is WITH (security_barrier = true) (§5.1).
  2. Standard views inherit RLS from graph.resource; materialized views own their own RLS (§5.2, §5.3).
  3. INSTEAD OF triggers (Phase 2) MUST set gnomon.template_marker before invoking graph procedures (§7.3).
  4. INSTEAD OF triggers MUST run entity-type validation before write (§7.4).
  5. View column names use snake_case; module schema names replace . with _ (§3.3).
  6. Index naming follows idx_<view>_<field> (§4.2, M53010).
  7. Cross-module joins go through graph.statement — never through synthesized cross-schema FK constraints (§8.1).
  8. View regeneration is part of the install plan; destructive operations gate per KP26 (§9.1).

11. Compatibility and Migration

11.1 From direct JSONB queries

Application code that currently uses r.data->>'name' extraction patterns can migrate progressively:

Before: SELECT (data->>'name') FROM graph.resource WHERE kind = 'savvi.studio.team.entity_type.team'::LTREE
After:  SELECT name FROM savvi_studio_team.team

The view-mapping layer is additive — existing queries continue to work; new queries use the typed views.

11.2 From materialized fields

Some legacy modules denormalize fields into the JSON payload manually. The view-mapping layer subsumes this: declare the field on the entity-type, and the view extracts and indexes it. Existing data continues to satisfy the new view (since fields are extracted from the same JSON). No data migration required.

11.3 Phasing

PhaseCapabilityStatus
Phase 1Read-only views, expression indexes, security_barrierSpecified by this RFC
Phase 2INSTEAD OF triggers route writes through gnomon pipelineSpecified by this RFC, gated on RFC-0050 template-marker contract
Phase 3Generated CHECK constraints on enum/select fieldsFuture RFC
Phase 4Materialization heat-tracking + auto-promotionFuture RFC

Phase 1 is shippable now. Phase 2 ships when template-marker enforcement (RFC-0050) is in production.


Diagnostics

The diagnostic catalog for this RFC is authored in the structured Lean module and rendered in reference catalog § Diagnostics. Inline mentions in the prose above (e.g., “rejected with MNNxxx”) cross-link to the catalog at render time.

Linked References

The cross-RFC dependency graph is rendered in reference catalog § Linked References. Out-of-KG pointers to legacy code or external resources, when present, remain in this document under “Source-tree references” below.