ProvSQL C/C++ API
Adding support for provenance and uncertainty management to PostgreSQL databases
Loading...
Searching...
No Matches
provsql_utils.h
Go to the documentation of this file.
1/**
2 * @file provsql_utils.h
3 * @brief Core types, constants, and utilities shared across ProvSQL.
4 *
5 * This header is included by virtually every source file in the
6 * extension. It provides:
7 * - The @c gate_type enumeration listing all circuit-gate kinds
8 * recognised by ProvSQL (input, semiring operations, aggregation, etc.)
9 * - The @c constants_t structure caching PostgreSQL OIDs for the types,
10 * functions, and operators that ProvSQL installs, so that OID lookups
11 * happen once per session rather than on every query.
12 * - The @c database_constants_t wrapper for per-database OID caches.
13 * - Helper declarations for OID lookup and UUID manipulation.
14 * - Global flags controlling interrupt handling, where-provenance, and
15 * verbosity.
16 * - An implicit inclusion of @c provsql_error.h for the @c provsql_error
17 * / @c provsql_warning / @c provsql_notice / @c provsql_log macros.
18 */
19#ifndef PROVSQL_UTILS_H
20#define PROVSQL_UTILS_H
21
22#include "pg_config.h" // for PG_VERSION_NUM
23#include "c.h" // for int16
24
25#include "postgres.h"
26#include "utils/uuid.h"
27
28#if PG_VERSION_NUM < 100000
29/// Number of bytes in a UUID
30#define UUID_LEN 16
31
32/** UUID structure. In versions of PostgreSQL < 10, pg_uuid_t is declared
33 * to be an opaque struct pg_uuid_t in uuid.h, so we have to give the
34 * definition of struct pg_uuid_t; this problem is resolved in PostgreSQL 10. */
35struct pg_uuid_t
36{
37 unsigned char data[UUID_LEN]; ///< Raw 16-byte UUID storage
38};
39#endif /* PG_VERSION_NUM */
40
41#include "postgres_ext.h"
42#include "nodes/pg_list.h"
43
44/**
45 * @brief Possible gate types in the provenance circuit.
46 *
47 * @warning ON-DISK ABI: this enum's integer values are stored in the
48 * @c gates.mmap backing file (see @c MMappedCircuit). Reordering,
49 * inserting, or renumbering existing members will silently invalidate
50 * every existing installation's persistent circuit. New gate types
51 * must be appended **at the end**, just before @c gate_invalid. If an
52 * existing gate type ever needs to be removed or renumbered, the mmap
53 * format must gain a version header and a migration path.
54 */
55typedef enum gate_type {
56 gate_input, ///< Input (variable) gate of the circuit
57 gate_plus, ///< Semiring plus
58 gate_times, ///< Semiring times
59 gate_monus, ///< M-Semiring monus
60 gate_project, ///< Project gate (for where provenance)
61 gate_zero, ///< Semiring zero
62 gate_one, ///< Semiring one
63 gate_eq, ///< Equijoin gate (for where provenance)
64 gate_agg, ///< Aggregation operator (for aggregate provenance)
65 gate_semimod, ///< Semimodule scalar multiplication (for aggregate provenance)
66 gate_cmp, ///< Comparison of aggregate values (HAVING-clause provenance)
67 gate_delta, ///< δ-semiring operator (see Amsterdamer, Deutch, Tannen, PODS 2011)
68 gate_value, ///< Scalar value (for aggregate provenance)
69 gate_mulinput, ///< Multivalued input (for Boolean provenance)
70 gate_update, ///< Update operation
71 gate_rv, ///< Continuous random-variable leaf (extra encodes distribution)
72 gate_arith, ///< n-ary arithmetic gate over scalar-valued children (info1 holds operator tag)
73 gate_mixture, ///< Probabilistic mixture: three wires [p_token (gate_input Bernoulli), x_token, y_token]; samples x when p is true, y otherwise
74 gate_assumed, ///< Structural marker over a single child whose sub-circuit was computed under a Boolean-provenance assumption (e.g. the safe-query rewrite); transparent (identity) for Boolean-compatible evaluators, fatal error for the rest, kept as an explicit node in PROV-XML export
75 gate_annotation, ///< Transparent single-child wrapper carrying a query-level annotation in @c extra (inversion-free certificate / per-input order key); identity for EVERY evaluator, and -- unlike the children-only convention -- its UUID folds in @c extra so distinct annotations over the same child are distinct gates.
76 gate_conditioned, ///< Conditioning marker with two children [target, evidence]: measure-only, @c probability_evaluate returns P(target ∧ evidence)/P(evidence) and the RV / agg_token evaluators the restricted distribution; for the uuid carrier a TERMINAL gate (never a semiring child), nested conditioning folding into a conjunction of evidence; refused by every general @c sr_* semiring (normalization is not a semiring operation).
77 gate_mobius, ///< Signed Möbius combination: a MEASURE-only gate carrying one integer coefficient per child (in @c extra, the @c gate_arith precedent), @c probability_evaluate returns Σ_i coeff_i · P(child_i); the one new primitive of the safe-UCQ Möbius-inversion route (see @c MobiusCompiler.h), with certified-independent Boolean islands below it; refused by every general @c sr_* semiring (a signed combination is not a semiring operation).
78 gate_case, ///< N-ary guarded selection over scalar (RV) children: wires are [guard_1, value_1, ..., guard_k, value_k, default] (odd length 2k+1), first-match semantics -- the value of the first guard (a Boolean @c gate_cmp / event) that holds, else the default. Carries data only in its wires (the @c gate_conditioned precedent: no @c info / @c extra). RV/measure-carrier: a real arm in the MC sampler / RangeCheck / Expectation footprint, refused by every general @c sr_* semiring (a guarded selection is not a semiring operation).
79 gate_observe, ///< Latent-variable observation (likelihood-weighting evidence): one wire → an observed bare @c gate_rv leaf, the datum in @c extra. Contributes a continuous density factor (the leaf's pdf at the datum) instead of a Boolean truth value, composing into an evidence circuit by @c gate_times exactly like a conditioning event. Evaluated only by the importance-sampling weight walk (@c Sampler::evalWeight); refused by every Boolean / semiring evaluator (a density factor is not a semiring operation).
80 gate_invalid, ///< Invalid gate type
81 nb_gate_types ///< Total number of gate types
82} gate_type;
83
84/**
85 * @brief Scalar-aggregation flag, stored in the upper bit of a @c gate_agg's
86 * @c info2 (whose low 31 bits hold the aggregate result-type OID).
87 *
88 * Set by the query rewriter when the aggregation has no @c GROUP @c BY (a single
89 * always-present result row). It tells the value-aware evaluators that the
90 * empty-input world is a real possible world (carrying the aggregate's
91 * empty-group value), rather than the "no row" of a grouped query. Result-type
92 * OIDs never use bit 31, so the low 31 bits still recover the type via
93 * @c PROVSQL_AGG_TYPE_MASK.
94 *
95 * @warning The flag is folded into the gate's content UUID (see
96 * @c provenance_aggregate), so a scalar and a grouped aggregate over identical
97 * children stay distinct gates and their @c set_infos calls do not clobber.
98 */
99#define PROVSQL_AGG_SCALAR_FLAG 0x80000000u
100#define PROVSQL_AGG_TYPE_MASK 0x7FFFFFFFu
101
102/**
103 * @brief Arithmetic operator tags used by @c gate_arith.
104 *
105 * Stored in the gate's @c info1 field. Local enum (not a PostgreSQL
106 * operator OID) because arithmetic in the sampler / evaluator is just
107 * C++ doubles, with no need to dispatch through the PG catalog.
108 *
109 * @warning ON-DISK ABI: like @c gate_type, these integer values are
110 * persisted (in @c info1). Reordering or renumbering existing tags
111 * will silently invalidate every existing installation's persistent
112 * circuit. New tags must be appended at the end.
113 */
114typedef enum provsql_arith_op {
115 PROVSQL_ARITH_PLUS = 0, ///< n-ary, sum of children
116 PROVSQL_ARITH_TIMES = 1, ///< n-ary, product of children
117 PROVSQL_ARITH_MINUS = 2, ///< binary, child0 - child1
118 PROVSQL_ARITH_DIV = 3, ///< binary, child0 / child1
119 PROVSQL_ARITH_NEG = 4, ///< unary, -child0
120 PROVSQL_ARITH_MAX = 5, ///< n-ary, max of children (order statistic; greatest / max aggregate)
121 PROVSQL_ARITH_MIN = 6, ///< n-ary, min of children (order statistic; least / min aggregate)
122 PROVSQL_ARITH_POW = 7, ///< binary, child0 ^ child1 (real branch only:
123 ///< a negative base drawn with a non-integer
124 ///< exponent raises at evaluation)
125 PROVSQL_ARITH_LN = 8, ///< unary, natural logarithm of child0
126 ///< (a negative draw raises at evaluation)
127 PROVSQL_ARITH_EXP = 9, ///< unary, e^child0
128 PROVSQL_ARITH_PERCENTILE = 10 ///< continuous percentile (order-statistic
129 ///< aggregate): wires are interleaved
130 ///< [ind_1, x_1, ..., ind_n, x_n] (even
131 ///< count) where ind_i is the row's 0/1
132 ///< presence indicator; the fraction is
133 ///< text-encoded in @c extra. Per draw:
134 ///< the values whose indicator draws 1 are
135 ///< sorted and linearly interpolated at the
136 ///< fraction (SQL @c percentile_cont); an
137 ///< empty draw is NaN (undefined world).
139
140/**
141 * @brief Tags identifying the planner-time route that produced a circuit.
142 *
143 * Three rewrites replace a query's ordinary lineage with a circuit of their
144 * own -- the safe-query (read-once) rewriter, the joint-width UCQ compiler and
145 * the recursive-reachability compiler -- and all three then hand that circuit
146 * to the ordinary probability dispatcher, which evaluates it by an independent
147 * / certified-island sweep. Without a tag the three are indistinguishable at
148 * evaluation time and all report @c independent. Each route therefore stamps
149 * its tag on the root gate it produces, and @c probability_evaluate.cpp turns
150 * that into a first-class method name (@c sq-rewrite / @c bounded-jw /
151 * @c reachability) for @c provsql.last_eval_method and for @c byName dispatch.
152 *
153 * Where the tag lives depends on what the route's root already carries:
154 * @c PROVSQL_ROUTE_SQ_REWRITE and @c PROVSQL_ROUTE_REACHABILITY go in @c info1
155 * of the @c gate_assumed wrapper the route puts on its root (the assumption
156 * kind in @c extra -- 'boolean' / 'absorptive' -- does not identify the route:
157 * both are also reachable through the public @c provenance_assume), while
158 * @c PROVSQL_ROUTE_BOUNDED_JW goes in @c info2 of the materialised d-D root,
159 * whose @c info1 is already @c DNNF_CERT_INFO.
160 *
161 * @warning ON-DISK ABI: like @c gate_type and @c provsql_arith_op, these
162 * integer values are persisted (in @c info1 / @c info2). Reordering or
163 * renumbering existing tags will silently mislabel every existing
164 * installation's persistent circuit. New tags must be appended at the end.
165 */
166typedef enum provsql_route {
167 PROVSQL_ROUTE_NONE = 0, ///< No route rewrite: ordinary lineage
168 PROVSQL_ROUTE_SQ_REWRITE = 1, ///< Hierarchical-CQ read-once rewrite (@c src/safe_query.c)
169 PROVSQL_ROUTE_BOUNDED_JW = 2, ///< Joint-width UCQ compiler (@c src/UCQJointCompiler.h)
170 PROVSQL_ROUTE_REACHABILITY = 3 ///< Recursive-reachability compiler (@c src/reachability_evaluate.cpp)
172
173/** Names of gate types */
174extern const char *gate_type_name[];
175
176/**
177 * @brief Canonical name of the per-row provenance column installed by
178 * @c add_provenance / @c repair_key.
179 *
180 * Centralised so the planner-hook entry points (@c src/provsql.c) and
181 * the safe-query detector (@c src/safe_query.c) agree on the literal;
182 * see the @c provenance_guard trigger in @c sql/provsql.common.sql.
183 */
184#define PROVSQL_COLUMN_NAME "provsql"
185
186/** Structure to store the value of various constants. This is needed to
187 * uniquely identify types, functions, etc., in PostgreSQL through their
188 * Object Identifier Types (OIDs). */
189typedef struct constants_t {
190 Oid OID_SCHEMA_PROVSQL; ///< OID of the provsql SCHEMA
191 Oid OID_TYPE_GATE_TYPE; ///< OID of the provenance_gate TYPE
192 Oid OID_TYPE_AGG_TOKEN; ///< OID of the agg_token TYPE
193 Oid OID_TYPE_UUID; ///< OID of the uuid TYPE
194 Oid OID_TYPE_UUID_ARRAY; ///< OID of the uuid[] TYPE
195 Oid OID_TYPE_BOOL; ///< OID of the BOOL TYPE
196 Oid OID_TYPE_INT; ///< OID of the INT TYPE
197 Oid OID_TYPE_INT_ARRAY; ///< OID of the INT[] TYPE
198 Oid OID_TYPE_FLOAT; ///< OID of the FLOAT TYPE
199 Oid OID_TYPE_VARCHAR; ///< OID of the VARCHAR TYPE
200 Oid OID_TYPE_TSTZMULTIRANGE; ///< OID of the tstzmultirange TYPE (PG14+, InvalidOid otherwise)
201 Oid OID_TYPE_NUMMULTIRANGE; ///< OID of the nummultirange TYPE (PG14+, InvalidOid otherwise)
202 Oid OID_TYPE_INT4MULTIRANGE; ///< OID of the int4multirange TYPE (PG14+, InvalidOid otherwise)
203 Oid OID_FUNCTION_ARRAY_AGG; ///< OID of the array_agg FUNCTION
204 Oid OID_FUNCTION_PROVENANCE_PLUS; ///< OID of the provenance_plus FUNCTION
205 Oid OID_FUNCTION_PROVENANCE_TIMES; ///< OID of the provenance_times FUNCTION
206 Oid OID_FUNCTION_PROVENANCE_MONUS; ///< OID of the provenance_monus FUNCTION
207 Oid OID_FUNCTION_PROVENANCE_PROJECT; ///< OID of the provenance_project FUNCTION
208 Oid OID_FUNCTION_PROVENANCE_EQ;///< OID of the provenance_eq FUNCTION
209 Oid OID_FUNCTION_PROVENANCE_CMP; ///< OID of the provenance_cmp FUNCTION
210 Oid OID_FUNCTION_PROVENANCE; ///< OID of the provenance FUNCTION
211 Oid GATE_TYPE_TO_OID[nb_gate_types]; ///< Array of the OID of each provenance_gate ENUM value
212 Oid OID_FUNCTION_PROVENANCE_DELTA; ///< OID of the provenance_delta FUNCTION
213 Oid OID_FUNCTION_PROVENANCE_CMP_TIMES; ///< OID of the provenance_cmp_times FUNCTION
214 Oid OID_FUNCTION_PROVENANCE_AGGREGATE; ///< OID of the provenance_aggregate FUNCTION
215 Oid OID_FUNCTION_PROVENANCE_SEMIMOD; ///< OID of the provenance_semimod FUNCTION
216 Oid OID_FUNCTION_GATE_ZERO; ///< OID of the provenance_zero FUNCTION
217 Oid OID_FUNCTION_GATE_ONE; ///< OID of the provenance_one FUNCTION
218 Oid OID_OPERATOR_NOT_EQUAL_UUID; ///< OID of the <> operator on UUIDs FUNCTION
219 Oid OID_FUNCTION_NOT_EQUAL_UUID; ///< OID of the = operator on UUIDs FUNCTION
220 Oid OID_FUNCTION_AGG_TOKEN_UUID; ///< OID of the agg_token_uuid FUNCTION
221 Oid OID_FUNCTION_AGG_VALUE_GATE; ///< agg_value_gate(numeric) -> uuid
222 Oid OID_FUNCTION_GET_CHILDREN; ///< OID of the get_children FUNCTION
223 Oid OID_FUNCTION_GET_EXTRA; ///< OID of the get_extra FUNCTION
224 Oid OID_UNNEST; ///< OID of the unnest(anyarray) FUNCTION
225 Oid OID_TYPE_RANDOM_VARIABLE; ///< OID of the random_variable TYPE
226 Oid OID_TYPE_RANDOM_VARIABLE_ARRAY; ///< OID of the random_variable[] TYPE
227 /** @name Order-statistic constructors the planner lifts a builtin
228 * @c GREATEST / @c LEAST over @c random_variable arguments into. */
229 /**@{*/
230 Oid OID_FUNCTION_RV_GREATEST; ///< provsql.greatest(VARIADIC random_variable[])
231 Oid OID_FUNCTION_RV_LEAST; ///< provsql.least(VARIADIC random_variable[])
232 /**@}*/
233 Oid OID_FUNCTION_RV_AGGREGATE_SEMIMOD; ///< OID of rv_aggregate_semimod(uuid, rv) -> rv: wraps a per-row argument as mixture(prov, rv, as_random(0)) (identity 0, for sum / avg-numerator)
234 Oid OID_FUNCTION_RV_AGGREGATE_SEMIMOD_ID; ///< OID of the 3-arg rv_aggregate_semimod(uuid, rv, float8): identity-parameterised wrap mixture(prov, rv, as_random(identity)) for product / max / min
235 Oid OID_FUNCTION_RV_AGGREGATE_INDICATOR; ///< OID of rv_aggregate_indicator(uuid) -> rv: the avg denominator wrap mixture(prov, 1, 0)
236 Oid OID_FUNCTION_RV_AGGREGATE_INDICATOR_VALUED; ///< OID of rv_aggregate_indicator(uuid, rv) -> rv: NULL when the row's value is NULL (SQL NULL-skip for avg's count)
237 Oid OID_FUNCTION_RV_DIV; ///< OID of random_variable_div(rv, rv) -> rv: builds the avg num/denom division gate
238 /** @brief OIDs of the RV-returning aggregates, keyed for the per-aggregate
239 * identity dispatch in @c make_rv_aggregate_expression (product / max /
240 * min bake their identity into the wrap; avg rewrites to sum/sum). */
241 /**@{*/
242 Oid OID_AGG_SUM_RV; ///< provsql.sum(random_variable)
243 Oid OID_AGG_PRODUCT_RV; ///< provsql.product(random_variable)
244 Oid OID_AGG_AVG_RV; ///< provsql.avg(random_variable)
245 Oid OID_AGG_MAX_RV; ///< provsql.max(random_variable)
246 Oid OID_AGG_MIN_RV; ///< provsql.min(random_variable)
247 Oid OID_AGG_RV_SUM_OR_NULL; ///< provsql.rv_sum_or_null(random_variable): the avg-numerator sum, NULL on an empty group (so avg is NULL for an empty group after STRICT division)
248 /**@}*/
249 /** @brief SQL-standard statistic aggregates over @c random_variable rows
250 * and their internal indicator-carrying rewrite targets.
251 *
252 * The public forms wrap every row with the certain indicator
253 * @c as_random(1); a provenance-tracked query is rewritten by
254 * @c make_rv_aggregate_expression to the @c _impl form whose extra
255 * leading argument is the row's provenance indicator
256 * @c rv_aggregate_indicator(prov), so absent rows drop out of the
257 * statistic (count, sums, and the percentile's member set alike). */
258 /**@{*/
259 Oid OID_AGG_COVAR_POP_RV; ///< provsql.covar_pop(rv, rv)
260 Oid OID_AGG_COVAR_SAMP_RV; ///< provsql.covar_samp(rv, rv)
261 Oid OID_AGG_CORR_RV; ///< provsql.corr(rv, rv)
262 Oid OID_AGG_STDDEV_POP_RV; ///< provsql.stddev_pop(rv)
263 Oid OID_AGG_STDDEV_SAMP_RV; ///< provsql.stddev_samp(rv)
264 Oid OID_AGG_PERCENTILE_CONT_RV; ///< provsql.percentile_cont(float8) WITHIN GROUP (ORDER BY rv)
265 Oid OID_AGG_RV_COVAR_POP_IMPL; ///< provsql.rv_covar_pop_impl(ind rv, x rv, y rv)
266 Oid OID_AGG_RV_COVAR_SAMP_IMPL; ///< provsql.rv_covar_samp_impl(ind rv, x rv, y rv)
267 Oid OID_AGG_RV_CORR_IMPL; ///< provsql.rv_corr_impl(ind rv, x rv, y rv)
268 Oid OID_AGG_RV_STDDEV_POP_IMPL; ///< provsql.rv_stddev_pop_impl(ind rv, x rv)
269 Oid OID_AGG_RV_STDDEV_SAMP_IMPL; ///< provsql.rv_stddev_samp_impl(ind rv, x rv)
270 Oid OID_AGG_RV_PERCENTILE_IMPL; ///< provsql.rv_percentile_impl(fraction float8, ind rv, x rv)
271 /**@}*/
272 Oid OID_FUNCTION_CHOOSE; ///< OID of the choose(anyelement) aggregate (keeps the first non-NULL value); used to decorrelate scalar subqueries into a LEFT JOIN + GROUP BY
273 /** @brief OID of @c provsql.assume_boolean(uuid)->uuid.
274 *
275 * Installed by the @c 1.5.0--1.6.0 upgrade script. Wraps its child
276 * in a fresh @c gate_assumed and returns the wrapper's UUID.
277 * When @c InvalidOid the safe-query rewriter (and any other
278 * Boolean-only rewrite that needs the marker) is effectively
279 * disabled even if @c provsql.boolean_provenance is on: the
280 * rewriter refuses to produce unmarked roots on a schema that
281 * cannot enforce the semiring-compatibility check. */
283 /** @brief OID of @c provsql.annotate(uuid,text)->uuid.
284 *
285 * Wraps its child in a fresh transparent @c gate_annotation whose UUID
286 * folds in the @c extra text, and returns the wrapper's UUID. Used to
287 * attach the inversion-free tractability certificate (on the root) and the
288 * per-input order keys. @c InvalidOid on a schema predating the gate
289 * (the inversion-free carrier is then disabled). */
291 /** @brief OID of @c provsql.inversion_free_key(text,text,int)->text.
292 *
293 * Builds the @c K-prefixed per-input order-key string the planner attaches
294 * (via @c annotate) to each certified atom's provenance on the
295 * inversion-free path. @c InvalidOid on a schema predating it (markers are
296 * then not attached; the path declines and falls back). */
298 /** OIDs of the @c random_variable_{eq,ne,le,lt,ge,gt} comparison
299 * procedure functions, indexed by the @c ComparisonOperator enum
300 * (@c EQ=0, @c NE=1, @c LE=2, @c LT=3, @c GE=4, @c GT=5; matches the
301 * order in @c src/Aggregation.h). Used by the planner hook to detect
302 * RV-comparison @c OpExpr nodes in WHERE clauses. */
304 /** @brief OID of @c provsql.cond(uuid,uuid)->uuid.
305 *
306 * Builds the terminal @c gate_conditioned (value-level conditioning, the
307 * binary @c | operator). The rewriter wraps a row's output provenance in
308 * it when a @c given(...) marker is present. @c InvalidOid on a schema
309 * predating the conditioning feature (the @c given rewrite is then
310 * disabled). */
312 /** @brief OID of @c provsql.given(uuid)->uuid.
313 *
314 * The whole-tuple output-conditioning marker: a consumed select-list term
315 * the rewriter strips from the visible projection, conditioning each output
316 * row's provenance on the marker's argument. @c InvalidOid on a schema
317 * predating the feature. */
319 /** @brief OID of @c provsql.random_variable_cond(random_variable,uuid).
320 * The real conditioning constructor the planner emits when rewriting the
321 * @c "X | (predicate)" placeholder. @c InvalidOid disables the rewrite. */
323 /** @brief OID of @c provsql.agg_token_cond(agg_token,uuid): the conditioning
324 * constructor for the @c agg_token carrier the planner emits when rewriting
325 * the @c "SUM(x) | (predicate)" placeholder. */
327 /** @name @c "X | (predicate)" placeholder OIDs (carrier-parametric).
328 * Each is a no-op placeholder operator whose right operand is a Boolean
329 * combination of random_variable / agg_token comparisons; the planner
330 * converts that predicate into a condition gate and emits the matching
331 * conditioning constructor. @c InvalidOid disables the rewrite. */
332 /**@{*/
333 Oid OID_FUNCTION_COND_PREDICATE; ///< cond_predicate(uuid,boolean)
334 Oid OID_FUNCTION_RV_COND_PREDICATE; ///< random_variable_cond_predicate(random_variable,boolean)
335 Oid OID_FUNCTION_AGG_COND_PREDICATE; ///< agg_token_cond_predicate(agg_token,boolean)
336 Oid OID_FUNCTION_PREDICATE_COND_PREDICATE; ///< predicate_cond_predicate(boolean,boolean) -- (A)|(B), both events
337 Oid OID_FUNCTION_GIVEN_PREDICATE; ///< given_predicate(boolean) -- prefix whole-tuple
338 /**@}*/
339 /** @brief OID of @c provsql.regular_indicator(boolean): the deterministic
340 * @c gate_one/@c gate_zero indicator the planner emits for an ordinary
341 * (regular-type) comparison appearing inside a mixed conditioning
342 * predicate. */
344 /** @brief OID of the real @c provsql.probability_evaluate(uuid,text,text).
345 * The target of the @c probability(<predicate>) rewrite: the planner emits
346 * a call to it over the event token built from the Boolean argument. */
348 /** @brief OID of the @c probability(boolean,text,text) placeholder.
349 * When its argument carries a probabilistic (random_variable / aggregate)
350 * comparison the planner rewrites the whole call into
351 * @c probability_evaluate over the argument's event token; a purely
352 * deterministic argument is left to the SQL body (which returns @c 1/0).
353 * The predicate surface is only on @c probability, not
354 * @c probability_evaluate, to avoid an unknown-literal overload ambiguity
355 * (see @c sql/provsql.common.sql). @c InvalidOid disables the rewrite. */
357 /** @brief OID of @c provsql.rv_case(uuid[])->random_variable.
358 * Builds a @c gate_case from the flattened
359 * @c [guard_1, value_1, ..., default] wire list the planner emits for an
360 * RV-typed @c CASE expression. @c InvalidOid on a schema predating
361 * @c gate_case (the @c CASE-over-RV rewrite is then disabled). */
363 /** @brief OID of @c agg_case(uuid[]), the @c agg_token constructor the
364 * planner hook lowers an aggregate-carrier @c CASE into. @c InvalidOid on
365 * a schema predating it (the rewrite is then disabled). */
367 bool ok; ///< true if constants were loaded
369
370
371
372
373/** Structure to store the value of various constants for a specific
374 * database. */
375typedef struct database_constants_t {
376 Oid database; ///< OID of the database these constants belong to
377 constants_t constants; ///< Cached OID constants for this database
379
380/**
381 * @brief Retrieve the cached OID constants for the current database.
382 *
383 * On first call (or after a cache miss) this function looks up the OIDs
384 * of all ProvSQL-specific types, functions, and operators in the system
385 * catalogs and stores them in a per-database cache. Subsequent calls
386 * return the cached values without touching the catalogs.
387 *
388 * @param failure_if_not_possible If @c true, call @c provsql_error when
389 * the ProvSQL schema cannot be found (e.g. the extension is not
390 * installed in the current database). If @c false, return a
391 * constants_t with @c ok==false instead of aborting.
392 * @return A @c constants_t whose @c ok field is @c true on success.
393 */
394constants_t get_constants(bool failure_if_not_possible);
395
396/**
397 * @brief Find the equality operator OID for two given types.
398 *
399 * Searches @c pg_operator for the @c = operator that accepts
400 * @p ltypeId on the left and @p rtypeId on the right.
401 *
402 * @param ltypeId OID of the left operand type.
403 * @param rtypeId OID of the right operand type.
404 * @return The operator OID, or @c InvalidOid if none is found.
405 */
406Oid find_equality_operator(Oid ltypeId, Oid rtypeId);
407
408/** Global variable that becomes true if this particular backend received
409 * an interrupt signal. */
410extern bool provsql_interrupted;
411
412/** Global variable that indicates if where-provenance support has been
413 * activated through the provsql.where_provenance run-time configuration
414 * parameter. */
415extern bool provsql_where_provenance;
416
417/** Global variable that indicates the verbosity level set by the
418 * provsql.verbose_level run-time configuration parameter was set */
419extern int provsql_verbose;
420
421/** Global variable holding the probability evaluation method(s) used by the
422 * most recent probability_evaluate call, exposed via the
423 * provsql.last_eval_method run-time configuration parameter. */
424extern char *provsql_last_eval_method;
425
426/** Global flag controlling agg_token text output: when true,
427 * agg_token_out emits the underlying provenance UUID instead of the
428 * default "value (*)" display string. Driven by the
429 * provsql.aggtoken_text_as_uuid GUC. */
431
432/** Colon-separated list of directories prepended to PATH when ProvSQL
433 * spawns external tools (d4, c2d, minic2d, dsharp, weightmc, graph-easy),
434 * set by the provsql.tool_search_path run-time configuration parameter.
435 * NULL or empty means rely on the server's PATH alone. */
436extern char *provsql_tool_search_path;
437
438/** Compiler invoked as the final fallback in BooleanCircuit::makeDD when
439 * both interpretAsDD() and the in-process tree-decomposition path fail
440 * (the latter typically on treewidth blow-up). Defaults to "d4"; set by
441 * the provsql.fallback_compiler run-time configuration parameter to any
442 * compiler accepted by BooleanCircuit::compilation (d4 / d4v2 / c2d /
443 * minic2d / dsharp / panini-*). */
444extern char *provsql_fallback_compiler;
445
446/** Launch command for the managed KCMCP knowledge-compiler server, set by
447 * the provsql.kcmcp_server run-time configuration parameter (PGC_SIGHUP).
448 * The literal substring "{endpoint}" is replaced by the Unix-socket path the
449 * supervisor background worker chooses, e.g. "tdkc --kcmcp unix:{endpoint}".
450 * NULL or empty means no managed server is launched. */
451extern char *provsql_kcmcp_server;
452
453/** Read the live endpoint of the managed KCMCP server from shared memory
454 * (e.g. "unix:/tmp/..."), or an empty string when none is running. */
455const char *provsql_kcmcp_managed_endpoint(void);
456
457/** Register the supervisor background worker that launches and supervises the
458 * managed KCMCP server; called from _PG_init alongside the mmap worker. */
460
461/** Seed for the Monte Carlo sampler, set by the provsql.monte_carlo_seed
462 * run-time configuration parameter. -1 (default) means seed from
463 * std::random_device for non-deterministic sampling; any other value
464 * (including 0) is a literal seed for std::mt19937_64. Used by both
465 * the Bernoulli path (BooleanCircuit::monteCarlo) and the continuous
466 * path (gate_rv sampling), so a single GUC controls reproducibility
467 * end-to-end. */
468extern int provsql_monte_carlo_seed;
469
470/** Default sample count for Monte Carlo fallbacks when an analytical
471 * evaluator (Expectation, future hybrid evaluator, ...) cannot
472 * decompose a sub-circuit structurally. Unlike
473 * @c probability_evaluate(token, 'monte-carlo', n) where the sample
474 * count is an explicit argument, these implicit MC paths have no
475 * natural place to take @c n from.
476 *
477 * Set by the @c provsql.rv_mc_samples run-time configuration
478 * parameter; default 10000. Setting it to 0 disables the implicit
479 * MC fallback entirely: callers must then raise an exception rather
480 * than sampling. Useful for callers that want to guarantee
481 * analytical-only evaluation. */
482extern int provsql_rv_mc_samples;
483
484/* Effective-sample-size warning threshold for likelihood-weighting posterior
485 * inference (@c provsql.ess_warn_fraction; default 0.1). A readout over
486 * @c gate_observe evidence warns when the posterior ESS falls below this
487 * fraction of the accepted draws (the weights are degenerating). 0 silences
488 * the warning. */
489extern double provsql_ess_warn_fraction;
490
491/* Debug/safety hard cap on d-tree subproblems before the method bails to the
492 * next (0 = off). The chooser auto-budgets the d-tree at the next-best
493 * method's estimated cost regardless; this imposes an extra fixed cap. */
495
496/* Joint-width UCQ compiler (see UCQJointCompiler.h): the maximum joint
497 * treewidth attempted before the path declines (the SQL layer then falls
498 * back to the standard ladder). Default = TreeDecomposition::MAX_TREEWIDTH
499 * (10). */
501
502/* Joint-width UCQ compiler: the per-bag DP state-count cap, the true safety
503 * net (the static enumerating-variable count is only a predictor). Default
504 * 1<<16. */
505extern int provsql_joint_max_states;
506
507/* Recognise unsafe UCQs at planner time and route their existence provenance
508 * through the joint-width compiler (on by default); provsql.joint_width is a
509 * debug-only switch to disable it. */
510extern bool provsql_joint_width;
511
512/* Try the safe-UCQ Möbius-inversion route before the joint-width compiler,
513 * short-circuiting on success (on by default); provsql.mobius is a debug-only
514 * switch to disable it. */
515extern bool provsql_mobius;
516
517/* Data-cost cap of the Möbius route: it declines once its compile has built
518 * more than this many gates; provsql.mobius_max_gates GUC. */
519extern int provsql_mobius_max_gates;
520
521/* Query-cost cap of the Möbius route: it declines when the CNF of a sentence
522 * has more than this many conjuncts (the inclusion-exclusion lattice it walks
523 * has 2^M elements); provsql.mobius_max_cnf GUC. */
524extern int provsql_mobius_max_cnf;
525
526/** @brief When @c true (default), every @c GenericCircuit returned by
527 * @c getGenericCircuit is run through the universal cmp-resolution
528 * passes (RangeCheck for now, plus any future passes that decide
529 * comparators to certain Boolean values). Decisions become Bernoulli
530 * @c gate_input gates with probability 0 or 1, transparent to every
531 * downstream consumer (semiring evaluators, MC, view_circuit, PROV
532 * export, etc.). Set @c provsql.simplify_on_load to @c off when
533 * inspecting a circuit's raw structure (e.g. debugging gate-creation
534 * code paths). */
535extern bool provsql_simplify_on_load;
536
537/** @brief Run the hybrid evaluator (simplifier + per-cmp island
538 * decomposer) before dispatching a probability_evaluate query.
539 *
540 * Debug-only GUC, hidden from @c SHOW @c ALL and from
541 * @c postgresql.conf.sample (registered with
542 * @c GUC_NO_SHOW_ALL @c | @c GUC_NOT_IN_SAMPLE). When on (default),
543 * @c probability_evaluate runs the @c HybridEvaluator simplifier
544 * between @c RangeCheck and @c AnalyticEvaluator and the per-cmp
545 * MC island decomposer after @c AnalyticEvaluator: @c gate_arith
546 * subtrees are constant-folded and family-closed (normals, Erlang),
547 * and residual continuous-island comparators are MC-marginalised
548 * into Bernoulli @c gate_input leaves so the surrounding circuit
549 * becomes purely Boolean.
550 *
551 * Set to @c off to bypass both passes: undecidable comparators
552 * then fall through to whole-circuit MC (for the @c monte-carlo
553 * method) or raise (for @c independent / @c tree-decomposition).
554 * End users have no reason to flip this -- on is strictly better
555 * for them. Exists for developer A/B testing of the analytic
556 * path against the raw MC path and as a bisection knob if a
557 * closure rule turns out to be unsound on some workload. */
558extern bool provsql_hybrid_evaluation;
559
560/** @brief Hidden diagnostic flag for the family of closed-form /
561 * analytic probability evaluators that resolve @c gate_cmps inside
562 * @c probability_evaluate ; see the
563 * @c provsql.cmp_probability_evaluation GUC.
564 *
565 * When on (default), @c probability_evaluate runs pre-passes that
566 * recognise specific @c gate_cmp shapes and replace each cmp with
567 * a Bernoulli @c gate_input carrying the closed-form probability,
568 * bypassing the DNF that @c provsql_having's
569 * @c enumerate_valid_worlds would otherwise emit. The first
570 * implementation in this family is the Poisson-binomial pre-pass
571 * for HAVING @c COUNT(*) @c op @c C over distinct @c gate_input
572 * leaves (see @c CountCmpEvaluator.h) ; future MIN / MAX / SUM
573 * evaluators will gate on the same flag. Off forces every cmp to
574 * fall through to the enumeration path. End users have no reason
575 * to flip this ; exists for developer A/B testing and as a
576 * bisection escape valve. */
578
579/** @brief Kill-switch for the inversion-free structured-d-DNNF probability
580 * path; see the @c provsql.inversion_free GUC.
581 *
582 * When on (default), @c probability_evaluate, on a query carrying an
583 * inversion-free tractability certificate, tries the structured-d-DNNF
584 * builder after @c independentEvaluation and before tree-decomposition / d4.
585 * Off disables only that automatic insertion (for A/B testing); the explicit
586 * @c probability_evaluate(token,'inversion-free') method ignores this flag.
587 * The path is self-gating on the certificate, which is attached only to
588 * certified queries, so leaving it on is safe. */
589extern bool provsql_inversion_free;
590
591/** @brief Opt-in safe-query optimisation for hierarchical conjunctive
592 * queries; see the @c provsql.boolean_provenance GUC.
593 *
594 * When @c true, the planner is permitted to rewrite self-join-free
595 * hierarchical CQs (and independent UCQs) over TID / BID tables to
596 * a read-once form whose probability is computable in linear time.
597 * The rewriter tags the resulting root gate so that semiring
598 * evaluations incompatible with this rewrite refuse to run on the
599 * produced circuit. */
601
602/** @brief Derived flag of the @c provsql.provenance GUC: the session's
603 * provenance class is 'absorptive' or 'boolean', licensing
604 * constructions sound for absorptive semirings only (cyclic recursion
605 * stopped at the absorptive value fixpoint, tagged tokens). */
607
608#include "MMappedTableInfo.h"
609
610/**
611 * @brief Look up per-table provenance metadata with a backend-local cache.
612 *
613 * Resolves to a cached value when the relation's relcache entry has
614 * not been invalidated since the last fetch; otherwise issues one
615 * @c 's' IPC to the background worker. The cache is invalidated
616 * via @c CacheRegisterRelcacheCallback, so concurrent
617 * @c add_provenance / @c repair_key / @c remove_provenance in other
618 * backends are reflected here without polling.
619 *
620 * Safe to call from the planner hot path.
621 *
622 * @param relid pg_class OID of the relation to look up.
623 * @param out On @c true return, filled with the stored record.
624 * @return @c true if a record exists for @p relid, @c false otherwise.
625 */
626extern bool provsql_lookup_table_info(Oid relid, ProvenanceTableInfo *out);
627
628/**
629 * @brief Raw IPC fetch (no cache).
630 *
631 * Implementation detail of @c provsql_lookup_table_info, exposed only
632 * so the cache layer in @c provsql_utils.c can reach it. Callers in
633 * the planner hot path should go through @c provsql_lookup_table_info.
634 */
635extern bool provsql_fetch_table_info(Oid relid, ProvenanceTableInfo *out);
636
637/**
638 * @brief Look up the base-ancestor set of a tracked relation.
639 *
640 * Per-backend cached over IPC. Returns the ancestor set when
641 * @p relid is tracked and the registry has a non-empty entry for it.
642 * @c false either when @p relid has no metadata record at all (the
643 * relation was never run through @c add_provenance / @c repair_key)
644 * or when the record exists but @c ancestor_n @c == @c 0 (the CTAS
645 * hook hasn't populated the lineage yet, or the registry was
646 * explicitly cleared). The two failure modes share the false
647 * return because both make the safe-query rewriter take the
648 * conservative refuse path -- there is no use case for treating
649 * them differently.
650 *
651 * Backed by the same per-backend cache as
652 * @c provsql_lookup_table_info and invalidated through the same
653 * relcache-invalidation callback, so concurrent
654 * @c set_ancestors / @c add_provenance / @c repair_key calls in
655 * other backends are reflected here without polling.
656 *
657 * @param relid pg_class OID of the relation to look up.
658 * @param ancestor_n_out On @c true return, count of valid entries
659 * in @p ancestors_out.
660 * @param ancestors_out On @c true return, the sorted-deduplicated
661 * ancestor OIDs (caller-allocated buffer of
662 * @c PROVSQL_TABLE_INFO_MAX_ANCESTORS @c Oid).
663 * @return @c true on a non-empty ancestor set; @c false otherwise.
664 */
665extern bool provsql_lookup_ancestry(Oid relid,
666 uint16 *ancestor_n_out,
667 Oid *ancestors_out);
668
669/**
670 * @brief Raw IPC fetch for the ancestry half (no cache).
671 *
672 * Implementation detail of @c provsql_lookup_ancestry, exposed so
673 * the cache layer in @c provsql_utils.c can reach it. Callers in
674 * the planner hot path should go through @c provsql_lookup_ancestry.
675 */
676extern bool provsql_fetch_ancestry(Oid relid,
677 uint16 *ancestor_n_out,
678 Oid *ancestors_out);
679
680/**
681 * @brief Upper bounds for the relation-key cache.
682 *
683 * Each relation contributes at most @c PROVSQL_KEY_CACHE_MAX_KEYS
684 * distinct PRIMARY-KEY / NOT-NULL-UNIQUE column-sets, each over at
685 * most @c PROVSQL_KEY_CACHE_MAX_KEY_COLS columns. These bounds keep
686 * the cache entry fixed-size (so the backend-local sorted-array
687 * representation can reuse the @c provsql_lookup_table_info pattern
688 * verbatim); relations with more or wider keys silently drop the
689 * overflow, treating the missing keys as if they did not exist
690 * (over-conservative -- the §2 FD-aware detector simply misses an
691 * optimisation, never produces an unsound rewrite).
692 */
693#define PROVSQL_KEY_CACHE_MAX_KEYS 4
694#define PROVSQL_KEY_CACHE_MAX_KEY_COLS 8
695
696/**
697 * @brief One PRIMARY-KEY or NOT-NULL-UNIQUE key on a relation.
698 *
699 * @c col_n is the number of valid entries in @c cols (in
700 * @c pg_index.indkey order, i.e. column position in the key, not
701 * @c pg_attribute.attnum order). All columns are NOT NULL by
702 * construction: PRIMARY KEY enforces this implicitly, and UNIQUE
703 * constraints are admitted only when @c pg_attribute.attnotnull is
704 * @c true for every constituent column (the §2 soundness trap on
705 * nullable UNIQUE).
706 */
711
712/**
713 * @brief Per-relation set of PRIMARY-KEY and NOT-NULL-UNIQUE keys.
714 *
715 * Populated by @c provsql_lookup_relation_keys from @c pg_constraint
716 * (filtered by @c contype @c IN @c ('p','u')) joined to
717 * @c pg_index and @c pg_attribute (for the NOT-NULL check). The
718 * detector's §2 PK-FD pass walks @c keys and, for every key @c K it
719 * recognises among the query's equijoin equivalence classes, tags
720 * the determined columns as functionally fixed inside the relevant
721 * RTE.
722 */
728
729/**
730 * @brief Look up the PRIMARY-KEY and NOT-NULL-UNIQUE keys of a
731 * relation with a backend-local cache.
732 *
733 * Companion to @c provsql_lookup_table_info. The cache lives in a
734 * separate backing array with its own relcache-invalidation
735 * callback so that a future @c ALTER @c TABLE that adds / drops a
736 * constraint refreshes the next lookup without polling. Returns
737 * @c true when the relation has at least one PRIMARY KEY or
738 * NOT-NULL UNIQUE constraint; @c false otherwise (in which case
739 * @p *out is filled with @c key_n @c = @c 0). Safe to call from
740 * the planner hot path.
741 *
742 * @param relid pg_class OID of the relation to inspect.
743 * @param out Filled on return. @c out->relid is set to @p relid
744 * regardless of return value; @c out->keys holds up to
745 * @c PROVSQL_KEY_CACHE_MAX_KEYS keys.
746 */
747extern bool provsql_lookup_relation_keys(Oid relid,
749
750#include "provsql_error.h"
751
752#ifdef __cplusplus
753/* Neutralise the PostgreSQL macros (gettext family, port.h's printf-family
754 * replacements) that break STL / Boost headers included after this point;
755 * see c_cpp_compatibility.h. Done here so every C++ translation unit that
756 * pulls in the PostgreSQL headers through provsql_utils.h is covered
757 * without having to mind its include order. */
758#include "c_cpp_compatibility.h"
759#endif
760
761#endif /* PROVSQL_UTILS_H */
Per-table provenance metadata persisted alongside the circuit store.
Fix macro conflicts between PostgreSQL headers and the C++ STL/Boost.
int provsql_mobius_max_gates
Data-cost cap of the Möbius route: it declines (falling through to joint-width / the ladder) once its...
Definition provsql.c:107
bool provsql_where_provenance
Global variable that indicates if where-provenance support has been activated through the provsql....
Definition provsql.c:91
bool provsql_absorptive_provenance
Derived flag: the session's provenance class is 'absorptive' or 'boolean' – licenses constructions so...
Definition provsql.c:114
int provsql_verbose
Verbosity level; controlled by the provsql.verbose_level GUC.
Definition provsql.c:93
bool provsql_simplify_on_load
Run universal cmp-resolution passes when getGenericCircuit returns; controlled by the provsql....
Definition provsql.c:109
int provsql_mobius_max_cnf
Query-cost cap of the Möbius route: it declines when a sentence's CNF has more than this many conjunc...
Definition provsql.c:108
bool provsql_inversion_free
Insert the inversion-free structured-d-DNNF path into the default probability chain (after independen...
Definition provsql.c:112
double provsql_ess_warn_fraction
Effective-sample-size warning threshold for likelihood weighting: warn when the posterior ESS falls b...
Definition provsql.c:101
char * provsql_last_eval_method
Last probability evaluation method(s) used; exposed via provsql.last_eval_method.
Definition provsql.c:94
bool provsql_mobius
Try the safe-UCQ Möbius-inversion route (a guaranteed-PTIME exact route for its class) BEFORE the joi...
Definition provsql.c:106
int provsql_rv_mc_samples
Default sample count for analytical-evaluator MC fallbacks; 0 disables fallback (callers raise instea...
Definition provsql.c:100
int provsql_dtree_max_subproblems
Debug/safety hard cap on d-tree subproblems before it bails (0 = off; the chooser auto-budgets at the...
Definition provsql.c:102
char * provsql_kcmcp_server
Launch command for the managed KCMCP server (with a {endpoint} placeholder); controlled by the provsq...
Definition provsql.c:98
bool provsql_joint_width
Recognise unsafe UCQs at planner time and route their existence provenance through the joint-width co...
Definition provsql.c:105
int provsql_monte_carlo_seed
Seed for the Monte Carlo sampler; -1 means non-deterministic (std::random_device); controlled by the ...
Definition provsql.c:99
bool provsql_cmp_probability_evaluation
Run closed-form / analytic probability evaluators for gate_cmps inside probability_evaluate (currentl...
Definition provsql.c:111
char * provsql_tool_search_path
Colon-separated directory list prepended to PATH when invoking external tools (d4,...
Definition provsql.c:96
bool provsql_interrupted
Global variable that becomes true if this particular backend received an interrupt signal.
Definition provsql.c:89
bool provsql_boolean_provenance
Derived flag: the session's provenance class is 'boolean' – enables the Boolean-only machinery (safe-...
Definition provsql.c:113
int provsql_joint_max_states
Per-bag DP state-count cap of the joint-width UCQ compiler (the true safety net); provsql....
Definition provsql.c:104
char * provsql_fallback_compiler
Compiler used by BooleanCircuit::makeDD as the final fallback after interpretAsDD and tree-decomposit...
Definition provsql.c:97
bool provsql_hybrid_evaluation
Run the hybrid-evaluator simplifier inside probability_evaluate; controlled by the provsql....
Definition provsql.c:110
int provsql_joint_max_treewidth
Maximum joint treewidth the joint-width UCQ compiler attempts before declining (caller falls back to ...
Definition provsql.c:103
bool provsql_aggtoken_text_as_uuid
When true, agg_token::text emits the underlying provenance UUID instead of "value (*)".
Definition provsql.c:95
Uniform error-reporting macros for ProvSQL.
const char * gate_type_name[]
Names of gate types.
provsql_arith_op
Arithmetic operator tags used by gate_arith.
@ PROVSQL_ARITH_PERCENTILE
continuous percentile (order-statistic aggregate): wires are interleaved [ind_1, x_1,...
@ PROVSQL_ARITH_DIV
binary, child0 / child1
@ PROVSQL_ARITH_LN
unary, natural logarithm of child0 (a negative draw raises at evaluation)
@ PROVSQL_ARITH_PLUS
n-ary, sum of children
@ PROVSQL_ARITH_POW
binary, child0 ^ child1 (real branch only: a negative base drawn with a non-integer exponent raises a...
@ PROVSQL_ARITH_NEG
unary, -child0
@ PROVSQL_ARITH_MINUS
binary, child0 - child1
@ PROVSQL_ARITH_EXP
unary, e^child0
@ PROVSQL_ARITH_TIMES
n-ary, product of children
@ PROVSQL_ARITH_MIN
n-ary, min of children (order statistic; least / min aggregate)
@ PROVSQL_ARITH_MAX
n-ary, max of children (order statistic; greatest / max aggregate)
Oid find_equality_operator(Oid ltypeId, Oid rtypeId)
Find the equality operator OID for two given types.
#define PROVSQL_KEY_CACHE_MAX_KEY_COLS
void RegisterProvSQLKCMCPWorker(void)
Register the supervisor background worker that launches and supervises the managed KCMCP server; call...
bool provsql_lookup_ancestry(Oid relid, uint16 *ancestor_n_out, Oid *ancestors_out)
Look up the base-ancestor set of a tracked relation.
bool provsql_lookup_table_info(Oid relid, ProvenanceTableInfo *out)
Look up per-table provenance metadata with a backend-local cache.
const char * provsql_kcmcp_managed_endpoint(void)
Read the live endpoint of the managed KCMCP server from shared memory (e.g.
constants_t get_constants(bool failure_if_not_possible)
Retrieve the cached OID constants for the current database.
@ gate_observe
Latent-variable observation (likelihood-weighting evidence): one wire → an observed bare gate_rv leaf...
@ gate_rv
Continuous random-variable leaf (extra encodes distribution).
@ gate_case
N-ary guarded selection over scalar (RV) children: wires are [guard_1, value_1, .....
@ gate_annotation
Transparent single-child wrapper carrying a query-level annotation in extra (inversion-free certifica...
@ gate_mobius
Signed Möbius combination: a MEASURE-only gate carrying one integer coefficient per child (in extra,...
@ gate_conditioned
Conditioning marker with two children [target, evidence]: measure-only, probability_evaluate returns ...
@ gate_mixture
Probabilistic mixture: three wires [p_token (gate_input Bernoulli), x_token, y_token]; samples x when...
@ gate_arith
n-ary arithmetic gate over scalar-valued children (info1 holds operator tag)
@ gate_assumed
Structural marker over a single child whose sub-circuit was computed under a Boolean-provenance assum...
@ nb_gate_types
Total number of gate types.
bool provsql_lookup_relation_keys(Oid relid, ProvenanceRelationKeys *out)
Look up the PRIMARY-KEY and NOT-NULL-UNIQUE keys of a relation with a backend-local cache.
bool provsql_fetch_table_info(Oid relid, ProvenanceTableInfo *out)
Raw IPC fetch (no cache).
#define UUID_LEN
Number of bytes in a UUID.
bool provsql_fetch_ancestry(Oid relid, uint16 *ancestor_n_out, Oid *ancestors_out)
Raw IPC fetch for the ancestry half (no cache).
#define PROVSQL_KEY_CACHE_MAX_KEYS
Upper bounds for the relation-key cache.
provsql_route
Tags identifying the planner-time route that produced a circuit.
@ PROVSQL_ROUTE_BOUNDED_JW
Joint-width UCQ compiler (src/UCQJointCompiler.h).
@ PROVSQL_ROUTE_SQ_REWRITE
Hierarchical-CQ read-once rewrite (src/safe_query.c).
@ PROVSQL_ROUTE_NONE
No route rewrite: ordinary lineage.
@ PROVSQL_ROUTE_REACHABILITY
Recursive-reachability compiler (src/reachability_evaluate.cpp).
One PRIMARY-KEY or NOT-NULL-UNIQUE key on a relation.
AttrNumber cols[PROVSQL_KEY_CACHE_MAX_KEY_COLS]
Per-relation set of PRIMARY-KEY and NOT-NULL-UNIQUE keys.
ProvenanceRelationKey keys[PROVSQL_KEY_CACHE_MAX_KEYS]
Per-relation metadata for the safe-query optimisation.
Structure to store the value of various constants.
Oid OID_FUNCTION_REGULAR_INDICATOR
OID of provsql.regular_indicator(boolean): the deterministic gate_one/gate_zero indicator the planner...
Oid OID_FUNCTION_PROVENANCE_EQ
OID of the provenance_eq FUNCTION.
Oid OID_FUNCTION_PROVENANCE_AGGREGATE
OID of the provenance_aggregate FUNCTION.
Oid OID_FUNCTION_PROVENANCE_SEMIMOD
OID of the provenance_semimod FUNCTION.
Oid OID_FUNCTION_RV_DIV
OID of random_variable_div(rv, rv) -> rv: builds the avg num/denom division gate.
Oid OID_AGG_AVG_RV
provsql.avg(random_variable)
Oid OID_AGG_RV_CORR_IMPL
provsql.rv_corr_impl(ind rv, x rv, y rv)
Oid OID_AGG_RV_SUM_OR_NULL
provsql.rv_sum_or_null(random_variable): the avg-numerator sum, NULL on an empty group (so avg is NUL...
Oid OID_AGG_SUM_RV
OIDs of the RV-returning aggregates, keyed for the per-aggregate identity dispatch in make_rv_aggrega...
Oid OID_FUNCTION_CHOOSE
OID of the choose(anyelement) aggregate (keeps the first non-NULL value); used to decorrelate scalar ...
Oid OID_AGG_RV_STDDEV_SAMP_IMPL
provsql.rv_stddev_samp_impl(ind rv, x rv)
Oid OID_AGG_STDDEV_SAMP_RV
provsql.stddev_samp(rv)
Oid OID_FUNCTION_ANNOTATE
OID of provsql.annotate(uuid,text)->uuid.
Oid OID_FUNCTION_PROVENANCE
OID of the provenance FUNCTION.
Oid OID_FUNCTION_RV_LEAST
provsql.least(VARIADIC random_variable[])
Oid OID_FUNCTION_RV_CASE
OID of provsql.rv_case(uuid[])->random_variable.
Oid OID_FUNCTION_INVERSION_FREE_KEY
OID of provsql.inversion_free_key(text,text,int)->text.
Oid OID_FUNCTION_AGG_VALUE_GATE
agg_value_gate(numeric) -> uuid
Oid OID_FUNCTION_AGG_TOKEN_UUID
OID of the agg_token_uuid FUNCTION.
Oid OID_AGG_STDDEV_POP_RV
provsql.stddev_pop(rv)
Oid OID_FUNCTION_RV_AGGREGATE_SEMIMOD
OID of rv_aggregate_semimod(uuid, rv) -> rv: wraps a per-row argument as mixture(prov,...
Oid OID_TYPE_VARCHAR
OID of the VARCHAR TYPE.
Oid OID_FUNCTION_GATE_ZERO
OID of the provenance_zero FUNCTION.
Oid OID_SCHEMA_PROVSQL
OID of the provsql SCHEMA.
Oid OID_TYPE_RANDOM_VARIABLE_ARRAY
OID of the random_variable[] TYPE.
Oid OID_AGG_PRODUCT_RV
provsql.product(random_variable)
Oid OID_FUNCTION_COND
OID of provsql.cond(uuid,uuid)->uuid.
Oid OID_TYPE_GATE_TYPE
OID of the provenance_gate TYPE.
Oid OID_FUNCTION_PROVENANCE_PROJECT
OID of the provenance_project FUNCTION.
Oid OID_FUNCTION_RV_AGGREGATE_INDICATOR
OID of rv_aggregate_indicator(uuid) -> rv: the avg denominator wrap mixture(prov, 1,...
Oid OID_FUNCTION_GET_CHILDREN
OID of the get_children FUNCTION.
Oid OID_FUNCTION_RV_AGGREGATE_SEMIMOD_ID
OID of the 3-arg rv_aggregate_semimod(uuid, rv, float8): identity-parameterised wrap mixture(prov,...
Oid OID_UNNEST
OID of the unnest(anyarray) FUNCTION.
Oid OID_FUNCTION_COND_PREDICATE
cond_predicate(uuid,boolean)
Oid OID_AGG_MIN_RV
provsql.min(random_variable)
Oid OID_TYPE_FLOAT
OID of the FLOAT TYPE.
Oid OID_TYPE_AGG_TOKEN
OID of the agg_token TYPE.
Oid OID_FUNCTION_ARRAY_AGG
OID of the array_agg FUNCTION.
Oid OID_TYPE_INT
OID of the INT TYPE.
Oid GATE_TYPE_TO_OID[nb_gate_types]
Array of the OID of each provenance_gate ENUM value.
Oid OID_FUNCTION_PROVENANCE_PLUS
OID of the provenance_plus FUNCTION.
Oid OID_OPERATOR_NOT_EQUAL_UUID
OID of the <> operator on UUIDs FUNCTION.
Oid OID_TYPE_UUID
OID of the uuid TYPE.
Oid OID_TYPE_TSTZMULTIRANGE
OID of the tstzmultirange TYPE (PG14+, InvalidOid otherwise).
bool ok
true if constants were loaded
Oid OID_TYPE_INT_ARRAY
OID of the INT[] TYPE.
Oid OID_AGG_RV_PERCENTILE_IMPL
provsql.rv_percentile_impl(fraction float8, ind rv, x rv)
Oid OID_FUNCTION_PROVENANCE_DELTA
OID of the provenance_delta FUNCTION.
Oid OID_FUNCTION_ASSUME_BOOLEAN
OID of provsql.assume_boolean(uuid)->uuid.
Oid OID_FUNCTION_PROVENANCE_TIMES
OID of the provenance_times FUNCTION.
Oid OID_FUNCTION_PROVENANCE_MONUS
OID of the provenance_monus FUNCTION.
Oid OID_FUNCTION_AGG_COND_PREDICATE
agg_token_cond_predicate(agg_token,boolean)
Oid OID_FUNCTION_GIVEN_PREDICATE
given_predicate(boolean) – prefix whole-tuple
Oid OID_TYPE_BOOL
OID of the BOOL TYPE.
Oid OID_FUNCTION_NOT_EQUAL_UUID
OID of the = operator on UUIDs FUNCTION.
Oid OID_FUNCTION_AGG_CASE
OID of agg_case(uuid[]), the agg_token constructor the planner hook lowers an aggregate-carrier CASE ...
Oid OID_AGG_CORR_RV
provsql.corr(rv, rv)
Oid OID_FUNCTION_GIVEN
OID of provsql.given(uuid)->uuid.
Oid OID_FUNCTION_GATE_ONE
OID of the provenance_one FUNCTION.
Oid OID_AGG_COVAR_SAMP_RV
provsql.covar_samp(rv, rv)
Oid OID_TYPE_NUMMULTIRANGE
OID of the nummultirange TYPE (PG14+, InvalidOid otherwise).
Oid OID_FUNCTION_RV_AGGREGATE_INDICATOR_VALUED
OID of rv_aggregate_indicator(uuid, rv) -> rv: NULL when the row's value is NULL (SQL NULL-skip for a...
Oid OID_FUNCTION_PROBABILITY_EVALUATE
OID of the real provsql.probability_evaluate(uuid,text,text).
Oid OID_FUNCTION_RV_COND
OID of provsql.random_variable_cond(random_variable,uuid).
Oid OID_FUNCTION_RV_COND_PREDICATE
random_variable_cond_predicate(random_variable,boolean)
Oid OID_TYPE_UUID_ARRAY
OID of the uuid[] TYPE.
Oid OID_FUNCTION_PREDICATE_COND_PREDICATE
predicate_cond_predicate(boolean,boolean) – (A)|(B), both events
Oid OID_AGG_MAX_RV
provsql.max(random_variable)
Oid OID_FUNCTION_AGG_COND
OID of provsql.agg_token_cond(agg_token,uuid): the conditioning constructor for the agg_token carrier...
Oid OID_FUNCTION_PROBABILITY_PREDICATE
OID of the probability(boolean,text,text) placeholder.
Oid OID_TYPE_RANDOM_VARIABLE
OID of the random_variable TYPE.
Oid OID_AGG_COVAR_POP_RV
SQL-standard statistic aggregates over random_variable rows and their internal indicator-carrying rew...
Oid OID_FUNCTION_PROVENANCE_CMP
OID of the provenance_cmp FUNCTION.
Oid OID_AGG_PERCENTILE_CONT_RV
provsql.percentile_cont(float8) WITHIN GROUP (ORDER BY rv)
Oid OID_FUNCTION_RV_GREATEST
provsql.greatest(VARIADIC random_variable[])
Oid OID_AGG_RV_COVAR_POP_IMPL
provsql.rv_covar_pop_impl(ind rv, x rv, y rv)
Oid OID_AGG_RV_STDDEV_POP_IMPL
provsql.rv_stddev_pop_impl(ind rv, x rv)
Oid OID_TYPE_INT4MULTIRANGE
OID of the int4multirange TYPE (PG14+, InvalidOid otherwise).
Oid OID_AGG_RV_COVAR_SAMP_IMPL
provsql.rv_covar_samp_impl(ind rv, x rv, y rv)
Oid OID_FUNCTION_GET_EXTRA
OID of the get_extra FUNCTION.
Oid OID_FUNCTION_RV_CMP[6]
OIDs of the random_variable_{eq,ne,le,lt,ge,gt} comparison procedure functions, indexed by the Compar...
Oid OID_FUNCTION_PROVENANCE_CMP_TIMES
OID of the provenance_cmp_times FUNCTION.
Structure to store the value of various constants for a specific database.
Oid database
OID of the database these constants belong to.
constants_t constants
Cached OID constants for this database.
UUID structure.