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"
69#include <unordered_map>
73#include <unordered_set>
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");
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);
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));
138#if PG_VERSION_NUM >= 140000
142Datum to_datum(
const semiring::Subset &, uint64_t v) {
return Int64GetDatum(
static_cast<int64
>(v)); }
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;
160std::string fixpoint_cache_ctx;
161int16 fixpoint_cache_typlen;
162bool fixpoint_cache_typbyval;
167std::unordered_map<std::string, std::pair<double, std::string> >
171std::unordered_map<std::string, semiring::best_path_t> best_path_cache;
173void fixpoint_cache_clear()
175 fixpoint_cache.clear();
176 tropical_paths_cache.clear();
177 best_path_cache.clear();
178 if(fixpoint_cache_cxt)
179 MemoryContextReset(fixpoint_cache_cxt);
182void fixpoint_cache_xact_callback(XactEvent event,
void *)
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();
193template <
typename Sem>
198 if(!fixpoint_cache_cxt) {
199 fixpoint_cache_cxt = AllocSetContextCreate(TopMemoryContext,
200 "ProvSQL fixpoint cache",
201 ALLOCSET_DEFAULT_SIZES);
203 if(!fixpoint_cache_callback) {
204 RegisterXactCallback(fixpoint_cache_xact_callback,
nullptr);
205 fixpoint_cache_callback =
true;
207 using V =
typename Sem::value_type;
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 =
220 d = to_datum(sr, vec[i]);
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);
254template <
typename Sem>
262 using V =
typename Sem::value_type;
263 std::unordered_map<gate_t, V> mapping;
265 [&sr](
const char *v) {
return sr.
parse_leaf(v); }, drop_table);
270 V out = std::move(mapping.at(g));
271 fixpoint_cache_store(c, sr);
274 std::unordered_map<gate_t, V>().swap(mapping);
275 return to_datum(sr, std::move(out));
287 const std::unordered_map<gate_t, std::string> *labels)
301 if (SPI_connect() != SPI_OK_CONNECT)
307 if (!OidIsValid(table)) {
308 if (SPI_execute(
"SELECT ''::text AS value, NULL::uuid AS provenance WHERE false",
309 true, 0) != SPI_OK_SELECT) {
316 char *table_name = get_rel_name(table);
326 const char *qualified = quote_qualified_identifier(
327 get_namespace_name(get_rel_namespace(table)), table_name);
329 constexpr size_t nb_max_uuid_value = 10000000;
331 StringInfoData join_query;
332 initStringInfo(&join_query);
333 bool drop_table =
false;
339 Datum uuid_array = (Datum) 0;
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) {
353 Datum *elems =
static_cast<Datum *
>(palloc(uuids.size() *
sizeof(Datum)));
354 for(
size_t i = 0; i < uuids.size(); ++i) {
356 elems[i] = UUIDPGetDatum(&values[i]);
358 uuid_array = PointerGetDatum(
359 construct_array(elems, uuids.size(), UUIDOID, UUID_LEN,
false,
364 appendStringInfo(&join_query,
365 "SELECT value, provenance FROM %s t "
366 "JOIN unnest($1) AS u(id) ON t.provenance=u.id",
369 const char *create_temp_table =
"CREATE TEMP TABLE tmp_uuids(id uuid);";
370 if (SPI_exec(create_temp_table, 0) != SPI_OK_UTILITY) {
376 constexpr size_t batch_size = 1000;
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 ");
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) ?
"" :
",");
388 int retval=SPI_exec(insert_query.data, 0);
389 pfree(insert_query.data);
391 if(retval != SPI_OK_INSERT) {
398 appendStringInfo(&join_query,
399 "SELECT value, provenance FROM %s t JOIN tmp_uuids u ON t.provenance = u.id", qualified);
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,
409 : SPI_execute(join_query.data, !drop_table, 0);
410 if (ret != SPI_OK_SELECT) {
437 if(
semiring==
"boolexpr" && !OidIsValid(table)) {
440 return pec_boolexpr(bc, root,
nullptr);
449 "Unknown element type for expectation: must be float8");
458 fixpoint_cache_ctx =
semiring +
"|" + std::to_string(table) +
"|" +
459 std::to_string(type) +
"|" +
460 std::to_string(GetCurrentCommandId(
false));
464 get_typlenbyval(INT8OID, &fixpoint_cache_typlen, &fixpoint_cache_typbyval);
466 get_typlenbyval(type, &fixpoint_cache_typlen, &fixpoint_cache_typbyval);
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);
485 std::unordered_map<gate_t, std::string> gc_labels;
487 return std::string(v);
490 std::unordered_map<gate_t, gate_t> gc_to_bc;
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;
500 return pec_boolexpr(bc, root, &bc_labels);
528#if PG_VERSION_NUM >= 140000
545 if (get_typtype(type) == TYPTYPE_ENUM) {
556 throw CircuitException(
"Unknown element type for provenance_evaluate_compiled");
574 fixpoint_cache_ctx.clear();
578 const std::string ctx = std::to_string(costs) +
"|" +
579 std::to_string(labels) +
"|" +
580 std::to_string(GetCurrentCommandId(
false));
582 auto it = tropical_paths_cache.find(ctx +
"|" +
uuid2string(token));
583 if(it != tropical_paths_cache.end())
591 std::unordered_map<gate_t, double> cost;
593 [](
const char *v) {
return atof(v); },
595 std::unordered_map<gate_t, std::string> label;
597 [](
const char *v) {
return std::string(v); },
601 std::unordered_map<gate_t, semiring::tropical_paths_t> mapping;
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);
611 ic == cost.end() ? 0. : ic->second,
619 RegisterXactCallback(fixpoint_cache_xact_callback,
nullptr);
620 fixpoint_cache_callback =
true;
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(
632 std::make_pair(vec[i].cost, vec[i].paths.render()));
635 return {out.cost, out.paths.render()};
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] =
652 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
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)));
661 }
catch(
const std::exception &e) {
663 provsql_error(
"provenance_evaluate_tropical_paths: %s", e.what());
666 provsql_error(
"provenance_evaluate_tropical_paths: Unknown exception");
686 fixpoint_cache_ctx.clear();
690 const std::string ctx = std::to_string(costs) +
"|" +
691 std::to_string(labels) +
"|" +
692 std::to_string(GetCurrentCommandId(
false));
694 auto it = best_path_cache.find(ctx +
"|" +
uuid2string(token));
695 if(it != best_path_cache.end())
703 std::unordered_map<gate_t, double> cost;
705 [](
const char *v) {
return atof(v); },
707 std::unordered_map<gate_t, std::string> label;
709 [](
const char *v) {
return std::string(v); },
713 std::unordered_map<gate_t, semiring::best_path_t> mapping;
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);
723 ic == cost.end() ? 0. : ic->second,
724 il == label.end() ?
nullptr : &il->second);
731 RegisterXactCallback(fixpoint_cache_xact_callback,
nullptr);
732 fixpoint_cache_callback =
true;
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(
758 const Oid costs = PG_ARGISNULL(1) ? InvalidOid : PG_GETARG_OID(1);
759 const Oid labels = PG_ARGISNULL(2) ? InvalidOid : PG_GETARG_OID(2);
764 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
766 tupdesc = BlessTupleDesc(tupdesc);
767 Datum values[2] = {Float8GetDatum(out.
cost), (Datum)0};
768 bool nulls[2] = {
false, 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,
777 PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
781 }
catch(
const std::exception &e) {
783 provsql_error(
"provenance_evaluate_best_path: %s", e.what());
786 provsql_error(
"provenance_evaluate_best_path: Unknown exception");
799 if (PG_ARGISNULL(0) || PG_ARGISNULL(2))
804 Datum token = PG_GETARG_DATUM(0);
806 Oid table = PG_GETARG_OID(1);
808 text *t = PG_GETARG_TEXT_P(2);
809 std::string
semiring(VARDATA(t),VARSIZE(t)-VARHDRSZ);
811 Oid type = get_fn_expr_argtype(fcinfo->flinfo, 3);
821 }
catch(
const std::exception &e) {
826 provsql_error(
"provenance_evaluate_compiled: Unknown exception");
837std::unordered_map<std::string, bool> plain_truth_memo;
838constexpr size_t plain_truth_memo_max = 1000000;
842int quick_plain_truth(
const pg_uuid_t &token,
unsigned depth)
845 auto it = plain_truth_memo.find(key);
846 if (it != plain_truth_memo.end())
851 unsigned nb_children = 0;
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; }
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);
883 if (nb_children >= 1)
884 res = quick_plain_truth(children[0], depth + 1);
904#if PG_VERSION_NUM >= 120000
905 LOCAL_FCINFO(fcinfo, 1);
907 FunctionCallInfoData fcinfo_data;
908 FunctionCallInfo fcinfo = &fcinfo_data;
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;
918 fcinfo->arg[0] = UUIDPGetDatum(&token);
919 fcinfo->argnull[0] =
false;
921 d = FunctionCallInvoke(fcinfo);
923 res = DatumGetBool(d) ? 1 : 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);
959 PG_RETURN_BOOL(
true);
960 token = *PG_GETARG_UUID_P(0);
962 int quick = quick_plain_truth(token, 0);
964 PG_RETURN_BOOL(quick == 1);
975 std::unordered_map<gate_t, bool> mapping;
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(
991 }
catch(
const std::exception &) {
995 if (plain_truth_memo.size() >= plain_truth_memo_max)
996 plain_truth_memo.clear();
1014 uint64_t mask =
static_cast<uint64_t
>(PG_GETARG_INT64(0));
1015 Oid enum_oid = get_fn_expr_argtype(fcinfo->flinfo, 1);
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]));
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));
1042 uint64_t mask =
static_cast<uint64_t
>(PG_GETARG_INT64(0));
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)
1051 PG_RETURN_OID(labels.
oids[l]);
1065 if(PG_ARGISNULL(0) || PG_ARGISNULL(1) || PG_ARGISNULL(2) || PG_ARGISNULL(3))
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));
1073 AttrNumber att = get_attnum(table,
"value");
1074 if(att == InvalidAttrNumber)
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");
1084 Oid in_func, typioparam;
1085 getTypeInputInfo(enum_oid, &in_func, &typioparam);
1086 Oid label = DatumGetObjectId(OidInputFunctionCall(in_func, label_text,
1089 uint64_t bit = uint64_t(1) << labels.
rank.at(label);
1094 mask =
static_cast<uint64_t
>(DatumGetInt64(
1099 }
catch(
const std::exception &e) {
1103 if(mode ==
"consent")
1105 PG_RETURN_BOOL(mask & bit);
1132 constants_t constants;
1134 std::size_t max_size;
1136 std::unordered_map<std::string, std::string> names;
1137 std::size_t next_name = 1;
1145 static constexpr std::size_t OWN = std::numeric_limits<std::size_t>::max();
1148 static constexpr std::size_t SLACK = 4;
1150 static constexpr std::size_t BATCH = 4096;
1151 std::deque<Item> todo;
1157 std::unordered_map<gate_t, std::string> base;
1158 std::unordered_set<std::string> stubs;
1162 std::size_t batch_from = 0;
1163 bool batch_loaded =
false;
1168 class CappedFormula :
public semiring::Formula {
1170 std::string check(std::string v)
const {
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));
1180 value_type times(
const std::vector<value_type> &v)
const override {
1181 return check(Formula::times(v));
1183 value_type plus_of(
const std::vector<const value_type *> &v)
const override {
1184 return check(Formula::plus_of(v));
1186 value_type times_of(
const std::vector<const value_type *> &v)
const override {
1187 return check(Formula::times_of(v));
1189 value_type monus(value_type x, value_type y)
const override {
1190 return check(Formula::monus(std::move(x), std::move(y)));
1196 static std::size_t contributors(
const GenericCircuit &c,
gate_t g) {
1198 std::unordered_set<gate_t> seen;
1200 while(!stack.empty()) {
1201 const gate_t u = stack.back();
1203 if(!seen.insert(u).second)
1222 void expand_comparisons(Region &g,
gate_t root) {
1223 GenericCircuit &c = g.r.circuit;
1228 const std::size_t cap = 8 * SLACK * max_size;
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
1236 GenericCircuit saved_circuit = c;
1237 auto saved_base = g.base;
1240 }
catch(
const TooLarge &) {
1241 c = std::move(saved_circuit);
1242 g.base = std::move(saved_base);
1247 void load(Region &g,
const FormulaRequest &q) {
1251 for(
const auto &s : g.r.stubs)
1252 g.stubs.insert(s.uuid);
1253 const bool drop_table =
1255 semiring::Formula sr;
1257 [&sr](
const char *v) { return sr.parse_leaf(v); }, drop_table);
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});
1271 std::string render(Region ®,
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))
1277 auto b = reg.base.find(g);
1278 if(b != reg.base.end())
1280 std::unordered_map<gate_t, std::string> m;
1281 std::unordered_set<gate_t> seen{g};
1282 std::vector<gate_t> stack;
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();
1290 if(!seen.insert(u).second)
1292 const std::string uu = c.
getUUID(u);
1293 if(!uu.empty() && reg.stubs.count(uu)) {
1294 m.emplace(u, name_of(uu));
1297 auto bu = reg.base.find(u);
1298 if(bu != reg.base.end()) {
1299 m.emplace(u, bu->second);
1303 for(
auto it = wu.rbegin(); it != wu.rend(); ++it)
1304 stack.push_back(*it);
1307 return sr.
to_text(std::move(m.at(g)));
1311 static std::string summary(
const FormulaStub &s,
const std::string &nm) {
1313 const std::vector<std::string> v{nm +
".1",
"…", nm +
"." + std::to_string(n)};
1314 semiring::Formula sr;
1326 return sr.
to_text(std::move(r)) +
" (" + std::to_string(n) +
" terms)";
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) {
1337 bool next(std::string &name, std::string &formula) {
1340 Item &item = todo.front();
1341 if(item.child == OWN) {
1342 const std::string uuid = item.uuid;
1343 name = names.at(uuid);
1346 if(reg.stubs.count(uuid)) {
1347 for(
const auto &s : reg.r.stubs)
1348 if(s.
uuid == uuid) {
1349 formula = summary(s, name);
1356 const gate_t g = reg.r.circuit.getGate(uuid);
1357 expand_comparisons(reg, g);
1358 formula = render(reg, g);
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)});
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));
1373 name = names.at(uuid) +
"." + std::to_string(i + 1);
1374 const std::string ch = batch.r.children.at(i - batch_from);
1377 batch_loaded =
false;
1379 formula = render(batch, batch.r.circuit.getGate(ch));
1384void delete_formula_rows(
void *arg)
1386 delete static_cast<FormulaRows *
>(arg);
1397 FuncCallContext *funcctx;
1399 if(SRF_IS_FIRSTCALL()) {
1400 funcctx = SRF_FIRSTCALL_INIT();
1402 SRF_RETURN_DONE(funcctx);
1406 const Oid type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1409 token = *DatumGetUUIDP(DirectFunctionCall1(
1410 uuid_in, CStringGetDatum(((
agg_token *) PG_GETARG_POINTER(0))->tok)));
1412 token = *PG_GETARG_UUID_P(0);
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);
1419 provsql_error(
"sr_formula_rows: max_size must be positive");
1422 MemoryContext old = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1424 if(get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1426 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
1427 MemoryContextSwitchTo(old);
1429 FormulaRows *rows =
nullptr;
1432 rows =
new FormulaRows(constants, token, table, max_size);
1436 }
catch(
const std::exception &e) {
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;
1449 MemoryContextRegisterResetCallback(funcctx->multi_call_memory_ctx, cb);
1452 funcctx = SRF_PERCALL_SETUP();
1453 FormulaRows *rows =
static_cast<FormulaRows *
>(funcctx->user_fctx);
1454 std::string name, formula;
1459 more = rows->next(name, formula);
1463 values[0] = text_datum(name);
1464 values[1] = text_datum(formula);
1469 }
catch(
const std::exception &e) {
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)));
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.
Counting semiring (ℕ, +, ×, 0, 1).
Analytical expectation / variance / moment evaluator over RV circuits.
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.
virtual char const * what() const noexcept
Return the error message as a C-string.
A refusal by design, or a known gap, rather than an error.
const char * scope() const noexcept
The kind of the refusal.
const char * tag() const noexcept
The tag of the refusal.
std::vector< gate_t > & getWires(gate_t g)
Return a mutable reference to the child-wire list of gate g.
gateType getGateType(gate_t g) const
Return the type of gate g.
uuid getUUID(gate_t g) const
Return the UUID string associated with gate g.
gate_t getGate(const uuid &u)
Return (or create) the gate associated with UUID u.
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...
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.
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,...
The Boolean semiring over bool.
The counting semiring over unsigned.
static constexpr value_type INFINITE
: the count of a tuple derived through a cycle.
How-provenance m-semiring over .
Interval-union m-semiring with Datum carrier, parameterised by a multirange type OID.
The Łukasiewicz fuzzy m-semiring over double.
Min-max / max-min m-semiring with Datum carrier over a PostgreSQL enum type.
The regular-expression semiring over regex_t.
Subsets of the labels of an enum type, as a 64-bit mask.
static constexpr uint64_t UNRESTRICTED
The bit of the unrestricted world, in CONSENT mode.
Tropical (min-plus) m-semiring restricted to nonnegative costs.
The min-cost-paths semiring over tropical_paths_t.
Tropical (min-plus) m-semiring over double.
The Viterbi (max-times) m-semiring over double.
Which-provenance (lineage) semiring.
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.
std::set< label_set > why_provenance_t
Why-provenance value: the full set of all witnesses.
std::optional< std::set< std::string > > which_provenance_t
Which-provenance value: a set of labels, or (empty optional).
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...
int provsql_max_memory
Memory, in MB, that the evaluations of a statement may add to the backend's resident set,...
#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.
Aggregate token bundling a provenance UUID with a running value.
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.
std::vector< Oid > oids
label OIDs, by rank
std::unordered_map< Oid, unsigned > rank
rank of each label OID
A cost and a derivation of that cost, as a word of labels.
bool is_zero() const
Whether this is .
std::vector< std::string > word
Its labels.
static regex_t atom(const std::string &label)
A one-letter language; for an empty label.
A regular expression: an immutable tree, shared between the expressions built from it.
A cost, and the derivations of that cost.