Compare commits

..

1 Commits

Author SHA1 Message Date
f60158564d Family references discriminate through the referenced row's type
Intention: make local <prop>_type columns optional denormalization instead
of an engine requirement — writers should only ever have to say WHO.

Outcomes:
- compile_one_of: a type-strategy family REFERENCE (payer, source, target)
  now selects its polymorphic branch via the referenced row's own type —
  CASE (SELECT type FROM agreego.entity WHERE id = <alias>.<prop>_id) —
  the truth itself, instead of requiring a <prop>_type column beside the
  id. kind-strategy STI and a row's self-discrimination still read locally
  (there is no referenced row to consult). All CASEs are now simple-form,
  so the operand is evaluated once even as a subquery.
- GUC readers guard against the empty string: a rolled-back transaction
  that FIRST-sets a custom GUC leaves it '' session-wide (not unset), and
  COALESCE alone never fires — auth.user_id and punc.external now NULLIF
  first, matching agreego.get_cue's own convention.
- Golden fixtures regenerated via UPDATE_EXPECT; 1286 tests green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 18:21:44 -04:00
10 changed files with 101 additions and 92 deletions

View File

@ -374,7 +374,7 @@ The Queryer transforms Postgres into a pre-compiled Semantic Query Engine, desig
* **Multi-Table Branching**: If the Physical Table is a parent to other tables (e.g. `organization` has variations `["organization", "bot", "person"]`), the compiler generates a dynamic `CASE WHEN type = '...' THEN ...` query, expanding into sub-queries for each variation. To ensure safe resolution, the compiler dynamically evaluates correlation boundaries: it attempts standard Relational Edge discovery first. If no explicit relational edge exists (indicating pure Table Inheritance rather than a standard foreign-key graph relationship), it safely invokes a **Table Parity Fallback**. This generates an explicit ID correlation constraint (`AND inner.id = outer.id`), perfectly binding the structural variations back to the parent row to eliminate Cartesian products.
* **Single-Table Bypass**: If the Physical Table is a leaf node with only one variation (e.g. `person` has variations `["person"]`), the compiler cleanly bypasses `CASE` generation and compiles a simple `SELECT` across the base table, as all schema extensions (e.g. `light.person`, `full.person`) are guaranteed to reside in the exact same physical row.
* **Polymorphic Relation Type Filtering**: When a relationship maps to a polymorphic target with variations, the Queryer compiles an `IN` clause containing all allowed table variations (e.g., `counterparty_type IN ('bot', 'organization', 'person')`) rather than matching the base type literal, ensuring all polymorphic types are loaded correctly.
* **Tenant Scoping & ReBAC Filtering**: When `jspg_query` compiles root-level or relationship-level entity queries, the generated SQL queries evaluate within the calling PostgreSQL transaction's session configuration (e.g. `punc.cue.organization_ids`, `punc.cue.roles`). The compiled queries seamlessly interact with PostgreSQL Row Level Security (RLS) policies on base tables (such as `agreego.entity`) and pre-materialized Zanzibar graph edges (`agreego.relationship`), ensuring multi-tenant isolation and $O(1)$ query evaluation without requiring manual WHERE scoping logic across every application punc.
* **Tenant Scoping & ReBAC Filtering**: When `jspg_query` compiles root-level or relationship-level entity queries, the generated SQL queries evaluate within the calling PostgreSQL transaction's session configuration (e.g. `auth.organization_ids`, `auth.roles`). The compiled queries seamlessly interact with PostgreSQL Row Level Security (RLS) policies on base tables (such as `agreego.entity`) and pre-materialized Zanzibar graph edges (`agreego.relationship`), ensuring multi-tenant isolation and $O(1)$ query evaluation without requiring manual WHERE scoping logic across every application punc.
* **Static Relation Constraints (Kind Constraints)**: When a relationship (such as a nested object or array) is defined with a schema that constrains a field value statically using a `const` or `enum` keyword (for example, `kind` constrained to `"cover"` in a `cover_attachment`), the Queryer automatically extracts these static assertions during AST compilation. It injects them directly as static filters into the SQL subquery's `WHERE` clause (e.g. `AND attachment.kind = 'cover'`), allowing developers to query pre-filtered subsets of related tables natively through the schema.
* **Proxy Schema Dereferencing / Resolution**: To support punc endpoints that return non-polymorphic table-backed shapes (using `type: "full.X"` proxy schemas at the root response level), the Queryer compiler automatically dereferences non-table schema pointers to their target schemas prior to checking the types. This allows the Queryer to correctly resolve the table relationship edges pre-compiled on the full schema, while avoiding polluting the database registry with relations on ad-hoc punc response schemas during setup.

