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_invalid, ///< Invalid gate type
79 nb_gate_types ///< Total number of gate types
80} gate_type;
81
82/**
83 * @brief Scalar-aggregation flag, stored in the upper bit of a @c gate_agg's
84 * @c info2 (whose low 31 bits hold the aggregate result-type OID).
85 *
86 * Set by the query rewriter when the aggregation has no @c GROUP @c BY (a single
87 * always-present result row). It tells the value-aware evaluators that the
88 * empty-input world is a real possible world (carrying the aggregate's
89 * empty-group value), rather than the "no row" of a grouped query. Result-type
90 * OIDs never use bit 31, so the low 31 bits still recover the type via
91 * @c PROVSQL_AGG_TYPE_MASK.
92 *
93 * @warning The flag is folded into the gate's content UUID (see
94 * @c provenance_aggregate), so a scalar and a grouped aggregate over identical
95 * children stay distinct gates and their @c set_infos calls do not clobber.
96 */
97#define PROVSQL_AGG_SCALAR_FLAG 0x80000000u
98#define PROVSQL_AGG_TYPE_MASK 0x7FFFFFFFu
99
100/**
101 * @brief Arithmetic operator tags used by @c gate_arith.
102 *
103 * Stored in the gate's @c info1 field. Local enum (not a PostgreSQL
104 * operator OID) because arithmetic in the sampler / evaluator is just
105 * C++ doubles, with no need to dispatch through the PG catalog.
106 *
107 * @warning ON-DISK ABI: like @c gate_type, these integer values are
108 * persisted (in @c info1). Reordering or renumbering existing tags
109 * will silently invalidate every existing installation's persistent
110 * circuit. New tags must be appended at the end.
111 */
112typedef enum provsql_arith_op {
113 PROVSQL_ARITH_PLUS = 0, ///< n-ary, sum of children
114 PROVSQL_ARITH_TIMES = 1, ///< n-ary, product of children
115 PROVSQL_ARITH_MINUS = 2, ///< binary, child0 - child1
116 PROVSQL_ARITH_DIV = 3, ///< binary, child0 / child1
117 PROVSQL_ARITH_NEG = 4 ///< unary, -child0
119
120/** Names of gate types */
121extern const char *gate_type_name[];
122
123/**
124 * @brief Canonical name of the per-row provenance column installed by
125 * @c add_provenance / @c repair_key.
126 *
127 * Centralised so the planner-hook entry points (@c src/provsql.c) and
128 * the safe-query detector (@c src/safe_query.c) agree on the literal;
129 * see the @c provenance_guard trigger in @c sql/provsql.common.sql.
130 */
131#define PROVSQL_COLUMN_NAME "provsql"
132
133/** Structure to store the value of various constants. This is needed to
134 * uniquely identify types, functions, etc., in PostgreSQL through their
135 * Object Identifier Types (OIDs). */
136typedef struct constants_t {
137 Oid OID_SCHEMA_PROVSQL; ///< OID of the provsql SCHEMA
138 Oid OID_TYPE_GATE_TYPE; ///< OID of the provenance_gate TYPE
139 Oid OID_TYPE_AGG_TOKEN; ///< OID of the agg_token TYPE
140 Oid OID_TYPE_UUID; ///< OID of the uuid TYPE
141 Oid OID_TYPE_UUID_ARRAY; ///< OID of the uuid[] TYPE
142 Oid OID_TYPE_BOOL; ///< OID of the BOOL TYPE
143 Oid OID_TYPE_INT; ///< OID of the INT TYPE
144 Oid OID_TYPE_INT_ARRAY; ///< OID of the INT[] TYPE
145 Oid OID_TYPE_FLOAT; ///< OID of the FLOAT TYPE
146 Oid OID_TYPE_VARCHAR; ///< OID of the VARCHAR TYPE
147 Oid OID_TYPE_TSTZMULTIRANGE; ///< OID of the tstzmultirange TYPE (PG14+, InvalidOid otherwise)
148 Oid OID_TYPE_NUMMULTIRANGE; ///< OID of the nummultirange TYPE (PG14+, InvalidOid otherwise)
149 Oid OID_TYPE_INT4MULTIRANGE; ///< OID of the int4multirange TYPE (PG14+, InvalidOid otherwise)
150 Oid OID_FUNCTION_ARRAY_AGG; ///< OID of the array_agg FUNCTION
151 Oid OID_FUNCTION_PROVENANCE_PLUS; ///< OID of the provenance_plus FUNCTION
152 Oid OID_FUNCTION_PROVENANCE_TIMES; ///< OID of the provenance_times FUNCTION
153 Oid OID_FUNCTION_PROVENANCE_MONUS; ///< OID of the provenance_monus FUNCTION
154 Oid OID_FUNCTION_PROVENANCE_PROJECT; ///< OID of the provenance_project FUNCTION
155 Oid OID_FUNCTION_PROVENANCE_EQ;///< OID of the provenance_eq FUNCTION
156 Oid OID_FUNCTION_PROVENANCE_CMP; ///< OID of the provenance_cmp FUNCTION
157 Oid OID_FUNCTION_PROVENANCE; ///< OID of the provenance FUNCTION
158 Oid GATE_TYPE_TO_OID[nb_gate_types]; ///< Array of the OID of each provenance_gate ENUM value
159 Oid OID_FUNCTION_PROVENANCE_DELTA; ///< OID of the provenance_delta FUNCTION
160 Oid OID_FUNCTION_PROVENANCE_AGGREGATE; ///< OID of the provenance_aggregate FUNCTION
161 Oid OID_FUNCTION_PROVENANCE_SEMIMOD; ///< OID of the provenance_semimod FUNCTION
162 Oid OID_FUNCTION_GATE_ZERO; ///< OID of the provenance_zero FUNCTION
163 Oid OID_FUNCTION_GATE_ONE; ///< OID of the provenance_one FUNCTION
164 Oid OID_OPERATOR_NOT_EQUAL_UUID; ///< OID of the <> operator on UUIDs FUNCTION
165 Oid OID_FUNCTION_NOT_EQUAL_UUID; ///< OID of the = operator on UUIDs FUNCTION
166 Oid OID_FUNCTION_AGG_TOKEN_UUID; ///< OID of the agg_token_uuid FUNCTION
167 Oid OID_FUNCTION_GET_CHILDREN; ///< OID of the get_children FUNCTION
168 Oid OID_FUNCTION_GET_EXTRA; ///< OID of the get_extra FUNCTION
169 Oid OID_UNNEST; ///< OID of the unnest(anyarray) FUNCTION
170 Oid OID_TYPE_RANDOM_VARIABLE; ///< OID of the random_variable TYPE
171 Oid OID_FUNCTION_RV_AGGREGATE_SEMIMOD; ///< OID of rv_aggregate_semimod helper (uuid, rv -> rv) used to wrap each per-row argument of an RV-returning aggregate (sum, avg, ...)
172 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
173 /** @brief OID of @c provsql.assume_boolean(uuid)->uuid.
174 *
175 * Installed by the @c 1.5.0--1.6.0 upgrade script. Wraps its child
176 * in a fresh @c gate_assumed and returns the wrapper's UUID.
177 * When @c InvalidOid the safe-query rewriter (and any other
178 * Boolean-only rewrite that needs the marker) is effectively
179 * disabled even if @c provsql.boolean_provenance is on: the
180 * rewriter refuses to produce unmarked roots on a schema that
181 * cannot enforce the semiring-compatibility check. */
183 /** @brief OID of @c provsql.annotate(uuid,text)->uuid.
184 *
185 * Wraps its child in a fresh transparent @c gate_annotation whose UUID
186 * folds in the @c extra text, and returns the wrapper's UUID. Used to
187 * attach the inversion-free tractability certificate (on the root) and the
188 * per-input order keys. @c InvalidOid on a schema predating the gate
189 * (the inversion-free carrier is then disabled). */
191 /** @brief OID of @c provsql.inversion_free_key(text,text,int)->text.
192 *
193 * Builds the @c K-prefixed per-input order-key string the planner attaches
194 * (via @c annotate) to each certified atom's provenance on the
195 * inversion-free path. @c InvalidOid on a schema predating it (markers are
196 * then not attached; the path declines and falls back). */
198 /** OIDs of the @c random_variable_{eq,ne,le,lt,ge,gt} comparison
199 * procedure functions, indexed by the @c ComparisonOperator enum
200 * (@c EQ=0, @c NE=1, @c LE=2, @c LT=3, @c GE=4, @c GT=5; matches the
201 * order in @c src/Aggregation.h). Used by the planner hook to detect
202 * RV-comparison @c OpExpr nodes in WHERE clauses. */
204 /** @brief OID of @c provsql.cond(uuid,uuid)->uuid.
205 *
206 * Builds the terminal @c gate_conditioned (value-level conditioning, the
207 * binary @c | operator). The rewriter wraps a row's output provenance in
208 * it when a @c given(...) marker is present. @c InvalidOid on a schema
209 * predating the conditioning feature (the @c given rewrite is then
210 * disabled). */
212 /** @brief OID of @c provsql.given(uuid)->uuid.
213 *
214 * The whole-tuple output-conditioning marker: a consumed select-list term
215 * the rewriter strips from the visible projection, conditioning each output
216 * row's provenance on the marker's argument. @c InvalidOid on a schema
217 * predating the feature. */
219 /** @brief OID of @c provsql.random_variable_cond(random_variable,uuid).
220 * The real conditioning constructor the planner emits when rewriting the
221 * @c "X | (predicate)" placeholder. @c InvalidOid disables the rewrite. */
223 /** @brief OID of @c provsql.agg_token_cond(agg_token,uuid): the conditioning
224 * constructor for the @c agg_token carrier the planner emits when rewriting
225 * the @c "SUM(x) | (predicate)" placeholder. */
227 /** @name @c "X | (predicate)" placeholder OIDs (carrier-parametric).
228 * Each is a no-op placeholder operator whose right operand is a Boolean
229 * combination of random_variable / agg_token comparisons; the planner
230 * converts that predicate into a condition gate and emits the matching
231 * conditioning constructor. @c InvalidOid disables the rewrite. */
232 /**@{*/
233 Oid OID_FUNCTION_COND_PREDICATE; ///< cond_predicate(uuid,boolean)
234 Oid OID_FUNCTION_RV_COND_PREDICATE; ///< random_variable_cond_predicate(random_variable,boolean)
235 Oid OID_FUNCTION_AGG_COND_PREDICATE; ///< agg_token_cond_predicate(agg_token,boolean)
236 Oid OID_FUNCTION_GIVEN_PREDICATE; ///< given_predicate(boolean) -- prefix whole-tuple
237 /**@}*/
238 /** @brief OID of @c provsql.regular_indicator(boolean): the deterministic
239 * @c gate_one/@c gate_zero indicator the planner emits for an ordinary
240 * (regular-type) comparison appearing inside a mixed conditioning
241 * predicate. */
243 bool ok; ///< true if constants were loaded
245
246
247
248
249/** Structure to store the value of various constants for a specific
250 * database. */
251typedef struct database_constants_t {
252 Oid database; ///< OID of the database these constants belong to
253 constants_t constants; ///< Cached OID constants for this database
255
256/**
257 * @brief Retrieve the cached OID constants for the current database.
258 *
259 * On first call (or after a cache miss) this function looks up the OIDs
260 * of all ProvSQL-specific types, functions, and operators in the system
261 * catalogs and stores them in a per-database cache. Subsequent calls
262 * return the cached values without touching the catalogs.
263 *
264 * @param failure_if_not_possible If @c true, call @c provsql_error when
265 * the ProvSQL schema cannot be found (e.g. the extension is not
266 * installed in the current database). If @c false, return a
267 * constants_t with @c ok==false instead of aborting.
268 * @return A @c constants_t whose @c ok field is @c true on success.
269 */
270constants_t get_constants(bool failure_if_not_possible);
271
272/**
273 * @brief Find the equality operator OID for two given types.
274 *
275 * Searches @c pg_operator for the @c = operator that accepts
276 * @p ltypeId on the left and @p rtypeId on the right.
277 *
278 * @param ltypeId OID of the left operand type.
279 * @param rtypeId OID of the right operand type.
280 * @return The operator OID, or @c InvalidOid if none is found.
281 */
282Oid find_equality_operator(Oid ltypeId, Oid rtypeId);
283
284/** Global variable that becomes true if this particular backend received
285 * an interrupt signal. */
286extern bool provsql_interrupted;
287
288/** Global variable that indicates if where-provenance support has been
289 * activated through the provsql.where_provenance run-time configuration
290 * parameter. */
291extern bool provsql_where_provenance;
292
293/** Global variable that indicates the verbosity level set by the
294 * provsql.verbose_level run-time configuration parameter was set */
295extern int provsql_verbose;
296
297/** Global variable holding the probability evaluation method(s) used by the
298 * most recent probability_evaluate call, exposed via the
299 * provsql.last_eval_method run-time configuration parameter. */
300extern char *provsql_last_eval_method;
301
302/** Global flag controlling agg_token text output: when true,
303 * agg_token_out emits the underlying provenance UUID instead of the
304 * default "value (*)" display string. Driven by the
305 * provsql.aggtoken_text_as_uuid GUC. */
307
308/** Colon-separated list of directories prepended to PATH when ProvSQL
309 * spawns external tools (d4, c2d, minic2d, dsharp, weightmc, graph-easy),
310 * set by the provsql.tool_search_path run-time configuration parameter.
311 * NULL or empty means rely on the server's PATH alone. */
312extern char *provsql_tool_search_path;
313
314/** Compiler invoked as the final fallback in BooleanCircuit::makeDD when
315 * both interpretAsDD() and the in-process tree-decomposition path fail
316 * (the latter typically on treewidth blow-up). Defaults to "d4"; set by
317 * the provsql.fallback_compiler run-time configuration parameter to any
318 * compiler accepted by BooleanCircuit::compilation (d4 / d4v2 / c2d /
319 * minic2d / dsharp / panini-*). */
320extern char *provsql_fallback_compiler;
321
322/** Launch command for the managed KCMCP knowledge-compiler server, set by
323 * the provsql.kcmcp_server run-time configuration parameter (PGC_SIGHUP).
324 * The literal substring "{endpoint}" is replaced by the Unix-socket path the
325 * supervisor background worker chooses, e.g. "tdkc --kcmcp unix:{endpoint}".
326 * NULL or empty means no managed server is launched. */
327extern char *provsql_kcmcp_server;
328
329/** Read the live endpoint of the managed KCMCP server from shared memory
330 * (e.g. "unix:/tmp/..."), or an empty string when none is running. */
331const char *provsql_kcmcp_managed_endpoint(void);
332
333/** Register the supervisor background worker that launches and supervises the
334 * managed KCMCP server; called from _PG_init alongside the mmap worker. */
336
337/** Seed for the Monte Carlo sampler, set by the provsql.monte_carlo_seed
338 * run-time configuration parameter. -1 (default) means seed from
339 * std::random_device for non-deterministic sampling; any other value
340 * (including 0) is a literal seed for std::mt19937_64. Used by both
341 * the Bernoulli path (BooleanCircuit::monteCarlo) and the continuous
342 * path (gate_rv sampling), so a single GUC controls reproducibility
343 * end-to-end. */
344extern int provsql_monte_carlo_seed;
345
346/** Default sample count for Monte Carlo fallbacks when an analytical
347 * evaluator (Expectation, future hybrid evaluator, ...) cannot
348 * decompose a sub-circuit structurally. Unlike
349 * @c probability_evaluate(token, 'monte-carlo', n) where the sample
350 * count is an explicit argument, these implicit MC paths have no
351 * natural place to take @c n from.
352 *
353 * Set by the @c provsql.rv_mc_samples run-time configuration
354 * parameter; default 10000. Setting it to 0 disables the implicit
355 * MC fallback entirely: callers must then raise an exception rather
356 * than sampling. Useful for callers that want to guarantee
357 * analytical-only evaluation. */
358extern int provsql_rv_mc_samples;
359
360/* Debug/safety hard cap on d-tree subproblems before the method bails to the
361 * next (0 = off). The chooser auto-budgets the d-tree at the next-best
362 * method's estimated cost regardless; this imposes an extra fixed cap. */
364
365/* Joint-width UCQ compiler (see UCQJointCompiler.h): the maximum joint
366 * treewidth attempted before the path declines (the SQL layer then falls
367 * back to the standard ladder). Default = TreeDecomposition::MAX_TREEWIDTH
368 * (10). */
370
371/* Joint-width UCQ compiler: the per-bag DP state-count cap, the true safety
372 * net (the static enumerating-variable count is only a predictor). Default
373 * 1<<16. */
374extern int provsql_joint_max_states;
375
376/** @brief When @c true (default), every @c GenericCircuit returned by
377 * @c getGenericCircuit is run through the universal cmp-resolution
378 * passes (RangeCheck for now, plus any future passes that decide
379 * comparators to certain Boolean values). Decisions become Bernoulli
380 * @c gate_input gates with probability 0 or 1, transparent to every
381 * downstream consumer (semiring evaluators, MC, view_circuit, PROV
382 * export, etc.). Set @c provsql.simplify_on_load to @c off when
383 * inspecting a circuit's raw structure (e.g. debugging gate-creation
384 * code paths). */
385extern bool provsql_simplify_on_load;
386
387/** @brief Run the hybrid evaluator (simplifier + per-cmp island
388 * decomposer) before dispatching a probability_evaluate query.
389 *
390 * Debug-only GUC, hidden from @c SHOW @c ALL and from
391 * @c postgresql.conf.sample (registered with
392 * @c GUC_NO_SHOW_ALL @c | @c GUC_NOT_IN_SAMPLE). When on (default),
393 * @c probability_evaluate runs the @c HybridEvaluator simplifier
394 * between @c RangeCheck and @c AnalyticEvaluator and the per-cmp
395 * MC island decomposer after @c AnalyticEvaluator: @c gate_arith
396 * subtrees are constant-folded and family-closed (normals, Erlang),
397 * and residual continuous-island comparators are MC-marginalised
398 * into Bernoulli @c gate_input leaves so the surrounding circuit
399 * becomes purely Boolean.
400 *
401 * Set to @c off to bypass both passes: undecidable comparators
402 * then fall through to whole-circuit MC (for the @c monte-carlo
403 * method) or raise (for @c independent / @c tree-decomposition).
404 * End users have no reason to flip this -- on is strictly better
405 * for them. Exists for developer A/B testing of the analytic
406 * path against the raw MC path and as a bisection knob if a
407 * closure rule turns out to be unsound on some workload. */
408extern bool provsql_hybrid_evaluation;
409
410/** @brief Hidden diagnostic flag for the family of closed-form /
411 * analytic probability evaluators that resolve @c gate_cmps inside
412 * @c probability_evaluate ; see the
413 * @c provsql.cmp_probability_evaluation GUC.
414 *
415 * When on (default), @c probability_evaluate runs pre-passes that
416 * recognise specific @c gate_cmp shapes and replace each cmp with
417 * a Bernoulli @c gate_input carrying the closed-form probability,
418 * bypassing the DNF that @c provsql_having's
419 * @c enumerate_valid_worlds would otherwise emit. The first
420 * implementation in this family is the Poisson-binomial pre-pass
421 * for HAVING @c COUNT(*) @c op @c C over distinct @c gate_input
422 * leaves (see @c CountCmpEvaluator.h) ; future MIN / MAX / SUM
423 * evaluators will gate on the same flag. Off forces every cmp to
424 * fall through to the enumeration path. End users have no reason
425 * to flip this ; exists for developer A/B testing and as a
426 * bisection escape valve. */
428
429/** @brief Kill-switch for the inversion-free structured-d-DNNF probability
430 * path; see the @c provsql.inversion_free GUC.
431 *
432 * When on (default), @c probability_evaluate, on a query carrying an
433 * inversion-free tractability certificate, tries the structured-d-DNNF
434 * builder after @c independentEvaluation and before tree-decomposition / d4.
435 * Off disables only that automatic insertion (for A/B testing); the explicit
436 * @c probability_evaluate(token,'inversion-free') method ignores this flag.
437 * The path is self-gating on the certificate, which is attached only to
438 * certified queries, so leaving it on is safe. */
439extern bool provsql_inversion_free;
440
441/** @brief Opt-in safe-query optimisation for hierarchical conjunctive
442 * queries; see the @c provsql.boolean_provenance GUC.
443 *
444 * When @c true, the planner is permitted to rewrite self-join-free
445 * hierarchical CQs (and independent UCQs) over TID / BID tables to
446 * a read-once form whose probability is computable in linear time.
447 * The rewriter tags the resulting root gate so that semiring
448 * evaluations incompatible with this rewrite refuse to run on the
449 * produced circuit. */
451
452/** @brief Derived flag of the @c provsql.provenance GUC: the session's
453 * provenance class is 'absorptive' or 'boolean', licensing
454 * constructions sound for absorptive semirings only (cyclic recursion
455 * stopped at the absorptive value fixpoint, tagged tokens). */
457
458#include "MMappedTableInfo.h"
459
460/**
461 * @brief Look up per-table provenance metadata with a backend-local cache.
462 *
463 * Resolves to a cached value when the relation's relcache entry has
464 * not been invalidated since the last fetch; otherwise issues one
465 * @c 's' IPC to the background worker. The cache is invalidated
466 * via @c CacheRegisterRelcacheCallback, so concurrent
467 * @c add_provenance / @c repair_key / @c remove_provenance in other
468 * backends are reflected here without polling.
469 *
470 * Safe to call from the planner hot path.
471 *
472 * @param relid pg_class OID of the relation to look up.
473 * @param out On @c true return, filled with the stored record.
474 * @return @c true if a record exists for @p relid, @c false otherwise.
475 */
476extern bool provsql_lookup_table_info(Oid relid, ProvenanceTableInfo *out);
477
478/**
479 * @brief Raw IPC fetch (no cache).
480 *
481 * Implementation detail of @c provsql_lookup_table_info, exposed only
482 * so the cache layer in @c provsql_utils.c can reach it. Callers in
483 * the planner hot path should go through @c provsql_lookup_table_info.
484 */
485extern bool provsql_fetch_table_info(Oid relid, ProvenanceTableInfo *out);
486
487/**
488 * @brief Look up the base-ancestor set of a tracked relation.
489 *
490 * Per-backend cached over IPC. Returns the ancestor set when
491 * @p relid is tracked and the registry has a non-empty entry for it.
492 * @c false either when @p relid has no metadata record at all (the
493 * relation was never run through @c add_provenance / @c repair_key)
494 * or when the record exists but @c ancestor_n @c == @c 0 (the CTAS
495 * hook hasn't populated the lineage yet, or the registry was
496 * explicitly cleared). The two failure modes share the false
497 * return because both make the safe-query rewriter take the
498 * conservative refuse path -- there is no use case for treating
499 * them differently.
500 *
501 * Backed by the same per-backend cache as
502 * @c provsql_lookup_table_info and invalidated through the same
503 * relcache-invalidation callback, so concurrent
504 * @c set_ancestors / @c add_provenance / @c repair_key calls in
505 * other backends are reflected here without polling.
506 *
507 * @param relid pg_class OID of the relation to look up.
508 * @param ancestor_n_out On @c true return, count of valid entries
509 * in @p ancestors_out.
510 * @param ancestors_out On @c true return, the sorted-deduplicated
511 * ancestor OIDs (caller-allocated buffer of
512 * @c PROVSQL_TABLE_INFO_MAX_ANCESTORS @c Oid).
513 * @return @c true on a non-empty ancestor set; @c false otherwise.
514 */
515extern bool provsql_lookup_ancestry(Oid relid,
516 uint16 *ancestor_n_out,
517 Oid *ancestors_out);
518
519/**
520 * @brief Raw IPC fetch for the ancestry half (no cache).
521 *
522 * Implementation detail of @c provsql_lookup_ancestry, exposed so
523 * the cache layer in @c provsql_utils.c can reach it. Callers in
524 * the planner hot path should go through @c provsql_lookup_ancestry.
525 */
526extern bool provsql_fetch_ancestry(Oid relid,
527 uint16 *ancestor_n_out,
528 Oid *ancestors_out);
529
530/**
531 * @brief Upper bounds for the relation-key cache.
532 *
533 * Each relation contributes at most @c PROVSQL_KEY_CACHE_MAX_KEYS
534 * distinct PRIMARY-KEY / NOT-NULL-UNIQUE column-sets, each over at
535 * most @c PROVSQL_KEY_CACHE_MAX_KEY_COLS columns. These bounds keep
536 * the cache entry fixed-size (so the backend-local sorted-array
537 * representation can reuse the @c provsql_lookup_table_info pattern
538 * verbatim); relations with more or wider keys silently drop the
539 * overflow, treating the missing keys as if they did not exist
540 * (over-conservative -- the §2 FD-aware detector simply misses an
541 * optimisation, never produces an unsound rewrite).
542 */
543#define PROVSQL_KEY_CACHE_MAX_KEYS 4
544#define PROVSQL_KEY_CACHE_MAX_KEY_COLS 8
545
546/**
547 * @brief One PRIMARY-KEY or NOT-NULL-UNIQUE key on a relation.
548 *
549 * @c col_n is the number of valid entries in @c cols (in
550 * @c pg_index.indkey order, i.e. column position in the key, not
551 * @c pg_attribute.attnum order). All columns are NOT NULL by
552 * construction: PRIMARY KEY enforces this implicitly, and UNIQUE
553 * constraints are admitted only when @c pg_attribute.attnotnull is
554 * @c true for every constituent column (the §2 soundness trap on
555 * nullable UNIQUE).
556 */
561
562/**
563 * @brief Per-relation set of PRIMARY-KEY and NOT-NULL-UNIQUE keys.
564 *
565 * Populated by @c provsql_lookup_relation_keys from @c pg_constraint
566 * (filtered by @c contype @c IN @c ('p','u')) joined to
567 * @c pg_index and @c pg_attribute (for the NOT-NULL check). The
568 * detector's §2 PK-FD pass walks @c keys and, for every key @c K it
569 * recognises among the query's equijoin equivalence classes, tags
570 * the determined columns as functionally fixed inside the relevant
571 * RTE.
572 */
578
579/**
580 * @brief Look up the PRIMARY-KEY and NOT-NULL-UNIQUE keys of a
581 * relation with a backend-local cache.
582 *
583 * Companion to @c provsql_lookup_table_info. The cache lives in a
584 * separate backing array with its own relcache-invalidation
585 * callback so that a future @c ALTER @c TABLE that adds / drops a
586 * constraint refreshes the next lookup without polling. Returns
587 * @c true when the relation has at least one PRIMARY KEY or
588 * NOT-NULL UNIQUE constraint; @c false otherwise (in which case
589 * @p *out is filled with @c key_n @c = @c 0). Safe to call from
590 * the planner hot path.
591 *
592 * @param relid pg_class OID of the relation to inspect.
593 * @param out Filled on return. @c out->relid is set to @p relid
594 * regardless of return value; @c out->keys holds up to
595 * @c PROVSQL_KEY_CACHE_MAX_KEYS keys.
596 */
597extern bool provsql_lookup_relation_keys(Oid relid,
599
600#include "provsql_error.h"
601
602#ifdef __cplusplus
603/* Neutralise the PostgreSQL macros (gettext family, port.h's printf-family
604 * replacements) that break STL / Boost headers included after this point;
605 * see c_cpp_compatibility.h. Done here so every C++ translation unit that
606 * pulls in the PostgreSQL headers through provsql_utils.h is covered
607 * without having to mind its include order. */
608#include "c_cpp_compatibility.h"
609#endif
610
611#endif /* PROVSQL_UTILS_H */
Per-table provenance metadata persisted alongside the circuit store.
Fix macro conflicts between PostgreSQL headers and the C++ STL/Boost.
bool provsql_where_provenance
Global variable that indicates if where-provenance support has been activated through the provsql....
Definition provsql.c:87
bool provsql_absorptive_provenance
Derived flag: the session's provenance class is 'absorptive' or 'boolean' – licenses constructions so...
Definition provsql.c:108
int provsql_verbose
Verbosity level; controlled by the provsql.verbose_level GUC.
Definition provsql.c:89
bool provsql_simplify_on_load
Run universal cmp-resolution passes when getGenericCircuit returns; controlled by the provsql....
Definition provsql.c:103
bool provsql_inversion_free
Insert the inversion-free structured-d-DNNF path into the default probability chain (after independen...
Definition provsql.c:106
char * provsql_last_eval_method
Last probability evaluation method(s) used; exposed via provsql.last_eval_method.
Definition provsql.c:90
int provsql_rv_mc_samples
Default sample count for analytical-evaluator MC fallbacks; 0 disables fallback (callers raise instea...
Definition provsql.c:96
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:97
char * provsql_kcmcp_server
Launch command for the managed KCMCP server (with a {endpoint} placeholder); controlled by the provsq...
Definition provsql.c:94
int provsql_monte_carlo_seed
Seed for the Monte Carlo sampler; -1 means non-deterministic (std::random_device); controlled by the ...
Definition provsql.c:95
bool provsql_cmp_probability_evaluation
Run closed-form / analytic probability evaluators for gate_cmps inside probability_evaluate (currentl...
Definition provsql.c:105
char * provsql_tool_search_path
Colon-separated directory list prepended to PATH when invoking external tools (d4,...
Definition provsql.c:92
bool provsql_interrupted
Global variable that becomes true if this particular backend received an interrupt signal.
Definition provsql.c:85
bool provsql_boolean_provenance
Derived flag: the session's provenance class is 'boolean' – enables the Boolean-only machinery (safe-...
Definition provsql.c:107
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:99
char * provsql_fallback_compiler
Compiler used by BooleanCircuit::makeDD as the final fallback after interpretAsDD and tree-decomposit...
Definition provsql.c:93
bool provsql_hybrid_evaluation
Run the hybrid-evaluator simplifier inside probability_evaluate; controlled by the provsql....
Definition provsql.c:104
int provsql_joint_max_treewidth
Maximum joint treewidth the joint-width UCQ compiler attempts before declining (caller falls back to ...
Definition provsql.c:98
bool provsql_aggtoken_text_as_uuid
When true, agg_token::text emits the underlying provenance UUID instead of "value (*)".
Definition provsql.c:91
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_DIV
binary, child0 / child1
@ PROVSQL_ARITH_PLUS
n-ary, sum of children
@ PROVSQL_ARITH_NEG
unary, -child0
@ PROVSQL_ARITH_MINUS
binary, child0 - child1
@ PROVSQL_ARITH_TIMES
n-ary, product of children
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_rv
Continuous random-variable leaf (extra encodes distribution).
@ 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.
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_CHOOSE
OID of the choose(anyelement) aggregate (keeps the first non-NULL value); used to decorrelate scalar ...
Oid OID_FUNCTION_ANNOTATE
OID of provsql.annotate(uuid,text)->uuid.
Oid OID_FUNCTION_PROVENANCE
OID of the provenance FUNCTION.
Oid OID_FUNCTION_INVERSION_FREE_KEY
OID of provsql.inversion_free_key(text,text,int)->text.
Oid OID_FUNCTION_AGG_TOKEN_UUID
OID of the agg_token_uuid FUNCTION.
Oid OID_FUNCTION_RV_AGGREGATE_SEMIMOD
OID of rv_aggregate_semimod helper (uuid, rv -> rv) used to wrap each per-row argument of an RV-retur...
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_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_GET_CHILDREN
OID of the get_children FUNCTION.
Oid OID_UNNEST
OID of the unnest(anyarray) FUNCTION.
Oid OID_FUNCTION_COND_PREDICATE
cond_predicate(uuid,boolean)
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_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_GIVEN
OID of provsql.given(uuid)->uuid.
Oid OID_FUNCTION_GATE_ONE
OID of the provenance_one FUNCTION.
Oid OID_TYPE_NUMMULTIRANGE
OID of the nummultirange TYPE (PG14+, InvalidOid otherwise).
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_AGG_COND
OID of provsql.agg_token_cond(agg_token,uuid): the conditioning constructor for the agg_token carrier...
Oid OID_TYPE_RANDOM_VARIABLE
OID of the random_variable TYPE.
Oid OID_FUNCTION_PROVENANCE_CMP
OID of the provenance_cmp FUNCTION.
Oid OID_TYPE_INT4MULTIRANGE
OID of the int4multirange TYPE (PG14+, InvalidOid otherwise).
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...
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.