ProvSQL C/C++ API
Adding support for provenance and uncertainty management to PostgreSQL databases
Loading...
Searching...
No Matches
provenance_evaluate_compiled.cpp
Go to the documentation of this file.
1/**
2 * @file provenance_evaluate_compiled.cpp
3 * @brief SQL function @c provsql.provenance_evaluate_compiled() – C++ semiring evaluation.
4 *
5 * Implements the compiled (C++ generic) variant of provenance circuit
6 * evaluation. Unlike @c provenance_evaluate() (which calls user-supplied
7 * PostgreSQL functions for each semiring operation), this function
8 * evaluates the circuit using one of the built-in C++ semiring
9 * implementations from the @c semiring/ directory.
10 *
11 * Supported semirings (selected by the @p semiring argument):
12 * - @c "boolean" → @c semiring::Boolean
13 * - @c "counting" → @c semiring::Counting
14 * - @c "formula" → @c semiring::Formula (symbolic representation as a formula)
15 * - @c "how" → @c semiring::How (canonical polynomial provenance ℕ[X])
16 * - @c "why" → @c semiring::Why (witness sets)
17 * - @c "which" → @c semiring::Which (lineage)
18 * - @c "boolexpr" → @c semiring::BoolExpr (Boolean circuit for probability)
19 * - @c "tropical" → @c semiring::Tropical (min-plus, shortest-cost)
20 * - @c "viterbi" → @c semiring::Viterbi (max-times, most-likely derivation)
21 * - @c "lukasiewicz" → @c semiring::Lukasiewicz (Łukasiewicz fuzzy t-norm)
22 * - @c "interval_union" → @c semiring::IntervalUnion (multirange union, PG14+)
23 * for any of <tt>tstzmultirange</tt>, <tt>nummultirange</tt>,
24 * <tt>int4multirange</tt>; selected by the result type of the call
25 * - @c "minmax" / @c "maxmin" → @c semiring::MinMax over any user-defined
26 * PostgreSQL enum type, selected by @c get_typtype() == @c TYPTYPE_ENUM
27 * - @c "subset" / @c "clearance" / @c "consent" → @c semiring::Subset, the
28 * subsets of the labels of an enum type, returned as a @c bigint bitmask
29 * (declared in SQL as @c subset_evaluate)
30 *
31 * Each compiled semiring exposes @c parse_leaf() and (for text-valued
32 * carriers) @c to_text() member functions, so this file is purely a
33 * dispatcher: it picks the right semiring instance from the
34 * (result-type, semiring-name) pair, then calls the @c pec() template
35 * which runs the same four-step pipeline for every semiring (build leaf
36 * mapping, evaluate HAVING sub-circuits, evaluate the main circuit,
37 * encode the result as a Datum).
38 */
39extern "C" {
40#include "postgres.h"
41#include "fmgr.h"
42#include "catalog/pg_type.h"
43#include "utils/uuid.h"
44#include "utils/builtins.h"
45#include "utils/lsyscache.h"
46#include "utils/memutils.h"
47#include "utils/datum.h"
48#include "utils/array.h"
49#include "access/xact.h"
50#include "access/htup_details.h"
51#include "funcapi.h"
52#include "compatibility.h" /* TYPALIGN_CHAR fallback for PG < 13 */
53#include "provsql_utils.h"
54#include "provsql_mmap.h"
55#include "agg_token.h"
56
57PG_FUNCTION_INFO_V1(provenance_evaluate_compiled);
58PG_FUNCTION_INFO_V1(provenance_evaluate_tropical_paths);
59PG_FUNCTION_INFO_V1(provenance_evaluate_best_path);
60PG_FUNCTION_INFO_V1(plain_truth);
61PG_FUNCTION_INFO_V1(subset_labels);
62PG_FUNCTION_INFO_V1(subset_settling);
63PG_FUNCTION_INFO_V1(subset_member);
64PG_FUNCTION_INFO_V1(sr_formula_rows);
65}
66
67#include <string>
68#include <vector>
69#include <unordered_map>
70#include <algorithm>
71#include <deque>
72#include <limits>
73#include <unordered_set>
74
76#include "CircuitFromMMap.h"
77#include "Expectation.h"
78#include "having_semantics.hpp"
80#include "provsql_interrupt.h"
81#include "semiring/Boolean.h"
82#include "semiring/Counting.h"
83#include "semiring/Formula.h"
84#include "semiring/How.h"
85#include "semiring/Why.h"
86#include "semiring/Which.h"
87#include "semiring/BoolExpr.h"
88#include "semiring/Tropical.h"
89#include "semiring/Viterbi.h"
92#include "semiring/MinMax.h"
93#include "semiring/Subset.h"
94#include "semiring/Regex.h"
96#include "semiring/BestPath.h"
97
98const char *drop_temp_table = "DROP TABLE IF EXISTS tmp_uuids;";
99
100namespace {
101
102/**
103 * @brief Wrap a @c std::string in a Postgres @c text Datum.
104 *
105 * Within @c provsql.max_memory, the copy counted, and within what a text
106 * value holds (1 GB): a 54000 error otherwise, not palloc's internal one.
107 */
108Datum text_datum(const std::string &s) {
110 s.size(), "the result is too large to return (over 1 GB): a sub-circuit "
111 "shared by several gates is written out at each of them");
112 provsql_check_memory_for(s.size());
113 text *result = (text *) palloc(VARHDRSZ + s.size());
114 SET_VARSIZE(result, VARHDRSZ + s.size());
115 memcpy(VARDATA(result), s.c_str(), s.size());
116 return PointerGetDatum(result);
117}
118
119// to_datum overloads: encode a semiring's evaluation result as a Postgres Datum.
120Datum to_datum(const semiring::Boolean &, bool v) { return BoolGetDatum(v); }
121Datum to_datum(const semiring::Counting &, unsigned v) {
123 throw CircuitRefusal(
124 PROVSQL_DELIBERATE, "recursion-infinite-count",
125 "This tuple has infinitely many derivations (it is derived "
126 "through a cycle of its recursive query), which an integer "
127 "count cannot represent.");
128 return Int32GetDatum(static_cast<int32>(v));
129}
130Datum to_datum(const semiring::Tropical &, double v) { return Float8GetDatum(v); }
131Datum to_datum(const semiring::Viterbi &, double v) { return Float8GetDatum(v); }
132Datum to_datum(const semiring::Lukasiewicz &, double v) { return Float8GetDatum(v); }
133Datum to_datum(const semiring::Formula &sr, std::string v) { return text_datum(sr.to_text(std::move(v))); }
134Datum to_datum(const semiring::Why &sr, const semiring::why_provenance_t &v) { return text_datum(sr.to_text(v)); }
135Datum to_datum(const semiring::How &sr, const semiring::how_provenance_t &v) { return text_datum(sr.to_text(v)); }
136Datum to_datum(const semiring::Which &sr, const semiring::which_provenance_t &v) { return text_datum(sr.to_text(v)); }
137Datum to_datum(const semiring::Regex &sr, const semiring::regex_t &v) { return text_datum(sr.to_text(v)); }
138#if PG_VERSION_NUM >= 140000
139Datum to_datum(const semiring::IntervalUnion &, Datum v) { return v; }
140#endif
141Datum to_datum(const semiring::MinMax &, Datum v) { return v; }
142Datum to_datum(const semiring::Subset &, uint64_t v) { return Int64GetDatum(static_cast<int64>(v)); }
143
144namespace {
145
146/* Solutions of equation systems (recursive queries lowered by
147 * eval_recursive_system), one Datum per component, under the key
148 * "<context>|<fixpoint token>". The context names the semiring, the
149 * mapping and the result type, and the current command, so that a change
150 * to the mapping in the same transaction is never served a stale value;
151 * the cache lives until the end of the transaction. A query evaluating
152 * every row of a recursive result solves its system once, not once per
153 * row. */
154std::unordered_map<std::string, Datum> fixpoint_cache;
155MemoryContext fixpoint_cache_cxt = nullptr;
156bool fixpoint_cache_callback = false;
157constexpr size_t fixpoint_cache_max = 4000000;
158
159/* Context of the evaluation in progress, empty when not cacheable. */
160std::string fixpoint_cache_ctx;
161int16 fixpoint_cache_typlen;
162bool fixpoint_cache_typbyval;
163
164/* The same, for sr_tropical_paths, whose (cost, paths) results are no
165 * Datum of one type: kept as they are, under the key
166 * "<costs>|<labels>|<command>|<fixpoint token>". */
167std::unordered_map<std::string, std::pair<double, std::string> >
168tropical_paths_cache;
169
170/* The same, for sr_best_path. */
171std::unordered_map<std::string, semiring::best_path_t> best_path_cache;
172
173void fixpoint_cache_clear()
174{
175 fixpoint_cache.clear();
176 tropical_paths_cache.clear();
177 best_path_cache.clear();
178 if(fixpoint_cache_cxt)
179 MemoryContextReset(fixpoint_cache_cxt);
180}
181
182void fixpoint_cache_xact_callback(XactEvent event, void *)
183{
184 if(event == XACT_EVENT_COMMIT || event == XACT_EVENT_ABORT
185 || event == XACT_EVENT_PARALLEL_COMMIT
186 || event == XACT_EVENT_PARALLEL_ABORT
187 || event == XACT_EVENT_PREPARE)
188 fixpoint_cache_clear();
189}
190
191/* Store the solution of every system @p c solved, under the context set
192 * by the caller. */
193template <typename Sem>
194void fixpoint_cache_store(const GenericCircuit &c, const Sem &sr)
195{
196 if(fixpoint_cache_ctx.empty() || c.solved_systems.empty())
197 return;
198 if(!fixpoint_cache_cxt) {
199 fixpoint_cache_cxt = AllocSetContextCreate(TopMemoryContext,
200 "ProvSQL fixpoint cache",
201 ALLOCSET_DEFAULT_SIZES);
202 }
203 if(!fixpoint_cache_callback) {
204 RegisterXactCallback(fixpoint_cache_xact_callback, nullptr);
205 fixpoint_cache_callback = true;
206 }
207 using V = typename Sem::value_type;
208 for(const auto &[sys, p] : c.solved_systems) {
209 const auto &vec = *static_cast<const std::vector<V> *>(p.get());
210 if(fixpoint_cache.size() + vec.size() > fixpoint_cache_max)
211 fixpoint_cache_clear();
212 const std::string prefix = "fixpoint:" + c.getUUID(sys) + ":";
213 for(std::size_t i = 0; i < vec.size(); ++i) {
214 const std::string tok =
215 uuid2string(provsqlUuidV5(prefix + std::to_string(i + 1)));
216 /* A component with no value in the result type (an infinite count)
217 * is not cached: the row reading it is refused on its own. */
218 Datum d;
219 try {
220 d = to_datum(sr, vec[i]);
221 } catch(const CircuitException &) {
222 /* A resource limit stops the evaluation, not just this entry */
224 throw;
225 continue;
226 }
227 MemoryContext old = MemoryContextSwitchTo(fixpoint_cache_cxt);
228 d = datumCopy(d, fixpoint_cache_typbyval, fixpoint_cache_typlen);
229 MemoryContextSwitchTo(old);
230 fixpoint_cache.emplace(fixpoint_cache_ctx + "|" + tok, d);
231 }
232 }
233}
234
235}
236
237/**
238 * @brief Run the four-step compiled-evaluation pipeline for a semiring.
239 *
240 * 1. Build the input-gate → leaf-value mapping by parsing each leaf via
241 * @c sr.parse_leaf().
242 * 2. Rewrite HAVING comparison gates in @p c via @c provsql_having().
243 * 3. Evaluate the main circuit at @p g.
244 * 4. Encode the result as a Postgres Datum via @c to_datum(sr, ...).
245 *
246 * @tparam Sem The compiled semiring class.
247 * @param constants Extension OID cache.
248 * @param c Generic circuit to evaluate.
249 * @param g Root gate.
250 * @param sr Semiring instance.
251 * @param drop_table Whether the temporary UUID table should be dropped.
252 * @return The semiring evaluation result encoded as a Datum.
253 */
254template <typename Sem>
255Datum pec(
256 const constants_t &constants,
258 gate_t g,
259 const Sem &sr,
260 bool drop_table)
261{
262 using V = typename Sem::value_type;
263 std::unordered_map<gate_t, V> mapping;
264 initialize_provenance_mapping<V>(constants, c, mapping,
265 [&sr](const char *v) { return sr.parse_leaf(v); }, drop_table);
266
267 provsql_having(c, g, mapping, sr);
268 c.evaluate<Sem>(g, mapping, sr);
269 /* The result moved out of the values of the gates, not copied */
270 V out = std::move(mapping.at(g));
271 fixpoint_cache_store(c, sr);
272 /* The value of every gate, freed before the result is copied: a
273 * formula's would otherwise hold several times its size. */
274 std::unordered_map<gate_t, V>().swap(mapping);
275 return to_datum(sr, std::move(out));
276}
277
278/**
279 * @brief Evaluate the BoolExpr semiring; bypasses the GenericCircuit pipeline.
280 *
281 * With @p labels, each input gate renders as its mapped label; without,
282 * leaves render as the default @c x@<id@> placeholders.
283 */
284Datum pec_boolexpr(
285 BooleanCircuit &bc,
286 gate_t root,
287 const std::unordered_map<gate_t, std::string> *labels)
288{
289 return text_datum(labels ? bc.toString(root, *labels) : bc.toString(root));
290}
291
292} // namespace
293
294/**
295 * @brief Join a provenance mapping table with a set of UUIDs using SPI.
296 * @param table OID of the provenance mapping relation.
297 * @param uuids List of UUID strings to join against.
298 * @return @c true if a temporary table was created (caller must drop it).
299 */
300bool join_with_temp_uuids(Oid table, const std::vector<std::string> &uuids) {
301 if (SPI_connect() != SPI_OK_CONNECT)
302 throw CircuitException("SPI_connect failed");
303
304 // No mapping given: run an empty join, so the provenance mapping stays
305 // empty and every leaf falls back to the semiring's one (the
306 // absent-mapping convention).
307 if (!OidIsValid(table)) {
308 if (SPI_execute("SELECT ''::text AS value, NULL::uuid AS provenance WHERE false",
309 true, 0) != SPI_OK_SELECT) {
310 SPI_finish();
311 throw CircuitException("Join query failed");
312 }
313 return false;
314 }
315
316 char *table_name = get_rel_name(table);
317 if (!table_name) {
318 SPI_finish();
319 throw CircuitException("Invalid OID: no such table");
320 }
321 // Schema-qualify so the lookup works regardless of search_path.
322 // get_rel_name alone would resolve unqualified, which fails when the
323 // mapping lives in a schema not on search_path (e.g. provsql_test in
324 // the regression DB, or any user schema reached via Studio with the
325 // default "public, provsql" search_path).
326 const char *qualified = quote_qualified_identifier(
327 get_namespace_name(get_rel_namespace(table)), table_name);
328
329 constexpr size_t nb_max_uuid_value = 10000000;
330
331 StringInfoData join_query;
332 initStringInfo(&join_query);
333 bool drop_table = false;
334
335 // The UUIDs as a uuid[] parameter, when there are at most
336 // nb_max_uuid_value of them; a parameter rather than a literal list keeps
337 // the query text short, which is also what an error or a cancellation
338 // reports as its context.
339 Datum uuid_array = (Datum) 0;
340
341 // Two different mechanisms to implement the join (unless there are no
342 // UUIDs):
343 // if there are less than nb_max_uuid_value UUIDs, we join with the
344 // unnested uuid[] parameter;
345 // otherwise we create a temporary table where we dump the inserts
346 // and join with it.
347 if(uuids.size() == 0) {
348 appendStringInfo(&join_query,
349 "SELECT value, provenance FROM %s WHERE 'f'", qualified);
350 } else if(uuids.size() <= nb_max_uuid_value) {
351 pg_uuid_t *values =
352 static_cast<pg_uuid_t *>(palloc(uuids.size() * sizeof(pg_uuid_t)));
353 Datum *elems = static_cast<Datum *>(palloc(uuids.size() * sizeof(Datum)));
354 for(size_t i = 0; i < uuids.size(); ++i) {
355 values[i] = string2uuid(uuids[i]);
356 elems[i] = UUIDPGetDatum(&values[i]);
357 }
358 uuid_array = PointerGetDatum(
359 construct_array(elems, uuids.size(), UUIDOID, UUID_LEN, false,
360 TYPALIGN_CHAR));
361 pfree(elems);
362 pfree(values);
363
364 appendStringInfo(&join_query,
365 "SELECT value, provenance FROM %s t "
366 "JOIN unnest($1) AS u(id) ON t.provenance=u.id",
367 qualified);
368 } else {
369 const char *create_temp_table = "CREATE TEMP TABLE tmp_uuids(id uuid);";
370 if (SPI_exec(create_temp_table, 0) != SPI_OK_UTILITY) {
371 SPI_finish();
372 throw CircuitException("Failed to create temporary table");
373 }
374 drop_table = true;
375
376 constexpr size_t batch_size = 1000;
377
378 for (size_t offset = 0; offset < uuids.size(); offset += batch_size) {
379 StringInfoData insert_query;
380 initStringInfo(&insert_query);
381 appendStringInfo(&insert_query, "INSERT INTO tmp_uuids VALUES ");
382
383 size_t end = std::min(offset + batch_size, uuids.size());
384 for (size_t i = offset; i < end; ++i) {
385 appendStringInfo(&insert_query, "('%s')%s", uuids[i].c_str(), (i + 1 == end) ? "" : ",");
386 }
387
388 int retval=SPI_exec(insert_query.data, 0);
389 pfree(insert_query.data);
390
391 if(retval != SPI_OK_INSERT) {
392 SPI_exec(drop_temp_table, 0);
393 SPI_finish();
394 throw CircuitException("Batch insert into temp table failed");
395 }
396 }
397
398 appendStringInfo(&join_query,
399 "SELECT value, provenance FROM %s t JOIN tmp_uuids u ON t.provenance = u.id", qualified);
400 }
401
402 /* Read-only unless it reads the temporary table just filled: an sr_*
403 * evaluation is PARALLEL SAFE, and a parallel worker can only run a
404 * read-only command. */
405 Oid argtypes[1] = {UUIDARRAYOID};
406 const int ret = uuid_array != (Datum) 0
407 ? SPI_execute_with_args(join_query.data, 1, argtypes, &uuid_array,
408 nullptr, true, 0)
409 : SPI_execute(join_query.data, !drop_table, 0);
410 if (ret != SPI_OK_SELECT) {
411 if(drop_table)
412 SPI_exec(drop_temp_table, 0);
413 SPI_finish();
414 throw CircuitException("Join query failed");
415 }
416
417 return drop_table;
418}
419
420/**
421 * @brief Core implementation of compiled provenance evaluation.
422 * @param token UUID of the root provenance gate.
423 * @param table OID of the provenance mapping relation.
424 * @param semiring Name of the semiring to evaluate over.
425 * @param type OID of the result element type.
426 * @return Datum containing the semiring evaluation result.
427 */
429 (pg_uuid_t token, Oid table, const std::string &semiring, Oid type)
430{
431 constants_t constants = get_constants(true);
432
433 // boolexpr without a mapping has nothing to fetch from SPI: skip the
434 // GenericCircuit build + temp-UUID join and read the BooleanCircuit
435 // directly. Every other case (including boolexpr WITH a mapping)
436 // shares the prelude below.
437 if(semiring=="boolexpr" && !OidIsValid(table)) {
438 gate_t root;
439 BooleanCircuit bc = getBooleanCircuit(token, root);
440 return pec_boolexpr(bc, root, nullptr);
441 }
442
443 // The expectation evaluator reads its leaves directly from the
444 // gate_rv / gate_value extra fields; no leaf-mapping table is
445 // involved. Bypass the SPI prelude.
446 if(semiring=="expectation") {
447 if(type != constants.OID_TYPE_FLOAT)
448 throw CircuitException(
449 "Unknown element type for expectation: must be float8");
452 auto root = gc.getGate(uuid2string(token));
453 return Float8GetDatum(provsql::compute_expectation(gc, root));
454 }
455
456 /* A component of an equation system solved earlier in this command,
457 * under the same semiring and mapping: no circuit to load. */
458 fixpoint_cache_ctx = semiring + "|" + std::to_string(table) + "|" +
459 std::to_string(type) + "|" +
460 std::to_string(GetCurrentCommandId(false));
461 /* The subset semirings answer a bigint bitmask, whatever the enum type of
462 * the sample element that selects them. */
463 if(semiring == "subset" || semiring == "clearance" || semiring == "consent")
464 get_typlenbyval(INT8OID, &fixpoint_cache_typlen, &fixpoint_cache_typbyval);
465 else
466 get_typlenbyval(type, &fixpoint_cache_typlen, &fixpoint_cache_typbyval);
467 {
468 auto it = fixpoint_cache.find(fixpoint_cache_ctx + "|" + uuid2string(token));
469 if(it != fixpoint_cache.end())
470 return datumCopy(it->second, fixpoint_cache_typbyval,
471 fixpoint_cache_typlen);
472 }
473
475 auto g = c.getGate(uuid2string(token));
476 bool drop_table = join_with_temp_uuids(table, c.getMappableUUIDs());
477
478 if(semiring=="boolexpr") {
479 // boolexpr with a mapping: build the gate-to-label map on the
480 // GenericCircuit (the mapping table is keyed by input UUIDs that
481 // don't survive translation to BooleanCircuit gate ids), then
482 // translate keys to bc gates via gc_to_bc so bc.toString can label
483 // each leaf with its mapped value.
484 gate_t root;
485 std::unordered_map<gate_t, std::string> gc_labels;
486 initialize_provenance_mapping<std::string>(constants, c, gc_labels, [](const char *v) {
487 return std::string(v);
488 }, drop_table);
489
490 std::unordered_map<gate_t, gate_t> gc_to_bc;
491 BooleanCircuit bc = getBooleanCircuit(c, token, root, gc_to_bc);
492
493 std::unordered_map<gate_t, std::string> bc_labels;
494 bc_labels.reserve(gc_labels.size());
495 for(const auto &kv : gc_labels) {
496 auto it = gc_to_bc.find(kv.first);
497 if(it != gc_to_bc.end())
498 bc_labels[it->second] = kv.second;
499 }
500 return pec_boolexpr(bc, root, &bc_labels);
501 }
502
503 if (type == constants.OID_TYPE_VARCHAR)
504 {
505 if (semiring == "formula") return pec(constants, c, g, semiring::Formula{}, drop_table);
506 if (semiring == "why") return pec(constants, c, g, semiring::Why{}, drop_table);
507 if (semiring == "how") return pec(constants, c, g, semiring::How{}, drop_table);
508 if (semiring == "which") return pec(constants, c, g, semiring::Which{}, drop_table);
509 if (semiring == "regex") return pec(constants, c, g, semiring::Regex{}, drop_table);
510 throw CircuitException("Unknown semiring for type varchar: " + semiring);
511 }
512 if (type == constants.OID_TYPE_INT) {
513 if (semiring == "counting") return pec(constants, c, g, semiring::Counting{}, drop_table);
514 throw CircuitException("Unknown semiring for type int: " + semiring);
515 }
516 if (type == constants.OID_TYPE_FLOAT) {
517 if (semiring == "tropical") return pec(constants, c, g, semiring::Tropical{}, drop_table);
518 if (semiring == "tropical_nonneg")
519 return pec(constants, c, g, semiring::TropicalNonneg{}, drop_table);
520 if (semiring == "viterbi") return pec(constants, c, g, semiring::Viterbi{}, drop_table);
521 if (semiring == "lukasiewicz") return pec(constants, c, g, semiring::Lukasiewicz{}, drop_table);
522 throw CircuitException("Unknown semiring for type float: " + semiring);
523 }
524 if (type == constants.OID_TYPE_BOOL) {
525 if (semiring == "boolean") return pec(constants, c, g, semiring::Boolean{}, drop_table);
526 throw CircuitException("Unknown semiring for type bool: " + semiring);
527 }
528#if PG_VERSION_NUM >= 140000
529 if (type == constants.OID_TYPE_TSTZMULTIRANGE) {
530 if (semiring != "temporal" && semiring != "interval_union")
531 throw CircuitException("Unknown semiring for type tstzmultirange: " + semiring);
532 return pec(constants, c, g, semiring::IntervalUnion(constants.OID_TYPE_TSTZMULTIRANGE), drop_table);
533 }
534 if (type == constants.OID_TYPE_NUMMULTIRANGE) {
535 if (semiring != "interval_union")
536 throw CircuitException("Unknown semiring for type nummultirange: " + semiring);
537 return pec(constants, c, g, semiring::IntervalUnion(constants.OID_TYPE_NUMMULTIRANGE), drop_table);
538 }
539 if (type == constants.OID_TYPE_INT4MULTIRANGE) {
540 if (semiring != "interval_union")
541 throw CircuitException("Unknown semiring for type int4multirange: " + semiring);
542 return pec(constants, c, g, semiring::IntervalUnion(constants.OID_TYPE_INT4MULTIRANGE), drop_table);
543 }
544#endif
545 if (get_typtype(type) == TYPTYPE_ENUM) {
546 if (semiring == "minmax") return pec(constants, c, g, semiring::MinMax(type, false), drop_table);
547 if (semiring == "maxmin") return pec(constants, c, g, semiring::MinMax(type, true), drop_table);
548 if (semiring == "subset")
549 return pec(constants, c, g, semiring::Subset(type, semiring::Subset::Mode::SUBSET), drop_table);
550 if (semiring == "clearance")
551 return pec(constants, c, g, semiring::Subset(type, semiring::Subset::Mode::CLEARANCE), drop_table);
552 if (semiring == "consent")
553 return pec(constants, c, g, semiring::Subset(type, semiring::Subset::Mode::CONSENT), drop_table);
554 throw CircuitException("Unknown semiring for enum type: " + semiring);
555 }
556 throw CircuitException("Unknown element type for provenance_evaluate_compiled");
557}
558
559/**
560 * @brief Min-cost derivations of @p token and the derivations of that cost
561 * (@c semiring::TropicalPaths), each leaf with its cost from
562 * @p costs and its label from @p labels.
563 *
564 * An input missing from @p costs costs 0, one missing from @p labels is
565 * the empty word.
566 *
567 * @return The cost (@f$+\infty@f$ with no derivation) and the derivations,
568 * as a regular expression.
569 */
570static std::pair<double, std::string> tropical_paths_internal
571 (pg_uuid_t token, Oid costs, Oid labels)
572{
573 constants_t constants = get_constants(true);
574 fixpoint_cache_ctx.clear();
575
576 /* A component of an equation system solved earlier in this command,
577 * with the same mappings: no circuit to load. */
578 const std::string ctx = std::to_string(costs) + "|" +
579 std::to_string(labels) + "|" +
580 std::to_string(GetCurrentCommandId(false));
581 {
582 auto it = tropical_paths_cache.find(ctx + "|" + uuid2string(token));
583 if(it != tropical_paths_cache.end())
584 return it->second;
585 }
586
588 auto g = c.getGate(uuid2string(token));
589 const std::vector<std::string> inputs_uuid = c.getMappableUUIDs();
590
591 std::unordered_map<gate_t, double> cost;
592 initialize_provenance_mapping<double>(constants, c, cost,
593 [](const char *v) { return atof(v); },
594 join_with_temp_uuids(costs, inputs_uuid));
595 std::unordered_map<gate_t, std::string> label;
597 [](const char *v) { return std::string(v); },
598 join_with_temp_uuids(labels, inputs_uuid));
599
601 std::unordered_map<gate_t, semiring::tropical_paths_t> mapping;
602 std::set<gate_t> leaves(c.getInputs());
603 for(const auto &kv : cost)
604 leaves.insert(kv.first);
605 for(const auto &kv : label)
606 leaves.insert(kv.first);
607 for(auto x : leaves) {
608 auto ic = cost.find(x);
609 auto il = label.find(x);
610 mapping[x] = semiring::tropical_paths_t{
611 ic == cost.end() ? 0. : ic->second,
612 semiring::regex_ops::atom(il == label.end() ? "" : il->second)};
613 }
614
615 provsql_having(c, g, mapping, sr);
616 const auto out = c.evaluate<semiring::TropicalPaths>(g, mapping, sr);
617
618 if(!c.solved_systems.empty() && !fixpoint_cache_callback) {
619 RegisterXactCallback(fixpoint_cache_xact_callback, nullptr);
620 fixpoint_cache_callback = true;
621 }
622 for(const auto &[sys, p] : c.solved_systems) {
623 const auto &vec =
624 *static_cast<const std::vector<semiring::tropical_paths_t> *>(p.get());
625 if(tropical_paths_cache.size() + vec.size() > fixpoint_cache_max)
626 tropical_paths_cache.clear();
627 const std::string prefix = "fixpoint:" + c.getUUID(sys) + ":";
628 for(std::size_t i = 0; i < vec.size(); ++i)
629 tropical_paths_cache.emplace(
630 ctx + "|" +
631 uuid2string(provsqlUuidV5(prefix + std::to_string(i + 1))),
632 std::make_pair(vec[i].cost, vec[i].paths.render()));
633 }
634
635 return {out.cost, out.paths.render()};
636}
637
638/** @brief PostgreSQL-callable wrapper for tropical_paths_internal(). */
640{
641 if (PG_ARGISNULL(0))
642 PG_RETURN_NULL();
643
644 try {
645 provsql_interrupt_scope interrupt_scope;
646 const Oid costs = PG_ARGISNULL(1) ? InvalidOid : PG_GETARG_OID(1);
647 const Oid labels = PG_ARGISNULL(2) ? InvalidOid : PG_GETARG_OID(2);
648 const auto [cost, paths] =
649 tropical_paths_internal(*DatumGetUUIDP(PG_GETARG_DATUM(0)), costs, labels);
650
651 TupleDesc tupdesc;
652 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
653 throw CircuitException("tropical paths must return a record");
654 tupdesc = BlessTupleDesc(tupdesc);
655 Datum values[2] = {Float8GetDatum(cost), text_datum(paths)};
656 bool nulls[2] = {false, false};
657 PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
658 } catch(const CircuitRefusal &r) {
660 provsql_unsupported(r.scope(), r.tag(), "%s", r.what());
661 } catch(const std::exception &e) {
663 provsql_error("provenance_evaluate_tropical_paths: %s", e.what());
664 } catch(...) {
666 provsql_error("provenance_evaluate_tropical_paths: Unknown exception");
667 }
668
669 PG_RETURN_NULL();
670}
671
672/**
673 * @brief A least-cost derivation of @p token (@c semiring::BestPath), each
674 * leaf with its cost from @p costs and its label from @p labels.
675 *
676 * An input missing from @p costs costs 0, one missing from @p labels is
677 * the empty word.
678 *
679 * @return The cost (@f$+\infty@f$ with no derivation) and the labels of
680 * the derivation, in order.
681 */
683 (pg_uuid_t token, Oid costs, Oid labels)
684{
685 constants_t constants = get_constants(true);
686 fixpoint_cache_ctx.clear();
687
688 /* A component of an equation system solved earlier in this command,
689 * with the same mappings: no circuit to load. */
690 const std::string ctx = std::to_string(costs) + "|" +
691 std::to_string(labels) + "|" +
692 std::to_string(GetCurrentCommandId(false));
693 {
694 auto it = best_path_cache.find(ctx + "|" + uuid2string(token));
695 if(it != best_path_cache.end())
696 return it->second;
697 }
698
700 auto g = c.getGate(uuid2string(token));
701 const std::vector<std::string> inputs_uuid = c.getMappableUUIDs();
702
703 std::unordered_map<gate_t, double> cost;
704 initialize_provenance_mapping<double>(constants, c, cost,
705 [](const char *v) { return atof(v); },
706 join_with_temp_uuids(costs, inputs_uuid));
707 std::unordered_map<gate_t, std::string> label;
709 [](const char *v) { return std::string(v); },
710 join_with_temp_uuids(labels, inputs_uuid));
711
713 std::unordered_map<gate_t, semiring::best_path_t> mapping;
714 std::set<gate_t> leaves(c.getInputs());
715 for(const auto &kv : cost)
716 leaves.insert(kv.first);
717 for(const auto &kv : label)
718 leaves.insert(kv.first);
719 for(auto x : leaves) {
720 auto ic = cost.find(x);
721 auto il = label.find(x);
722 mapping[x] = semiring::BestPath::leaf(
723 ic == cost.end() ? 0. : ic->second,
724 il == label.end() ? nullptr : &il->second);
725 }
726
727 provsql_having(c, g, mapping, sr);
728 const auto out = c.evaluate<semiring::BestPath>(g, mapping, sr);
729
730 if(!c.solved_systems.empty() && !fixpoint_cache_callback) {
731 RegisterXactCallback(fixpoint_cache_xact_callback, nullptr);
732 fixpoint_cache_callback = true;
733 }
734 for(const auto &[sys, p] : c.solved_systems) {
735 const auto &vec =
736 *static_cast<const std::vector<semiring::best_path_t> *>(p.get());
737 if(best_path_cache.size() + vec.size() > fixpoint_cache_max)
738 best_path_cache.clear();
739 const std::string prefix = "fixpoint:" + c.getUUID(sys) + ":";
740 for(std::size_t i = 0; i < vec.size(); ++i)
741 best_path_cache.emplace(
742 ctx + "|" +
743 uuid2string(provsqlUuidV5(prefix + std::to_string(i + 1))),
744 vec[i]);
745 }
746
747 return out;
748}
749
750/** @brief PostgreSQL-callable wrapper for best_path_internal(). */
751Datum provenance_evaluate_best_path(PG_FUNCTION_ARGS)
752{
753 if (PG_ARGISNULL(0))
754 PG_RETURN_NULL();
755
756 try {
757 provsql_interrupt_scope interrupt_scope;
758 const Oid costs = PG_ARGISNULL(1) ? InvalidOid : PG_GETARG_OID(1);
759 const Oid labels = PG_ARGISNULL(2) ? InvalidOid : PG_GETARG_OID(2);
760 const semiring::best_path_t out =
761 best_path_internal(*DatumGetUUIDP(PG_GETARG_DATUM(0)), costs, labels);
762
763 TupleDesc tupdesc;
764 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
765 throw CircuitException("best path must return a record");
766 tupdesc = BlessTupleDesc(tupdesc);
767 Datum values[2] = {Float8GetDatum(out.cost), (Datum)0};
768 bool nulls[2] = {false, out.is_zero()};
769 if(!out.is_zero()) {
770 std::vector<Datum> elems;
771 for(const auto &l : out.word)
772 elems.push_back(text_datum(l));
773 values[1] = PointerGetDatum(
774 construct_array(elems.data(), elems.size(), TEXTOID, -1, false,
775 TYPALIGN_INT));
776 }
777 PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
778 } catch(const CircuitRefusal &r) {
780 provsql_unsupported(r.scope(), r.tag(), "%s", r.what());
781 } catch(const std::exception &e) {
783 provsql_error("provenance_evaluate_best_path: %s", e.what());
784 } catch(...) {
786 provsql_error("provenance_evaluate_best_path: Unknown exception");
787 }
788
789 PG_RETURN_NULL();
790}
791
792/** @brief PostgreSQL-callable wrapper for provenance_evaluate_compiled(). */
793Datum provenance_evaluate_compiled(PG_FUNCTION_ARGS)
794{
795 /* The sr_* SQL wrappers are STRICT, but the function itself is not:
796 * guard the required arguments rather than rely on the wrappers. The
797 * mapping (argument 1) is legitimately NULL -- the no-mapping mode
798 * renders anonymous leaves -- and reads as InvalidOid below. */
799 if (PG_ARGISNULL(0) || PG_ARGISNULL(2))
800 PG_RETURN_NULL();
801
802 try {
803 provsql_interrupt_scope interrupt_scope;
804 Datum token = PG_GETARG_DATUM(0);
805
806 Oid table = PG_GETARG_OID(1);
807
808 text *t = PG_GETARG_TEXT_P(2);
809 std::string semiring(VARDATA(t),VARSIZE(t)-VARHDRSZ);
810
811 Oid type = get_fn_expr_argtype(fcinfo->flinfo, 3);
812
813 return provenance_evaluate_compiled_internal(*DatumGetUUIDP(token), table, semiring, type);
814 } catch(const provsql::NoValueException &) {
815 /* An expectation defined in no world: SQL's NULL. */
817 PG_RETURN_NULL();
818 } catch(const CircuitRefusal &r) {
820 provsql_unsupported(r.scope(), r.tag(), "%s", r.what());
821 } catch(const std::exception &e) {
823 provsql_error("provenance_evaluate_compiled: %s", e.what());
824 } catch(...) {
826 provsql_error("provenance_evaluate_compiled: Unknown exception");
827 }
828
829 PG_RETURN_NULL();
830}
831
832namespace {
833
834/** Truth of the gates already met, in the database as it is: a gate never
835 * changes once created, nor does an input tuple's presence for the rows
836 * that read it. Bounded, so that a long session does not grow it forever. */
837std::unordered_map<std::string, bool> plain_truth_memo;
838constexpr size_t plain_truth_memo_max = 1000000;
839
840/** 1 / 0 for a gate whose truth follows from its type and its children's,
841 * -1 for one that needs the full evaluation (a comparison, ...). */
842int quick_plain_truth(const pg_uuid_t &token, unsigned depth)
843{
844 std::string key = uuid2string(token);
845 auto it = plain_truth_memo.find(key);
846 if (it != plain_truth_memo.end())
847 return it->second;
848 if (depth > 64)
849 return -1;
850
851 unsigned nb_children = 0;
852 pg_uuid_t *children = NULL;
853 gate_type type = provsql_fetch_gate(&token, &nb_children, &children);
854 int res = -1;
855
856 switch (type) {
857 case gate_input: case gate_mulinput: case gate_one:
858 res = 1;
859 break;
860 case gate_zero:
861 res = 0;
862 break;
863 case gate_times: case gate_plus: {
864 bool is_times = type == gate_times;
865 res = is_times ? 1 : 0;
866 for (unsigned i = 0; i < nb_children; ++i) {
867 int c = quick_plain_truth(children[i], depth + 1);
868 if (c < 0) { res = -1; break; }
869 if (is_times && !c) { res = 0; break; }
870 if (!is_times && c) { res = 1; break; }
871 }
872 break;
873 }
874 case gate_monus:
875 if (nb_children == 2) {
876 int a = quick_plain_truth(children[0], depth + 1);
877 int b = a == 1 ? quick_plain_truth(children[1], depth + 1) : 0;
878 res = a < 0 || b < 0 ? -1 : (a && !b);
879 }
880 break;
881 case gate_delta: case gate_project: case gate_eq: case gate_annotation:
882 case gate_assumed:
883 if (nb_children >= 1)
884 res = quick_plain_truth(children[0], depth + 1);
885 break;
886 case gate_cmp: {
887 /* A comparison of aggregate results holds, in the database as it is, by
888 * the values its sides record there: agg_guard_holds reads them off the
889 * gates. Deciding it that way rather than over the Boolean semiring
890 * matters, not merely for speed: the semiring reads a comparison through
891 * the worlds of what it aggregates, which is 2^n terms for n
892 * contributions, so a comparison over a few dozen rows -- one per row an
893 * exploded aggregate value produces -- would not finish. A comparison
894 * whose sides record no value (a random variable, a text aggregate)
895 * yields NULL and takes the evaluation below. */
896 constants_t constants = get_constants(false);
897 if (!constants.ok || !OidIsValid(constants.OID_FUNCTION_AGG_GUARD_HOLDS))
898 break;
899 {
900 FmgrInfo flinfo;
901 /* PostgreSQL 12 made the argument array variable-length, and with it
902 * LOCAL_FCINFO and fcinfo->args[]; before that the call info is a plain
903 * struct with fixed arg / argnull arrays. */
904#if PG_VERSION_NUM >= 120000
905 LOCAL_FCINFO(fcinfo, 1);
906#else
907 FunctionCallInfoData fcinfo_data;
908 FunctionCallInfo fcinfo = &fcinfo_data;
909#endif
910 Datum d;
911
912 fmgr_info(constants.OID_FUNCTION_AGG_GUARD_HOLDS, &flinfo);
913 InitFunctionCallInfoData(*fcinfo, &flinfo, 1, InvalidOid, NULL, NULL);
914#if PG_VERSION_NUM >= 120000
915 fcinfo->args[0].value = UUIDPGetDatum(&token);
916 fcinfo->args[0].isnull = false;
917#else
918 fcinfo->arg[0] = UUIDPGetDatum(&token);
919 fcinfo->argnull[0] = false;
920#endif
921 d = FunctionCallInvoke(fcinfo);
922 if (!fcinfo->isnull)
923 res = DatumGetBool(d) ? 1 : 0;
924 }
925 break;
926 }
927 default:
928 break;
929 }
930 free(children);
931
932 if (res >= 0) {
933 if (plain_truth_memo.size() >= plain_truth_memo_max)
934 plain_truth_memo.clear();
935 plain_truth_memo.emplace(std::move(key), res == 1);
936 }
937 return res;
938}
939
940} // namespace
941
942/**
943 * @brief Whether a token holds in the database as it is, every input tuple
944 * present: @c sr_boolean without a mapping.
945 *
946 * The rewriter filters by it the rows a displayed aggregate value reads, so
947 * that the value is what plain SQL computes on the same data: a row kept only
948 * for its provenance (the padding of a lowered outer join, a group a
949 * @c HAVING rejects, a row beyond a rank-filtered @c LIMIT) does not count.
950 * Gates whose truth follows from their children's (⊗, ⊕, ⊖, δ, ...) are
951 * walked directly, through the backend's gate cache; a comparison is left to
952 * the evaluation over the Boolean semiring, with no mapping to read.
953 */
954Datum plain_truth(PG_FUNCTION_ARGS)
955{
956 pg_uuid_t token;
957
958 if (PG_ARGISNULL(0))
959 PG_RETURN_BOOL(true);
960 token = *PG_GETARG_UUID_P(0);
961
962 int quick = quick_plain_truth(token, 0);
963 if (quick >= 0)
964 PG_RETURN_BOOL(quick == 1);
965
966 /* A token the Boolean semiring cannot evaluate (a comparison on a random
967 * variable, which has no value in the database as it is) holds: the row
968 * counts, as it did before this filter. */
969 bool res = true;
970 try {
971 provsql_interrupt_scope interrupt_scope;
973 gate_t g = c.getGate(uuid2string(token));
975 std::unordered_map<gate_t, bool> mapping;
976 provsql_having(c, g, mapping, sr);
977 res = c.evaluate<semiring::Boolean>(g, mapping, sr);
978 /* An equation system met on the way was solved whole: record the
979 * truth of each of its components, so that the other rows of the same
980 * recursive result, which the rewriter checks one by one, do not load
981 * and solve it again. */
982 for(const auto &[sys, p] : c.solved_systems) {
983 const auto &vec = *static_cast<const std::vector<bool> *>(p.get());
984 if(plain_truth_memo.size() + vec.size() >= plain_truth_memo_max)
985 plain_truth_memo.clear();
986 const std::string prefix = "fixpoint:" + c.getUUID(sys) + ":";
987 for(std::size_t i = 0; i < vec.size(); ++i)
988 plain_truth_memo.emplace(
989 uuid2string(provsqlUuidV5(prefix + std::to_string(i + 1))), vec[i]);
990 }
991 } catch(const std::exception &) {
993 res = true;
994 }
995 if (plain_truth_memo.size() >= plain_truth_memo_max)
996 plain_truth_memo.clear();
997 plain_truth_memo.emplace(uuid2string(token), res);
998 PG_RETURN_BOOL(res);
999}
1000
1001/**
1002 * @brief The labels a subset bitmask holds, as an array of the enum type of
1003 * @p element_one, in @c enumsortorder.
1004 *
1005 * Bits above the last label (the unrestricted element of the consent
1006 * semiring) are ignored.
1007 */
1008Datum subset_labels(PG_FUNCTION_ARGS)
1009{
1010 /* Not STRICT: the enum argument is read for its type only, and may be
1011 * NULL. */
1012 if(PG_ARGISNULL(0))
1013 PG_RETURN_NULL();
1014 uint64_t mask = static_cast<uint64_t>(PG_GETARG_INT64(0));
1015 Oid enum_oid = get_fn_expr_argtype(fcinfo->flinfo, 1);
1016 semiring::EnumLabels labels(enum_oid);
1017 std::vector<Datum> elems;
1018 for(std::size_t i = 0; i < labels.oids.size() && i < 63; ++i)
1019 if(mask & (uint64_t(1) << i))
1020 elems.push_back(ObjectIdGetDatum(labels.oids[i]));
1021 int16 typlen;
1022 bool typbyval;
1023 char typalign;
1024 get_typlenbyvalalign(enum_oid, &typlen, &typbyval, &typalign);
1025 PG_RETURN_ARRAYTYPE_P(construct_array(elems.data(), elems.size(), enum_oid,
1026 typlen, typbyval, typalign));
1027}
1028
1029/**
1030 * @brief The settling level of a set of clearance levels: the lowest level
1031 * from which membership no longer changes up to the top level.
1032 *
1033 * Settledness is upward-closed, so it always exists; the membership it
1034 * settles to is that of the top level.
1035 */
1036Datum subset_settling(PG_FUNCTION_ARGS)
1037{
1038 /* Not STRICT: the enum argument is read for its type only, and may be
1039 * NULL. */
1040 if(PG_ARGISNULL(0))
1041 PG_RETURN_NULL();
1042 uint64_t mask = static_cast<uint64_t>(PG_GETARG_INT64(0));
1043 semiring::EnumLabels labels(get_fn_expr_argtype(fcinfo->flinfo, 1));
1044 std::size_t n = labels.oids.size();
1045 if(n == 0 || n > 63)
1046 provsql_error("subset_settling: an enum type of 1 to 63 labels is required");
1047 bool top = mask & (uint64_t(1) << (n - 1));
1048 std::size_t l = n - 1;
1049 while(l > 0 && static_cast<bool>(mask & (uint64_t(1) << (l - 1))) == top)
1050 --l;
1051 PG_RETURN_OID(labels.oids[l]);
1052}
1053
1054/**
1055 * @brief Membership of a label, given as text, in the subset annotation of
1056 * a token: the predicate behind @c visible_at and @c consented_for.
1057 *
1058 * The enum type is that of the mapping table's @c value column (or the
1059 * element type of an array column), so that the caller writes the label as
1060 * a plain string. In @c consent mode, a purpose holds only where the
1061 * unrestricted element does too.
1062 */
1063Datum subset_member(PG_FUNCTION_ARGS)
1064{
1065 if(PG_ARGISNULL(0) || PG_ARGISNULL(1) || PG_ARGISNULL(2) || PG_ARGISNULL(3))
1066 PG_RETURN_NULL();
1067 pg_uuid_t token = *PG_GETARG_UUID_P(0);
1068 Oid table = PG_GETARG_OID(1);
1069 text *m = PG_GETARG_TEXT_P(2);
1070 std::string mode(VARDATA(m), VARSIZE(m) - VARHDRSZ);
1071 char *label_text = text_to_cstring(PG_GETARG_TEXT_P(3));
1072
1073 AttrNumber att = get_attnum(table, "value");
1074 if(att == InvalidAttrNumber)
1075 provsql_error("%s: the mapping has no column named value",
1076 mode == "consent" ? "consented_for" : "visible_at");
1077 Oid coltype = get_atttype(table, att);
1078 Oid elemtype = get_element_type(coltype);
1079 Oid enum_oid = OidIsValid(elemtype) ? elemtype : coltype;
1080 if(get_typtype(enum_oid) != TYPTYPE_ENUM)
1081 provsql_error("%s: the value column of the mapping is not of an enum type",
1082 mode == "consent" ? "consented_for" : "visible_at");
1083
1084 Oid in_func, typioparam;
1085 getTypeInputInfo(enum_oid, &in_func, &typioparam);
1086 Oid label = DatumGetObjectId(OidInputFunctionCall(in_func, label_text,
1087 typioparam, -1));
1088 semiring::EnumLabels labels(enum_oid);
1089 uint64_t bit = uint64_t(1) << labels.rank.at(label);
1090
1091 uint64_t mask = 0;
1092 try {
1093 provsql_interrupt_scope interrupt_scope;
1094 mask = static_cast<uint64_t>(DatumGetInt64(
1095 provenance_evaluate_compiled_internal(token, table, mode, enum_oid)));
1096 } catch(const CircuitRefusal &r) {
1098 provsql_unsupported(r.scope(), r.tag(), "%s", r.what());
1099 } catch(const std::exception &e) {
1101 provsql_error("subset_member: %s", e.what());
1102 }
1103 if(mode == "consent")
1104 PG_RETURN_BOOL((mask & bit) && (mask & semiring::Subset::UNRESTRICTED));
1105 PG_RETURN_BOOL(mask & bit);
1106}
1107
1108namespace {
1109
1110/**
1111 * @brief The rows of @c sr_formula_rows, produced one at a time.
1112 *
1113 * The circuit is not loaded whole: each row is written from its region,
1114 * the gates below its own down to the named ones, which the store answers
1115 * (@c FormulaRegions); the rows of the children of a wide gate are asked
1116 * for @c BATCH at a time. A row thus costs what it writes, and the memory
1117 * used does not depend on the size of the circuit.
1118 *
1119 * The size of a formula is counted in symbols, a gate for one, written out
1120 * at each use, a named descendant for one. A gate of more than
1121 * @c max_size is named (@c #1, @c #2, ...), the root always; its row is
1122 * written with its named descendants as their names. A named gate whose
1123 * row would still exceed @c SLACK times @c max_size (a sum of millions of
1124 * small contributions) is summarised in its row, each child given a row of
1125 * its own (@c #k.1, @c #k.2, ...).
1126 *
1127 * The comparisons on aggregates in a region are written as @c sr_formula
1128 * writes them where that fits in a row, as they are otherwise (see
1129 * @c expand_comparisons).
1130 */
1131class FormulaRows {
1132 constants_t constants;
1133 Oid table;
1134 std::size_t max_size;
1135 /** Names of the named gates met so far, by UUID */
1136 std::unordered_map<std::string, std::string> names;
1137 std::size_t next_name = 1;
1138 /** A gate's own row (@c child unset), or the row of the child of a wide
1139 * gate at position @c child, out of @c nb */
1140 struct Item {
1141 std::string uuid;
1142 std::size_t child;
1143 std::size_t nb;
1144 };
1145 static constexpr std::size_t OWN = std::numeric_limits<std::size_t>::max();
1146 /** How much longer than @c max_size the row of a named gate may be
1147 * before it is split into one row per child */
1148 static constexpr std::size_t SLACK = 4;
1149 /** Rows of the children of a wide gate asked for at once */
1150 static constexpr std::size_t BATCH = 4096;
1151 std::deque<Item> todo;
1152
1153 /** A loaded region, with the values of its leaves and of its expanded
1154 * comparisons */
1155 struct Region {
1156 FormulaRegions r;
1157 std::unordered_map<gate_t, std::string> base;
1158 std::unordered_set<std::string> stubs;
1159 };
1160 /** The children of the wide gate being written, @c batch_from onwards */
1161 Region batch;
1162 std::size_t batch_from = 0;
1163 bool batch_loaded = false;
1164
1165 /** Thrown by @c CappedFormula past its cap */
1166 struct TooLarge {};
1167 /** @c Formula, refusing a value longer than @c cap */
1168 class CappedFormula : public semiring::Formula {
1169 std::size_t cap;
1170 std::string check(std::string v) const {
1171 if(v.size() > cap)
1172 throw TooLarge();
1173 return v;
1174 }
1175public:
1176 explicit CappedFormula(std::size_t cap) : cap(cap) {}
1177 value_type plus(const std::vector<value_type> &v) const override {
1178 return check(Formula::plus(v));
1179 }
1180 value_type times(const std::vector<value_type> &v) const override {
1181 return check(Formula::times(v));
1182 }
1183 value_type plus_of(const std::vector<const value_type *> &v) const override {
1184 return check(Formula::plus_of(v));
1185 }
1186 value_type times_of(const std::vector<const value_type *> &v) const override {
1187 return check(Formula::times_of(v));
1188 }
1189 value_type monus(value_type x, value_type y) const override {
1190 return check(Formula::monus(std::move(x), std::move(y)));
1191 }
1192 };
1193
1194 /* The number of contributors to the aggregates the comparison @p g
1195 * reads */
1196 static std::size_t contributors(const GenericCircuit &c, gate_t g) {
1197 std::size_t k = 0;
1198 std::unordered_set<gate_t> seen;
1199 std::vector<gate_t> stack(c.getWires(g).begin(), c.getWires(g).end());
1200 while(!stack.empty()) {
1201 const gate_t u = stack.back();
1202 stack.pop_back();
1203 if(!seen.insert(u).second)
1204 continue;
1205 if(c.getGateType(u) == gate_agg)
1206 k += c.getWires(u).size();
1207 else
1208 for(const auto w : c.getWires(u))
1209 stack.push_back(w);
1210 }
1211 return k;
1212 }
1213
1214 /* The comparisons on aggregates below @p root written as sr_formula
1215 * writes them, a sum over the possible worlds of each group, unless that
1216 * sum could be longer than a row: they are then written as they are, the
1217 * sum being exponential in the size of the group. The worlds are
1218 * enumerated before any of the sum is written, so the expansion is tried
1219 * only when there are few enough of them; and it is given up, the region
1220 * restored, as soon as a value of it is longer than a row. A comparison
1221 * whose aggregate is a named gate, not in the region, is not expanded. */
1222 void expand_comparisons(Region &g, gate_t root) {
1223 GenericCircuit &c = g.r.circuit;
1224 const auto cmps = provsql_having_detail::collect_sp_cmp_gates(c, root);
1225 if(cmps.empty())
1226 return;
1227 /* A row of max_size symbols, at a few bytes each */
1228 const std::size_t cap = 8 * SLACK * max_size;
1229 std::size_t k = 0;
1230 for(const auto x : cmps)
1231 k += contributors(c, x);
1232 if(k >= 8 * sizeof(std::size_t) || (std::size_t(1) << k) > cap
1233 || (provsql_max_worlds > 0
1234 && (std::size_t(1) << k) > (std::size_t) provsql_max_worlds))
1235 return;
1236 GenericCircuit saved_circuit = c;
1237 auto saved_base = g.base;
1238 try {
1239 provsql_having(c, root, g.base, CappedFormula(cap));
1240 } catch(const TooLarge &) {
1241 c = std::move(saved_circuit);
1242 g.base = std::move(saved_base);
1243 }
1244 }
1245
1246 /* Ask the store for @p q, and read the labels of the leaves */
1247 void load(Region &g, const FormulaRequest &q) {
1248 g.r = getFormulaRegions({q}, max_size, SLACK * max_size);
1249 g.base.clear();
1250 g.stubs.clear();
1251 for(const auto &s : g.r.stubs)
1252 g.stubs.insert(s.uuid);
1253 const bool drop_table =
1254 join_with_temp_uuids(table, g.r.circuit.getMappableUUIDs());
1255 semiring::Formula sr;
1256 initialize_provenance_mapping<std::string>(constants, g.r.circuit, g.base,
1257 [&sr](const char *v) { return sr.parse_leaf(v); }, drop_table);
1258 }
1259
1260 /* The name of a named gate, given when first met, its row then queued */
1261 const std::string &name_of(const std::string &uuid) {
1262 auto it = names.find(uuid);
1263 if(it == names.end()) {
1264 it = names.emplace(uuid, "#" + std::to_string(next_name++)).first;
1265 todo.push_back({uuid, OWN, 0});
1266 }
1267 return it->second;
1268 }
1269
1270 /* The formula of @p g in its region, the named gates read as names */
1271 std::string render(Region &reg, gate_t g) {
1272 GenericCircuit &c = reg.r.circuit;
1273 semiring::Formula sr;
1274 const std::string gu = c.getUUID(g);
1275 if(reg.stubs.count(gu))
1276 return name_of(gu);
1277 auto b = reg.base.find(g);
1278 if(b != reg.base.end())
1279 return sr.to_text(b->second);
1280 std::unordered_map<gate_t, std::string> m;
1281 std::unordered_set<gate_t> seen{g};
1282 std::vector<gate_t> stack;
1283 const auto &w = c.getWires(g);
1284 for(auto it = w.rbegin(); it != w.rend(); ++it)
1285 stack.push_back(*it);
1286 while(!stack.empty()) {
1288 const gate_t u = stack.back();
1289 stack.pop_back();
1290 if(!seen.insert(u).second)
1291 continue;
1292 const std::string uu = c.getUUID(u);
1293 if(!uu.empty() && reg.stubs.count(uu)) {
1294 m.emplace(u, name_of(uu));
1295 continue;
1296 }
1297 auto bu = reg.base.find(u);
1298 if(bu != reg.base.end()) {
1299 m.emplace(u, bu->second);
1300 continue;
1301 }
1302 const auto &wu = c.getWires(u);
1303 for(auto it = wu.rbegin(); it != wu.rend(); ++it)
1304 stack.push_back(*it);
1305 }
1306 c.evaluate(g, m, sr);
1307 return sr.to_text(std::move(m.at(g)));
1308 }
1309
1310 /* The row of a wide gate, its children as #k.1 ... #k.n */
1311 static std::string summary(const FormulaStub &s, const std::string &nm) {
1312 const auto n = s.nb_children;
1313 const std::vector<std::string> v{nm + ".1", "…", nm + "." + std::to_string(n)};
1314 semiring::Formula sr;
1315 std::string r;
1316 switch(s.type) {
1317 case gate_plus:
1318 r = sr.plus(v);
1319 break;
1320 case gate_times:
1321 r = sr.times(v);
1322 break;
1323 default:
1324 r = sr.agg(getAggregationOperator(s.info1), v);
1325 }
1326 return sr.to_text(std::move(r)) + " (" + std::to_string(n) + " terms)";
1327 }
1328
1329public:
1330 FormulaRows(const constants_t &constants, pg_uuid_t token, Oid table,
1331 std::size_t max_size)
1332 : constants(constants), table(table), max_size(max_size) {
1333 name_of(uuid2string(token));
1334 }
1335
1336 /** The next row, as (name, formula); false when there is none left. */
1337 bool next(std::string &name, std::string &formula) {
1338 if(todo.empty())
1339 return false;
1340 Item &item = todo.front();
1341 if(item.child == OWN) {
1342 const std::string uuid = item.uuid;
1343 name = names.at(uuid);
1344 Region reg;
1345 load(reg, {string2uuid(uuid), 0, 0});
1346 if(reg.stubs.count(uuid)) {
1347 for(const auto &s : reg.r.stubs)
1348 if(s.uuid == uuid) {
1349 formula = summary(s, name);
1350 item.child = 0;
1351 item.nb = s.nb_children;
1352 }
1353 return true;
1354 }
1355 todo.pop_front();
1356 const gate_t g = reg.r.circuit.getGate(uuid);
1357 expand_comparisons(reg, g);
1358 formula = render(reg, g);
1359 return true;
1360 }
1361
1362 const std::string uuid = item.uuid;
1363 const std::size_t i = item.child++;
1364 const std::size_t nb = item.nb;
1365 if(!batch_loaded || i >= batch_from + batch.r.children.size()) {
1366 load(batch, {string2uuid(uuid), i, std::min(BATCH, nb - i)});
1367 batch_from = i;
1368 batch_loaded = true;
1369 for(const auto &ch : batch.r.children)
1370 if(!batch.stubs.count(ch))
1371 expand_comparisons(batch, batch.r.circuit.getGate(ch));
1372 }
1373 name = names.at(uuid) + "." + std::to_string(i + 1);
1374 const std::string ch = batch.r.children.at(i - batch_from);
1375 if(i + 1 == nb) {
1376 todo.pop_front();
1377 batch_loaded = false;
1378 }
1379 formula = render(batch, batch.r.circuit.getGate(ch));
1380 return true;
1381 }
1382};
1383
1384void delete_formula_rows(void *arg)
1385{
1386 delete static_cast<FormulaRows *>(arg);
1387}
1388
1389}
1390
1391/**
1392 * @brief The formula of a token as rows (name, formula), each bounded in
1393 * size: @c sr_formula with the large sub-terms named.
1394 */
1395Datum sr_formula_rows(PG_FUNCTION_ARGS)
1396{
1397 FuncCallContext *funcctx;
1398
1399 if(SRF_IS_FIRSTCALL()) {
1400 funcctx = SRF_FIRSTCALL_INIT();
1401 if(PG_ARGISNULL(0))
1402 SRF_RETURN_DONE(funcctx);
1403 /* The token is an ANYELEMENT, as for sr_formula, so that an aggregate
1404 * of a subquery comes as its agg_token, not as its value */
1405 constants_t constants = get_constants(true);
1406 const Oid type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1407 pg_uuid_t token;
1408 if(type == constants.OID_TYPE_AGG_TOKEN)
1409 token = *DatumGetUUIDP(DirectFunctionCall1(
1410 uuid_in, CStringGetDatum(((agg_token *) PG_GETARG_POINTER(0))->tok)));
1411 else if(type == UUIDOID || type == constants.OID_TYPE_RANDOM_VARIABLE)
1412 token = *PG_GETARG_UUID_P(0);
1413 else
1414 provsql_error("sr_formula_rows: the token must be a uuid, an agg_token "
1415 "or a random_variable, not %s", format_type_be(type));
1416 const Oid table = PG_ARGISNULL(1) ? InvalidOid : PG_GETARG_OID(1);
1417 const int32 max_size = PG_ARGISNULL(2) ? 50 : PG_GETARG_INT32(2);
1418 if(max_size < 1)
1419 provsql_error("sr_formula_rows: max_size must be positive");
1420
1421 /* The descriptor allocated where it lasts for all the rows */
1422 MemoryContext old = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1423 TupleDesc tupdesc;
1424 if(get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1425 provsql_error("sr_formula_rows must return a record");
1426 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
1427 MemoryContextSwitchTo(old);
1428
1429 FormulaRows *rows = nullptr;
1430 try {
1431 provsql_interrupt_scope interrupt_scope;
1432 rows = new FormulaRows(constants, token, table, max_size);
1433 } catch(const CircuitRefusal &r) {
1435 provsql_unsupported(r.scope(), r.tag(), "%s", r.what());
1436 } catch(const std::exception &e) {
1438 provsql_error("sr_formula_rows: %s", e.what());
1439 } catch(...) {
1441 provsql_error("sr_formula_rows: Unknown exception");
1442 }
1443 funcctx->user_fctx = rows;
1444 MemoryContextCallback *cb = static_cast<MemoryContextCallback *>(
1445 MemoryContextAlloc(funcctx->multi_call_memory_ctx,
1446 sizeof(MemoryContextCallback)));
1447 cb->func = delete_formula_rows;
1448 cb->arg = rows;
1449 MemoryContextRegisterResetCallback(funcctx->multi_call_memory_ctx, cb);
1450 }
1451
1452 funcctx = SRF_PERCALL_SETUP();
1453 FormulaRows *rows = static_cast<FormulaRows *>(funcctx->user_fctx);
1454 std::string name, formula;
1455 bool more = false;
1456 Datum values[2];
1457 try {
1458 provsql_interrupt_scope interrupt_scope;
1459 more = rows->next(name, formula);
1460 if(more) {
1461 if(provsql_max_memory > 0)
1463 values[0] = text_datum(name);
1464 values[1] = text_datum(formula);
1465 }
1466 } catch(const CircuitRefusal &r) {
1468 provsql_unsupported(r.scope(), r.tag(), "%s", r.what());
1469 } catch(const std::exception &e) {
1471 provsql_error("sr_formula_rows: %s", e.what());
1472 } catch(...) {
1474 provsql_error("sr_formula_rows: Unknown exception");
1475 }
1476 if(!more)
1477 SRF_RETURN_DONE(funcctx);
1478 bool nulls[2] = {false, false};
1479 SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(
1480 heap_form_tuple(funcctx->tuple_desc, values, nulls)));
1481}
AggregationOperator getAggregationOperator(Oid oid)
Map a PostgreSQL aggregate function OID to an AggregationOperator.
One least-cost derivation: its cost and its word of labels.
Boolean-expression (lineage formula) semiring.
Boolean semiring ({false, true}, ∨, ∧, false, true).
pg_uuid_t provsqlUuidV5(const std::string &name)
RFC 4122 version-5 UUID in the ProvSQL namespace.
Content-addressed materialisation of a certified d-D into the mmap provenance store.
FormulaRegions getFormulaRegions(const std::vector< FormulaRequest > &requests, unsigned long cap, unsigned long wide_cap)
The regions of requests, for sr_formula_rows (see FormulaRegions), with the load-time simplification ...
BooleanCircuit getBooleanCircuit(GenericCircuit &gc, pg_uuid_t token, gate_t &gate, std::unordered_map< gate_t, gate_t > &gc_to_bc)
Build a BooleanCircuit from an already-loaded GenericCircuit.
void applyProbabilisticSimplification(GenericCircuit &gc)
Simplify a loaded circuit for a probability readout.
GenericCircuit getGenericCircuit(pg_uuid_t token)
Build a GenericCircuit from the mmap store rooted at token.
Build in-memory circuits from the mmap-backed persistent store.
gate_t
Strongly-typed gate identifier.
Definition Circuit.h:53
Counting semiring (ℕ, +, ×, 0, 1).
Analytical expectation / variance / moment evaluator over RV circuits.
Symbolic representation of provenance as a human-readable formula.
How-provenance m-semiring (canonical polynomial provenance ℕ[X]).
Interval-union m-semiring over PostgreSQL multirange types.
Łukasiewicz fuzzy m-semiring over .
Min-max and max-min m-semirings over PostgreSQL enum types.
Regular-expression semiring: the derivations of a tuple as a language over the labels of its input tu...
The Boolean algebra of the subsets of a PostgreSQL enum type.
Min-cost derivations with the derivations of that cost.
Tropical (min-plus) m-semiring over .
Viterbi (max-times) m-semiring over .
Which-provenance (lineage) m-semiring.
Why-provenance semiring (set of witness sets).
Aggregate-provenance token type used in SQL aggregate functions.
Boolean circuit for provenance formula evaluation.
virtual std::string toString(gate_t g) const override
Return a textual description of gate g for debugging.
Exception type thrown by circuit operations on invalid input.
Definition Circuit.h:382
virtual char const * what() const noexcept
Return the error message as a C-string.
Definition Circuit.h:396
A refusal by design, or a known gap, rather than an error.
Definition Circuit.h:409
const char * scope() const noexcept
The kind of the refusal.
Definition Circuit.h:424
const char * tag() const noexcept
The tag of the refusal.
Definition Circuit.h:428
std::vector< gate_t > & getWires(gate_t g)
Return a mutable reference to the child-wire list of gate g.
Definition Circuit.h:311
gateType getGateType(gate_t g) const
Return the type of gate g.
Definition Circuit.h:301
uuid getUUID(gate_t g) const
Return the UUID string associated with gate g.
Definition Circuit.hpp:65
gate_t getGate(const uuid &u)
Return (or create) the gate associated with UUID u.
Definition Circuit.hpp:50
std::vector< std::pair< gate_t, std::shared_ptr< void > > > solved_systems
Equation systems solved by evaluate, with their solutions.
const S::value_type & evaluate(gate_t g, std::unordered_map< gate_t, typename S::value_type > &provenance_mapping, S semiring) const
Evaluate the sub-circuit rooted at gate g over semiring semiring.
std::vector< std::string > getMappableUUIDs() const
The UUIDs a provenance mapping can label: those of the input gates, and of the mulinput gates,...
const std::set< gate_t > & getInputs() const
Return the set of input (leaf) gates.
The quantity asked for has a value in no world (an aggregate over a group empty in every world of pos...
Definition Expectation.h:47
The SIGINT handler installed for the lifetime of the object, the previous one restored as it ends (a ...
The one-best-derivation semiring over best_path_t.
Definition BestPath.h:78
static best_path_t leaf(double cost, const std::string *label)
The value of an input of cost cost and label label, no label being the empty word,...
Definition BestPath.h:91
The Boolean semiring over bool.
Definition Boolean.h:41
The counting semiring over unsigned.
Definition Counting.h:43
static constexpr value_type INFINITE
: the count of a tuple derived through a cycle.
Definition Counting.h:48
Symbolic provenance representation over std::string.
Definition Formula.h:190
virtual value_type agg(AggregationOperator op, const std::vector< std::string > &s) override
Evaluate an aggregation gate.
Definition Formula.h:335
virtual value_type times(const std::vector< value_type > &v) const override
Apply the multiplicative operation to a list of values.
Definition Formula.h:276
value_type parse_leaf(const char *v) const
Definition Formula.h:594
std::string to_text(value_type s) const
Serialise a Formula evaluation as text.
Definition Formula.h:614
virtual value_type plus(const std::vector< value_type > &v) const override
Apply the additive operation to a list of values.
Definition Formula.h:273
How-provenance m-semiring over .
Definition How.h:72
Interval-union m-semiring with Datum carrier, parameterised by a multirange type OID.
The Łukasiewicz fuzzy m-semiring over double.
Definition Lukasiewicz.h:58
Min-max / max-min m-semiring with Datum carrier over a PostgreSQL enum type.
Definition MinMax.h:77
The regular-expression semiring over regex_t.
Definition Regex.h:280
Subsets of the labels of an enum type, as a 64-bit mask.
Definition Subset.h:96
static constexpr uint64_t UNRESTRICTED
The bit of the unrestricted world, in CONSENT mode.
Definition Subset.h:102
Tropical (min-plus) m-semiring restricted to nonnegative costs.
Definition Tropical.h:136
The min-cost-paths semiring over tropical_paths_t.
Tropical (min-plus) m-semiring over double.
Definition Tropical.h:52
The Viterbi (max-times) m-semiring over double.
Definition Viterbi.h:50
Which-provenance (lineage) semiring.
Definition Which.h:58
Why-provenance semiring.
Definition Why.h:56
PostgreSQL cross-version compatibility shims for ProvSQL.
Provenance evaluation helper for HAVING-clause circuits.
void provsql_having(GenericCircuit &c, gate_t g, MapT &mapping, SemiringT S=SemiringT{})
Rewrite HAVING comparison gates in the circuit into their possible-world provenance (world enumeratio...
std::vector< gate_t > collect_sp_cmp_gates(GenericCircuit &c, gate_t start)
double compute_expectation(const GenericCircuit &gc, gate_t root, std::optional< gate_t > event_root)
Compute (or if event_root is set) over the scalar sub-circuit rooted at root.
std::map< how_monomial_t, unsigned > how_provenance_t
How-provenance value: each monomial mapped to its (positive) coefficient.
Definition How.h:62
std::set< label_set > why_provenance_t
Why-provenance value: the full set of all witnesses.
Definition Why.h:49
std::optional< std::set< std::string > > which_provenance_t
Which-provenance value: a set of labels, or (empty optional).
Definition Which.h:50
Datum subset_settling(PG_FUNCTION_ARGS)
The settling level of a set of clearance levels: the lowest level from which membership no longer cha...
Datum subset_labels(PG_FUNCTION_ARGS)
The labels a subset bitmask holds, as an array of the enum type of element_one, in enumsortorder.
Datum provenance_evaluate_best_path(PG_FUNCTION_ARGS)
PostgreSQL-callable wrapper for best_path_internal().
static Datum provenance_evaluate_compiled_internal(pg_uuid_t token, Oid table, const std::string &semiring, Oid type)
Core implementation of compiled provenance evaluation.
const char * drop_temp_table
DROP TABLE statement for the per-query temporary provenance mapping table.
Datum sr_formula_rows(PG_FUNCTION_ARGS)
The formula of a token as rows (name, formula), each bounded in size: sr_formula with the large sub-t...
bool join_with_temp_uuids(Oid table, const std::vector< std::string > &uuids)
Join a provenance mapping table with a set of UUIDs using SPI.
static semiring::best_path_t best_path_internal(pg_uuid_t token, Oid costs, Oid labels)
A least-cost derivation of token (semiring::BestPath), each leaf with its cost from costs and its lab...
Datum provenance_evaluate_tropical_paths(PG_FUNCTION_ARGS)
PostgreSQL-callable wrapper for tropical_paths_internal().
Datum provenance_evaluate_compiled(PG_FUNCTION_ARGS)
PostgreSQL-callable wrapper for provenance_evaluate_compiled().
static std::pair< double, std::string > tropical_paths_internal(pg_uuid_t token, Oid costs, Oid labels)
Min-cost derivations of token and the derivations of that cost (semiring::TropicalPaths),...
Datum plain_truth(PG_FUNCTION_ARGS)
Whether a token holds in the database as it is, every input tuple present: sr_boolean without a mappi...
Datum subset_member(PG_FUNCTION_ARGS)
Membership of a label, given as text, in the subset annotation of a token: the predicate behind visib...
Template helper for populating provenance mappings from SPI results.
void initialize_provenance_mapping(const constants_t &constants, GenericCircuit &c, std::unordered_map< gate_t, T > &provenance_mapping, const std::function< T(const char *)> &charp_to_value, bool drop_table)
Populate a provenance mapping from the current SPI result set.
int provsql_max_worlds
Possible worlds of a group that a condition on its aggregate may have enumerated before the evaluatio...
Definition provsql.c:132
int provsql_max_memory
Memory, in MB, that the evaluations of a statement may add to the backend's resident set,...
Definition provsql.c:131
#define PROVSQL_DELIBERATE
What kind of limit a refusal or a freezing is.
#define provsql_error(fmt,...)
Report a fatal ProvSQL error and abort the current transaction.
#define provsql_unsupported(scope, tag, fmt,...)
Refuse a query ProvSQL cannot track, and abort the transaction.
void provsql_check_result_size(size_t bytes, const char *message)
Throw if a text value of bytes is past what PostgreSQL can hold in a value (1 GB),...
bool provsql_limit_pending(void)
Whether the evaluation stopped at a resource limit (provsql_limit_exceeded), not yet raised: a catch ...
void provsql_cancel_if_interrupted(void)
Raise PG's cancel if the evaluation stopped for one; nothing otherwise.
void provsql_check_memory_for(size_t extra)
Throw if extra more bytes would take the evaluations of the statement past provsql....
void provsql_check_memory(void)
Throw if the evaluations of the statement have made the backend's resident memory grow by more than p...
Cancellation of the long C++ evaluation loops.
void provsql_poll_interrupt()
Throw where an evaluation is to stop, its query cancelled.
gate_type provsql_fetch_gate(const pg_uuid_t *token, unsigned *nb_children_out, pg_uuid_t **children_out)
PostgreSQL-callable wrapper for get_gate_type().
Background worker and IPC primitives for mmap-backed circuit storage.
constants_t get_constants(bool failure_if_not_possible)
Retrieve the cached OID constants for the current database.
Core types, constants, and utilities shared across ProvSQL.
@ gate_annotation
Transparent single-child wrapper carrying a query-level annotation in extra (inversion-free certifica...
@ gate_assumed
Structural marker over a single child whose sub-circuit was computed under a Boolean-provenance assum...
pg_uuid_t string2uuid(const string &source)
Parse a UUID string into a pg_uuid_t.
string uuid2string(pg_uuid_t uuid)
Format a pg_uuid_t as a std::string.
std::string uuid
The gate.
unsigned long nb_children
Its number of children.
gate_type type
Its type.
unsigned info1
Its first integer annotation.
Aggregate token bundling a provenance UUID with a running value.
Definition agg_token.h:32
Structure to store the value of various constants.
Oid OID_TYPE_VARCHAR
OID of the VARCHAR TYPE.
Oid OID_FUNCTION_AGG_GUARD_HOLDS
OID of agg_guard_holds(), the truth of a comparison of aggregate results in the database as it is,...
Oid OID_TYPE_FLOAT
OID of the FLOAT TYPE.
Oid OID_TYPE_AGG_TOKEN
OID of the agg_token TYPE.
Oid OID_TYPE_INT
OID of the INT TYPE.
Oid OID_TYPE_TSTZMULTIRANGE
OID of the tstzmultirange TYPE (PG14+, InvalidOid otherwise).
bool ok
true if constants were loaded
Oid OID_TYPE_BOOL
OID of the BOOL TYPE.
Oid OID_TYPE_NUMMULTIRANGE
OID of the nummultirange TYPE (PG14+, InvalidOid otherwise).
Oid OID_TYPE_RANDOM_VARIABLE
OID of the random_variable TYPE.
Oid OID_TYPE_INT4MULTIRANGE
OID of the int4multirange TYPE (PG14+, InvalidOid otherwise).
The labels of an enum type, in enumsortorder: their OIDs, and the rank of each OID.
Definition Subset.h:66
std::vector< Oid > oids
label OIDs, by rank
Definition Subset.h:67
std::unordered_map< Oid, unsigned > rank
rank of each label OID
Definition Subset.h:68
A cost and a derivation of that cost, as a word of labels.
Definition BestPath.h:53
double cost
+∞ for 𝟘
Definition BestPath.h:54
bool is_zero() const
Whether this is .
Definition BestPath.h:58
std::vector< std::string > word
Its labels.
Definition BestPath.h:55
static regex_t atom(const std::string &label)
A one-letter language; for an empty label.
Definition Regex.h:180
A regular expression: an immutable tree, shared between the expressions built from it.
Definition Regex.h:63
A cost, and the derivations of that cost.