View File

@ -1408,8 +1408,13 @@
" 'archived', entity_19.archived,",
" 'created_at', entity_19.created_at,",
" 'is_primary', contact_21.is_primary,",
" 'target', CASE",
" WHEN relationship_20.target_type = 'phone_number' THEN ((",
" 'target', CASE (",
" SELECT __fam.type",
" FROM agreego.entity __fam",
" WHERE",
" __fam.id = relationship_20.target_id",
" )",
" WHEN 'phone_number' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_22.id,",
" 'type', entity_22.type,",
@ -1423,7 +1428,7 @@
" NOT entity_22.archived",
" AND relationship_20.target_id = entity_22.id",
" ))",
" WHEN relationship_20.target_type = 'email_address' THEN ((",
" WHEN 'email_address' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_24.id,",
" 'type', entity_24.type,",
@ -1437,7 +1442,7 @@
" NOT entity_24.archived",
" AND relationship_20.target_id = entity_24.id",
" ))",
" WHEN relationship_20.target_type = 'address' THEN ((",
" WHEN 'address' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_26.id,",
" 'type', entity_26.type,",
@ -1659,8 +1664,13 @@
" 'archived', entity_19.archived,",
" 'created_at', entity_19.created_at,",
" 'is_primary', contact_21.is_primary,",
" 'target', CASE",
" WHEN relationship_20.target_type = 'phone_number' THEN ((",
" 'target', CASE (",
" SELECT __fam.type",
" FROM agreego.entity __fam",
" WHERE",
" __fam.id = relationship_20.target_id",
" )",
" WHEN 'phone_number' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_22.id,",
" 'type', entity_22.type,",
@ -1674,7 +1684,7 @@
" NOT entity_22.archived",
" AND relationship_20.target_id = entity_22.id",
" ))",
" WHEN relationship_20.target_type = 'email_address' THEN ((",
" WHEN 'email_address' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_24.id,",
" 'type', entity_24.type,",
@ -1688,7 +1698,7 @@
" NOT entity_24.archived",
" AND relationship_20.target_id = entity_24.id",
" ))",
" WHEN relationship_20.target_type = 'address' THEN ((",
" WHEN 'address' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_26.id,",
" 'type', entity_26.type,",
@ -1889,8 +1899,8 @@
"sql": [
[
"((SELECT jsonb_strip_nulls((",
" SELECT COALESCE(jsonb_agg(CASE",
" WHEN organization_2.type = 'bot' THEN ((",
" SELECT COALESCE(jsonb_agg(CASE organization_2.type",
" WHEN 'bot' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_3.id,",
" 'type', entity_3.type,",
@ -1907,7 +1917,7 @@
" NOT entity_3.archived",
" AND entity_3.id = entity_1.id",
" ))",
" WHEN organization_2.type = 'organization' THEN ((",
" WHEN 'organization' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_6.id,",
" 'type', entity_6.type,",
@ -1921,7 +1931,7 @@
" NOT entity_6.archived",
" AND entity_6.id = entity_1.id",
" ))",
" WHEN organization_2.type = 'person' THEN ((",
" WHEN 'person' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_8.id,",
" 'type', entity_8.type,",
@ -1959,8 +1969,8 @@
"sql": [
[
"((SELECT jsonb_strip_nulls((",
" SELECT CASE",
" WHEN organization_2.type = 'bot' THEN ((",
" SELECT CASE organization_2.type",
" WHEN 'bot' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_3.id,",
" 'type', entity_3.type,",
@ -1976,7 +1986,7 @@
" NOT entity_3.archived",
" AND entity_3.id = entity_1.id",
" ))",
" WHEN organization_2.type = 'person' THEN ((",
" WHEN 'person' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_6.id,",
" 'type', entity_6.type,",
@ -2013,8 +2023,8 @@
"sql": [
[
"((SELECT jsonb_strip_nulls((",
" SELECT CASE",
" WHEN organization_2.type = 'person' THEN ((",
" SELECT CASE organization_2.type",
" WHEN 'person' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_3.id,",
" 'type', entity_3.type,",
@ -2121,8 +2131,13 @@
" 'archived', entity_21.archived,",
" 'created_at', entity_21.created_at,",
" 'is_primary', contact_23.is_primary,",
" 'target', CASE",
" WHEN relationship_22.target_type = 'phone_number' THEN ((",
" 'target', CASE (",
" SELECT __fam.type",
" FROM agreego.entity __fam",
" WHERE",
" __fam.id = relationship_22.target_id",
" )",
" WHEN 'phone_number' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_24.id,",
" 'type', entity_24.type,",
@ -2136,7 +2151,7 @@
" NOT entity_24.archived",
" AND relationship_22.target_id = entity_24.id",
" ))",
" WHEN relationship_22.target_type = 'email_address' THEN ((",
" WHEN 'email_address' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_26.id,",
" 'type', entity_26.type,",
@ -2150,7 +2165,7 @@
" NOT entity_26.archived",
" AND relationship_22.target_id = entity_26.id",
" ))",
" WHEN relationship_22.target_type = 'address' THEN ((",
" WHEN 'address' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_28.id,",
" 'type', entity_28.type,",
@ -2246,15 +2261,15 @@
"sql": [
[
"((SELECT jsonb_strip_nulls((",
" SELECT COALESCE(jsonb_agg(CASE",
" WHEN widget_2.kind = 'stock' THEN (jsonb_build_object(",
" SELECT COALESCE(jsonb_agg(CASE widget_2.kind",
" WHEN 'stock' THEN (jsonb_build_object(",
" 'id', entity_1.id,",
" 'type', entity_1.type,",
" 'archived', entity_1.archived,",
" 'created_at', entity_1.created_at,",
" 'kind', widget_2.kind",
" ))",
" WHEN widget_2.kind = 'tasks' THEN (jsonb_build_object(",
" WHEN 'tasks' THEN (jsonb_build_object(",
" 'id', entity_1.id,",
" 'type', entity_1.type,",
" 'archived', entity_1.archived,",
@ -2360,8 +2375,8 @@
" 'total', order_2.total,",
" 'customer_id', order_2.customer_id,",
" 'counterparty', (",
" SELECT CASE",
" WHEN organization_4.type = 'bot' THEN ((",
" SELECT CASE organization_4.type",
" WHEN 'bot' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_5.id,",
" 'type', entity_5.type,",
@ -2378,7 +2393,7 @@
" NOT entity_5.archived",
" AND entity_5.id = entity_3.id",
" ))",
" WHEN organization_4.type = 'organization' THEN ((",
" WHEN 'organization' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_8.id,",
" 'type', entity_8.type,",
@ -2392,7 +2407,7 @@
" NOT entity_8.archived",
" AND entity_8.id = entity_3.id",
" ))",
" WHEN organization_4.type = 'person' THEN ((",
" WHEN 'person' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_10.id,",
" 'type', entity_10.type,",

View File

@ -13,8 +13,7 @@ pub struct MockState {
pub query_responses: Vec<Result<Value, String>>,
pub execute_responses: Vec<Result<(), String>>,
pub mocks: Vec<Value>,
pub cue_created_by: Option<String>,
pub cue_external: bool,
pub punc_external: bool,
}
#[cfg(test)]
@ -25,12 +24,12 @@ impl MockState {
query_responses: Default::default(),
execute_responses: Default::default(),
mocks: Default::default(),
cue_created_by: Some("00000000-0000-0000-0000-000000000000".to_string()),
cue_external: false,
punc_external: false,
}
}
}
#[cfg(test)]
thread_local! {
pub static MOCK_STATE: RefCell<MockState> = RefCell::new(MockState::new());
@ -81,22 +80,16 @@ impl DatabaseExecutor for MockExecutor {
})
}
fn cue_created_by(&self) -> Result<String, String> {
MOCK_STATE.with(|state| {
state
.borrow()
.cue_created_by
.clone()
.ok_or_else(|| "Missing cue.created_by in session context".to_string())
})
fn auth_user_id(&self) -> Result<String, String> {
Ok("00000000-0000-0000-0000-000000000000".to_string())
}
fn timestamp(&self) -> Result<String, String> {
Ok("2026-03-10T00:00:00Z".to_string())
}
fn cue_external(&self) -> Result<bool, String> {
Ok(MOCK_STATE.with(|state| state.borrow().cue_external))
fn punc_external(&self) -> Result<bool, String> {
Ok(MOCK_STATE.with(|state| state.borrow().punc_external))
}
#[cfg(test)]
@ -119,27 +112,21 @@ impl DatabaseExecutor for MockExecutor {
s.query_responses.clear();
s.execute_responses.clear();
s.mocks.clear();
s.cue_created_by = Some("00000000-0000-0000-0000-00000000000".to_string());
s.cue_external = false;
s.punc_external = false;
});
}
}
#[cfg(test)]
impl MockExecutor {
pub fn set_cue_external(&self, external: bool) {
pub fn set_punc_external(&self, external: bool) {
MOCK_STATE.with(|state| {
state.borrow_mut().cue_external = external;
});
}
pub fn set_cue_created_by(&self, created_by: Option<String>) {
MOCK_STATE.with(|state| {
state.borrow_mut().cue_created_by = created_by;
state.borrow_mut().punc_external = external;
});
}
}
#[cfg(test)]
fn parse_and_match_mocks(sql: &str, mocks: &[Value]) -> Option<Vec<Value>> {
let sql_upper = sql.to_uppercase();
@ -168,8 +155,7 @@ fn parse_and_match_mocks(sql: &str, mocks: &[Value]) -> Option<Vec<Value>> {
let q_upper = query.to_uppercase();
// Check if mock type matches the table or any joined tables in this query
let table_regex =
Regex::new(r#"(?i)\s+(?:FROM|JOIN)\s+(?:[a-zA-Z_]\w*\.)?"?([a-zA-Z_]\w*)"?"#).ok()?;
let table_regex = Regex::new(r#"(?i)\s+(?:FROM|JOIN)\s+(?:[a-zA-Z_]\w*\.)?"?([a-zA-Z_]\w*)"?"#).ok()?;
let tables: Vec<String> = table_regex
.captures_iter(query)
.filter_map(|c| c.get(1).map(|m| m.as_str().to_string()))
@ -188,9 +174,7 @@ fn parse_and_match_mocks(sql: &str, mocks: &[Value]) -> Option<Vec<Value>> {
where_end = limit_idx;
}
}
where_clause = query[where_idx + 7..where_end]
.trim_end_matches(')')
.to_string();
where_clause = query[where_idx + 7..where_end].trim_end_matches(')').to_string();
}
if where_clause.is_empty() {

View File

@ -14,14 +14,14 @@ pub trait DatabaseExecutor: Send + Sync {
/// Executes an operation (INSERT, UPDATE, DELETE, or pg_notify) that does not return rows.
fn execute(&self, sql: &str, args: Option<Vec<Value>>) -> Result<(), String>;
/// Returns the current authenticated user's ID (from cue.created_by)
fn cue_created_by(&self) -> Result<String, String>;
/// Returns the current authenticated user's ID
fn auth_user_id(&self) -> Result<String, String>;
/// Returns the current transaction timestamp
fn timestamp(&self) -> Result<String, String>;
/// Returns true if the current execution context is marked as an external client API cue (cue.external = true)
fn cue_external(&self) -> Result<bool, String>;
/// Returns true if the current execution context is marked as an external client API cue (punc.external = true)
fn punc_external(&self) -> Result<bool, String>;
#[cfg(test)]
fn get_queries(&self) -> Vec<String>;

View File

@ -113,12 +113,12 @@ impl DatabaseExecutor for SpiExecutor {
})
}
fn cue_created_by(&self) -> Result<String, String> {
fn auth_user_id(&self) -> Result<String, String> {
self.transact(|| {
Spi::connect(|client| {
let mut tup_table = client
.select(
"SELECT NULLIF(current_setting('punc.cue', true), '')::jsonb->>'created_by'",
"SELECT COALESCE(NULLIF(current_setting('auth.user_id', true), ''), 'ffffffff-ffff-ffff-ffff-ffffffffffff')",
None,
&[],
)
@ -126,10 +126,10 @@ impl DatabaseExecutor for SpiExecutor {
let row = tup_table
.next()
.ok_or("No cue setting returned from context".to_string())?;
.ok_or("No user id setting returned from context".to_string())?;
let user_id: Option<String> = row.get(1).map_err(|e| e.to_string())?;
user_id.ok_or("Missing cue.created_by in session context".to_string())
user_id.ok_or("Missing user_id".to_string())
})
})
}
@ -151,12 +151,12 @@ impl DatabaseExecutor for SpiExecutor {
})
}
fn cue_external(&self) -> Result<bool, String> {
fn punc_external(&self) -> Result<bool, String> {
self.transact(|| {
Spi::connect(|client| {
let mut tup_table = client
.select(
"SELECT COALESCE((NULLIF(current_setting('punc.cue', true), '')::jsonb->>'external')::boolean, false)",
"SELECT COALESCE(NULLIF(current_setting('punc.external', true), ''), 'false')::boolean",
None,
&[],
)
@ -172,3 +172,4 @@ impl DatabaseExecutor for SpiExecutor {
})
}
}

View File

@ -232,9 +232,9 @@ impl Database {
self.executor.execute(sql, args)
}
/// Returns the current authenticated user's ID (from cue.created_by)
pub fn cue_created_by(&self) -> Result<String, String> {
self.executor.cue_created_by()
/// Returns the current authenticated user's ID
pub fn auth_user_id(&self) -> Result<String, String> {
self.executor.auth_user_id()
}
/// Returns the current transaction timestamp
@ -242,11 +242,6 @@ impl Database {
self.executor.timestamp()
}
/// Returns true if the current execution context is marked as an external client API cue (cue.external = true)
pub fn cue_external(&self) -> Result<bool, String> {
self.executor.cue_external()
}
pub fn compile(&mut self, errors: &mut Vec<crate::drop::Error>) {
// Phase 1: Registration
self.collect_schemas(errors);

View File

@ -351,8 +351,8 @@ impl Merger {
current_org_id = parent_org_id.clone();
}
let user_id = self.db.cue_created_by().map_err(|e| Error {
code: "CUE_CREATED_BY_FAILED".to_string(),
let user_id = self.db.auth_user_id().map_err(|e| Error {
code: "AUTH_USER_FAILED".to_string(),
values: Some(IndexMap::from([("error".to_string(), e.clone())])),
details: ErrorDetails {
cause: Some(e),

View File

@ -337,10 +337,25 @@ impl<'a> Compiler<'a> {
.get()
.ok_or("Missing compiled discriminator for polymorphism")?;
let type_col = if let Some(prop) = &node.property_name {
format!("{}_{}", prop, disc)
// The CASE operand that selects the polymorphic branch. For a `type`-strategy
// FAMILY REFERENCE (a property like `payer` or `source` pointing at another
// entity by `<prop>_id`), discriminate through the referenced row's own type
// in agreego.entity — the truth — instead of requiring a local `<prop>_type`
// column on the parent. Local `_type` columns thereby become optional
// denormalization rather than a requirement of the engine. `kind`-strategy
// (single-table STI) and self-discrimination (a row's own `type`) still read
// locally: there is no referenced row to consult.
let disc_operand = if let Some(prop) = &node.property_name {
if disc == "type" {
format!(
"(SELECT __fam.type FROM agreego.entity __fam WHERE __fam.id = {}.{}_id)",
node.parent_alias, prop
)
} else {
format!("{}.{}_{}", node.parent_alias, prop, disc)
}
} else {
disc.to_string()
format!("{}.{}", node.parent_alias, disc)
};
for (disc_val, (idx_opt, target_id_opt)) in options {
@ -369,10 +384,7 @@ impl<'a> Compiler<'a> {
sql
};
case_statements.push(format!(
"WHEN {}.{} = '{}' THEN ({})",
node.parent_alias, type_col, disc_val, val_sql
));
case_statements.push(format!("WHEN '{}' THEN ({})", disc_val, val_sql));
}
} else if let Some(idx) = idx_opt {
if let Some(target_schema) = node
@ -404,10 +416,7 @@ impl<'a> Compiler<'a> {
sql
};
case_statements.push(format!(
"WHEN {}.{} = '{}' THEN ({})",
node.parent_alias, type_col, disc_val, val_sql
));
case_statements.push(format!("WHEN '{}' THEN ({})", disc_val, val_sql));
}
}
}
@ -415,7 +424,12 @@ impl<'a> Compiler<'a> {
return Ok(("NULL".to_string(), "string".to_string()));
}
let sql = format!("CASE {} ELSE NULL END", case_statements.join(" "));
// Simple CASE: the operand is evaluated once even when it is a subquery.
let sql = format!(
"CASE {} {} ELSE NULL END",
disc_operand,
case_statements.join(" ")
);
Ok((sql, "object".to_string()))
}

View File

@ -180,7 +180,7 @@ impl<'a> ValidationContext<'a> {
}
if !self.response {
let is_external = self.db.cue_external().unwrap_or(false);
let is_external = self.db.executor.punc_external().unwrap_or(false);
if let Some(compiled_props) = self.schema.compiled_properties.get() {
for (key, sub_schema) in compiled_props {
if sub_schema.is_immutable(is_external) && obj.contains_key(key) {

View File

@ -1 +1 @@
1.0.199
1.0.198