29#include "catalog/pg_type.h"
31#include "storage/latch.h"
32#include "utils/uuid.h"
33#include "executor/spi.h"
35#include "access/htup_details.h"
48#include <unordered_map>
107 auto it = memo.find(g);
108 if(it != memo.end())
return it->second;
109 CHECK_FOR_INTERRUPTS();
122 for(
gate_t c : gc.
getWires(g)) pn *= (1.0 - mobiusEvalRec(gc, c, memo));
130 r = mobiusEvalRec(gc, w[0], memo) - mobiusEvalRec(gc, w[1], memo);
136 const std::string extra = gc.
getExtra(g);
141 std::map<std::string,long> co;
145 while(i < extra.size()) {
146 while(i < extra.size() && (extra[i]==
' '||extra[i]==
'\t')) ++i;
147 if(i >= extra.size())
break;
149 while(j < extra.size() && extra[j]!=
' ' && extra[j]!=
'\t') ++j;
150 const std::string tok = extra.substr(i, j-i);
151 if(tok.size()>2 && tok[0]==
'L' && tok[1]==
':')
152 lineage = tok.substr(2);
154 const std::size_t colon = tok.rfind(
':');
155 if(colon != std::string::npos)
156 co[tok.substr(0,colon)] =
157 std::strtol(tok.substr(colon+1).c_str(),
nullptr, 10);
163 for(std::size_t i=0;i<w.size();++i) {
167 auto cit = co.find(u);
170 v +=
static_cast<double>(cit->second) * mobiusEvalRec(gc, w[i], memo);
174 constexpr double tol = 1e-9;
175 if(v < -tol || v > 1.0 + tol)
176 provsql_warning(
"mobius: signed combination left [0,1] before clamping "
177 "(value %g) -- possible compiler bug", v);
178 if(v < 0.) v = 0.;
else if(v > 1.) v = 1.;
194std::string mobiusLineageOf(
pg_uuid_t token)
206 const std::size_t p = ex.find(
"L:");
207 if(p != std::string::npos) {
208 const std::size_t e = ex.find(
' ', p);
209 lineage = ex.substr(p + 2,
210 e == std::string::npos ? std::string::npos : e - p - 2);
219double mobiusProbabilityImpl(
pg_uuid_t token)
235 std::map<gate_t,double> memo;
236 r = mobiusEvalRec(gc, root, memo);
251string trim_arg(
const string &s)
253 size_t a = s.find_first_not_of(
" \t");
254 if(a == string::npos)
256 size_t b = s.find_last_not_of(
" \t");
257 return s.substr(a, b - a + 1);
269 map<string, string> kv;
270 vector<string> positional;
271 bool has(
const string &k)
const {
return kv.find(k) != kv.end(); }
272 string get(
const string &k)
const {
273 auto it = kv.find(k);
274 return it == kv.end() ? string() : it->second;
289MethodArgs parse_method_args(
const string &args)
292 stringstream ss(args);
294 while(getline(ss, tok,
',')) {
295 string t = trim_arg(tok);
298 auto eq = t.find(
'=');
299 if(eq == string::npos) {
300 out.positional.push_back(t);
302 string key = trim_arg(t.substr(0, eq));
303 string val = trim_arg(t.substr(eq + 1));
304 transform(key.begin(), key.end(), key.begin(),
305 [](
unsigned char c){ return tolower(c); });
315void reject_unknown_keys(
const MethodArgs &a,
const set<string> &allowed,
318 for(
const auto &p : a.kv)
319 if(allowed.find(p.first) == allowed.end())
321 method, p.first.c_str());
325bool parse_ulong_full(
const string &v,
unsigned long &out)
327 if(v.empty() || v.find_first_not_of(
"0123456789") != string::npos)
331 out = stoul(v, &pos);
332 return pos == v.size();
333 }
catch(
const std::exception &) {
339bool parse_double_full(
const string &v,
double &out)
346 return pos == v.size();
347 }
catch(
const std::exception &) {
361void parse_eps_delta(
const MethodArgs &a,
const char *method,
362 double &eps,
double &delta)
364 if(a.has(
"epsilon") && (!parse_double_full(a.get(
"epsilon"), eps)
365 || eps <= 0. || eps > 1.))
366 provsql_error(
"method '%s': epsilon must be in (0, 1]", method);
367 if(a.has(
"delta") && (!parse_double_full(a.get(
"delta"), delta)
368 || delta < 0. || delta >= 1.))
369 provsql_error(
"method '%s': delta must be in [0, 1)", method);
381 unsigned long samples = 0;
382 double eps = 0.1, delta = 0.05;
383 bool has_max =
false;
384 unsigned long max_samples = 0;
396SampleSpec parse_sample_spec(
const MethodArgs &a,
const char *method)
398 reject_unknown_keys(a, {
"samples",
"epsilon",
"delta",
"max_samples"}, method);
400 const bool has_samples = a.has(
"samples") || !a.positional.empty();
401 const bool has_adaptive = a.has(
"epsilon") || a.has(
"delta");
403 if(a.positional.size() > 1)
404 provsql_error(
"method '%s': too many positional arguments", method);
405 if(a.has(
"samples") && !a.positional.empty())
406 provsql_error(
"method '%s': give either samples= or a bare integer, "
408 if(has_samples && has_adaptive)
409 provsql_error(
"method '%s': samples is mutually exclusive with "
410 "epsilon/delta", method);
411 if(a.has(
"max_samples") && !has_adaptive)
412 provsql_error(
"method '%s': max_samples applies only to the adaptive "
413 "epsilon/delta path", method);
414 if(a.has(
"delta") && !a.has(
"epsilon"))
415 provsql_error(
"method '%s': delta requires epsilon", method);
420 const string v = a.has(
"samples") ? a.get(
"samples") : a.positional[0];
421 if(!parse_ulong_full(v, s.samples) || s.samples == 0)
422 provsql_error(
"method '%s': invalid sample count '%s'", method, v.c_str());
426 parse_eps_delta(a, method, s.eps, s.delta);
430 if(s.delta == 0. &&
string(method) !=
"relative"
431 &&
string(method) !=
"additive")
432 provsql_error(
"method '%s': delta must be in (0, 1); delta = 0 "
433 "(deterministic) is supported only on the 'relative' / "
434 "'additive' paths, which route to the d-tree or an exact "
436 if(a.has(
"max_samples")) {
438 if(!parse_ulong_full(a.get(
"max_samples"), s.max_samples) || s.max_samples == 0)
439 provsql_error(
"method '%s': invalid max_samples '%s'", method,
440 a.get(
"max_samples").c_str());
446unsigned long finalize_adaptive(
double nd,
const SampleSpec &s)
450 unsigned long n = (nd >= 9e18) ?
static_cast<unsigned long>(9e18)
451 :
static_cast<unsigned long>(nd);
454 if(s.has_max && n > s.max_samples)
460string fmt_num(
double x)
463 snprintf(buf,
sizeof(buf),
"%.6g", x);
480void emit_guarantee(
const char *kind,
double eps,
double delta,
481 unsigned long samples,
long clauses,
const char *tool)
485 string msg =
"approximation-guarantee: kind=" + string(kind)
486 +
" eps=" + fmt_num(eps);
488 msg +=
" delta=" + fmt_num(delta);
490 msg +=
" samples=" + std::to_string(samples);
492 msg +=
" clauses=" + std::to_string(clauses);
494 msg +=
" tool=" + string(tool);
499bool is_approx_wmc_tool(
const string &tool)
501 return tool ==
"weightmc" || tool ==
"approxmc";
505double eps_from_wmc_opt(
const string &opt)
507 auto semi = opt.find(
';');
508 if(semi == string::npos)
511 return (parse_double_full(opt.substr(semi + 1), e) && e > 0.) ? e : 0.8;
525unsigned long monte_carlo_samples(
const MethodArgs &a)
527 SampleSpec s = parse_sample_spec(a,
"monte-carlo");
528 unsigned long n = s.fixed
530 : finalize_adaptive(ceil(log(2.0 / s.delta) / (2.0 * s.eps * s.eps)), s);
533 const double eps = s.fixed
534 ? sqrt(log(2.0 / 0.05) / (2.0 *
static_cast<double>(n))) : s.eps;
535 const double delta = s.fixed ? 0.05 : s.delta;
536 emit_guarantee(
"additive", eps, delta, n, -1,
nullptr);
550string wmc_opt_from_args(
const MethodArgs &a,
const char *method)
552 if(!a.positional.empty()) {
553 if(a.has(
"epsilon") || a.has(
"delta"))
554 provsql_error(
"method '%s': give either the legacy 'delta;epsilon' or "
555 "epsilon=/delta=, not both", method);
556 if(a.positional.size() > 1)
557 provsql_error(
"method '%s': too many positional arguments", method);
558 return a.positional[0];
560 reject_unknown_keys(a, {
"epsilon",
"delta"}, method);
563 double eps = 0.8, delta = 0.5;
564 parse_eps_delta(a, method, eps, delta);
565 return (a.has(
"delta") ? a.get(
"delta") :
string()) +
";"
566 + (a.has(
"epsilon") ? a.get(
"epsilon") :
string());
591 const std::vector<gate_t> &clauses,
592 const std::vector<std::set<gate_t> > &supports,
595 const size_t m = clauses.size();
596 const double e = exp(1.0);
597 const double mm = (m == 0) ? 1. : static_cast<double>(m);
598 SampleSpec s = parse_sample_spec(a,
"karp-luby");
601 double r = c.
karpLuby(clauses, supports, s.samples);
603 sqrt(4.0 * (e - 2.0) * mm * log(2.0 / 0.05) /
static_cast<double>(s.samples));
604 emit_guarantee(
"relative", eps, 0.05, s.samples,
static_cast<long>(m),
nullptr);
609 const double Y = 4.0 * (e - 2.0) * log(2.0 / s.delta) / (s.eps * s.eps);
610 const double Y1 = 1.0 + (1.0 + s.eps) * Y;
611 const unsigned long cap =
612 s.has_max ? s.max_samples : finalize_adaptive(ceil(Y1 * mm), s);
613 unsigned long used = 0;
614 bool reached =
false;
617 if(reached || used == 0) {
618 emit_guarantee(
"relative", s.eps, s.delta, used,
static_cast<long>(m),
nullptr);
621 sqrt(4.0 * (e - 2.0) * mm * log(2.0 / 0.05) /
static_cast<double>(used));
623 "%lu-sample cap before the (epsilon=%g, delta=%g) target; "
624 "reporting the relative guarantee achieved at the samples "
625 "spent", cap, s.eps, s.delta);
626 emit_guarantee(
"relative", eps, 0.05, used,
static_cast<long>(m),
nullptr);
637 return mobiusProbabilityImpl(token);
655 const std::unordered_map<gate_t, gate_t> &gc_to_bc,
657 std::map<gate_t, StructuredDNNFBuilder::InputKey> &out)
659 std::set<gate_t> seen;
660 std::stack<gate_t> st;
662 while (!st.empty()) {
663 gate_t g = st.top(); st.pop();
664 if (!seen.insert(g).second)
continue;
671 auto it = gc_to_bc.find(w[0]);
672 if (it != gc_to_bc.end())
683 std::set<gate_t> bseen;
684 std::stack<gate_t> bst;
686 while (!bst.empty()) {
687 gate_t g = bst.top(); bst.pop();
688 if (!bseen.insert(g).second)
continue;
690 if (out.find(g) == out.end())
714 const std::map<gate_t, StructuredDNNFBuilder::InputKey> &keys)
716 std::vector<std::pair<gate_t, StructuredDNNFBuilder::InputKey>> v(
717 keys.begin(), keys.end());
718 std::sort(v.begin(), v.end(), [](
const auto &a,
const auto &b) {
719 const auto &ka = a.second, &kb = b.second;
720 if (ka.root != kb.root) return ka.root < kb.root;
721 if (ka.sec != kb.sec) return ka.sec < kb.sec;
722 int ga = (ka.factor == StructuredDNNFBuilder::GUARD_FACTOR) ? 0 : 1;
723 int gb = (kb.factor == StructuredDNNFBuilder::GUARD_FACTOR) ? 0 : 1;
724 if (ga != gb) return ga < gb;
725 if (ka.factor != kb.factor) return ka.factor < kb.factor;
726 return a.first < b.first;
728 std::map<gate_t, int> rank;
730 for (
const auto &p : v) rank[p.first] = r++;
744 std::string ex = gc.
getExtra(gc_root);
747 "carries no inversion-free certificate");
749 std::unordered_map<gate_t, gate_t> gc_to_bc;
751 std::map<gate_t, StructuredDNNFBuilder::InputKey> keys;
753 throw CircuitException(
"compile 'inversion-free': the certificate's inputs "
754 "lack per-input order markers");
773 const MethodArgs &a,
double &result,
774 std::string &actual_method);
891 return std::ldexp(1.0,
static_cast<int>(std::min<size_t>(k, 60)));
933 c.rewriteMultivaluedGates();
1037 for(
unsigned i = 0; i < 8; ++i) {
1040 const std::string text = gc->
getExtra(g);
1041 if(text.rfind(
"route:", 0) == 0) {
1042 const std::string name = text.substr(6);
1055 const auto [info1, info2] = gc->
getInfos(g);
1056 const unsigned tag =
1073 std::string name()
const override {
return "independent"; }
1075 bool inDefaultChain()
const override {
return true; }
1078 bool handlesMultivalued()
const override {
return true; }
1080 double estimatedCost(
const EvalContext &ctx,
const Tolerance &)
const override {
1088 bool applicable(
const EvalContext &ctx,
const Tolerance &)
const override {
1089 return !ctx.linked_group
1092 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1093 double r = ctx.c.independentEvaluation(ctx.gate);
1094 ctx.actual_method =
"independent";
1117 RouteMethod(
provsql_route route, std::string name, std::string requirement)
1118 : route_(route), name_(std::move(name)),
1119 requirement_(std::move(requirement)) {}
1121 std::string name()
const override {
return name_; }
1123 bool inDefaultChain()
const override {
return true; }
1126 bool handlesMultivalued()
const override {
return true; }
1128 double estimatedCost(
const EvalContext &ctx,
const Tolerance &)
const override {
1131 bool applicable(
const EvalContext &ctx,
const Tolerance &)
const override {
1132 return rootRoute(ctx.gc, ctx.gc_root) == route_;
1134 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1138 if(ctx.explicitly_named && rootRoute(ctx.gc, ctx.gc_root) != route_)
1140 requirement_.c_str());
1141 double r = ctx.c.independentEvaluation(ctx.gate);
1142 ctx.actual_method = name_;
1148 const std::string name_;
1149 const std::string requirement_;
1155 std::string name()
const override {
return "inversion-free"; }
1157 bool inDefaultChain()
const override {
return true; }
1159 double estimatedCost(
const EvalContext &ctx,
const Tolerance &)
const override {
1160 const double N =
static_cast<double>(ctx.n_inputs);
1162 * (
static_cast<double>(ctx.circuit_size) + N * std::log2(N < 2 ? 2. : N));
1164 bool applicable(
const EvalContext &ctx,
const Tolerance &)
const override {
1170 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1171 if(ctx.explicitly_named && !ctx.inv_free_cert)
1172 provsql_error(
"method 'inversion-free' requires an inversion-free "
1173 "certificate on the provenance root (none is attached "
1174 "to the rows of a join that merges no rows and uses no "
1175 "relation twice: 'independent' applies to them)");
1176 std::map<gate_t, StructuredDNNFBuilder::InputKey> keys;
1179 if(ctx.explicitly_named)
1180 provsql_error(
"method 'inversion-free': the provenance root carries a "
1181 "certificate but its inputs lack per-input order markers");
1183 throw CircuitException(
"inversion-free: inputs lack per-input order "
1188 ctx.actual_method =
"inversion-free";
1205 std::string name()
const override {
return "mobius"; }
1207 bool inDefaultChain()
const override {
return true; }
1210 double estimatedCost(
const EvalContext &ctx,
const Tolerance &)
const override {
1213 bool applicable(
const EvalContext &ctx,
const Tolerance &)
const override {
1214 return ctx.gc !=
nullptr
1215 && ctx.gc->getGateType(ctx.gc_root) ==
gate_mobius;
1217 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1218 if(ctx.gc ==
nullptr || ctx.gc->getGateType(ctx.gc_root) !=
gate_mobius)
1219 provsql_error(
"method 'mobius' requires a Möbius-route token (a "
1220 "gate_mobius signed-combination root)");
1221 ctx.actual_method =
"mobius";
1222 return mobiusProbabilityImpl(ctx.token);
1229static bool evalOptActive(
int setting,
const EvalContext &ctx)
1239template<
typename BuildOn>
1240static double evaluateViaDD(
EvalContext &ctx,
const std::string &builder,
1244 const bool fold = evalOptActive(
provsql_idp_fold, ctx) && !ctx.fold_component;
1246 return buildOn(ctx.c, ctx.gate, ctx).probabilityEvaluation();
1251 options.fold = fold;
1252 if(ctx.explicitly_named)
1253 options.required_builder = builder;
1254 options.last_builder = [&ctx]() {
return ctx.actual_method; };
1255 options.report = &report;
1258 [&](
const BooleanCircuit &cc,
gate_t g) { return buildOn(cc, g, ctx); },
1260 ctx.actual_method = report.describe();
1283 std::string name()
const override {
return "interpret-as-dd"; }
1285 bool producesDD()
const override {
return true; }
1292 double estimatedCost(
const EvalContext &ctx,
const Tolerance &)
const override {
1295 dDNNF buildDD(EvalContext &ctx)
const override {
1296 dDNNF dd = ctx.c.interpretAsDD(ctx.gate);
1297 ctx.actual_method =
"interpret-as-dd";
1300 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1311 std::string name()
const override {
return "tree-decomposition"; }
1313 bool inDefaultChain()
const override {
return true; }
1314 bool producesDD()
const override {
return true; }
1322 std::vector<Feature> requiredFeatures()
const override {
1325 bool applicable(
const EvalContext &ctx,
const Tolerance &)
const override {
1337 double estimatedCost(
const EvalContext &ctx,
const Tolerance &)
const override {
1338 return std::max(ctx.treedec_cost_floor_,
1344 struct PartOutOfReach {};
1350 static dDNNF buildOn(
const BooleanCircuit &cc,
gate_t g, EvalContext &ctx) {
1351 const bool whole = &cc == &ctx.c;
1354 const bool budgeted = !ctx.explicitly_named && std::isfinite(ctx.cost_budget);
1355 const double size = whole ?
static_cast<double>(ctx.circuit_size)
1356 : static_cast<double>(cc.getNbGates());
1357 const double remaining = ctx.cost_budget - ctx.treedec_spent_;
1366 const double w = ratio >= 1. ? std::floor(std::log2(ratio)) : 0.;
1367 width_cap =
static_cast<unsigned>(
1370 TreeDecomposition td(cc, width_cap);
1380 if(budgeted && real_cost > remaining) {
1382 ctx.tw_proxy_ = std::max(ctx.tw_proxy_,
1383 static_cast<unsigned>(td.getTreewidth()));
1384 reprice(ctx, real_cost,
1385 "tree-decomposition: discovered treewidth exceeds the budget");
1387 dDNNF dd = dDNNFTreeDecompositionBuilder{cc, g, td}.build();
1388 ctx.treedec_spent_ += real_cost;
1389 ctx.actual_method =
"tree-decomposition";
1391 }
catch(TreeDecompositionException &) {
1392 if(ctx.explicitly_named && whole)
1395 if(ctx.explicitly_named)
1396 throw PartOutOfReach();
1401 ctx.tw_proxy_ = std::max(ctx.tw_proxy_, width_cap + 1);
1402 throw MethodRepricedException(
1403 "tree-decomposition: treewidth above the bound");
1409 throw PartOutOfReach();
1411 "tree-decomposition: treewidth above the bound");
1419 [[noreturn]]
static void reprice(EvalContext &ctx,
double part_cost,
1421 ctx.treedec_cost_floor_ =
1422 std::max(ctx.treedec_cost_floor_, ctx.treedec_spent_ + part_cost);
1423 throw MethodRepricedException(why);
1425 dDNNF buildDD(EvalContext &ctx)
const override {
1426 ctx.treedec_spent_ = 0.;
1427 return buildOn(ctx.c, ctx.gate, ctx);
1429 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1430 ctx.treedec_spent_ = 0.;
1432 return evaluateViaDD(ctx,
"tree-decomposition", buildOn);
1433 }
catch(PartOutOfReach &) {
1438 return buildOn(ctx.c, ctx.gate, ctx).probabilityEvaluation();
1450 std::string name()
const override {
return "compilation"; }
1452 bool inDefaultChain()
const override {
return true; }
1453 bool producesDD()
const override {
return true; }
1460 double estimatedCost(
const EvalContext &ctx,
const Tolerance &)
const override {
1461 const double s =
static_cast<double>(ctx.circuit_size);
1462 return std::max(ctx.compilation_cost_floor_,
1466 static dDNNF buildOn(
const BooleanCircuit &cc,
gate_t g, EvalContext &ctx) {
1474 const std::string compiler =
1475 ctx.explicitly_named ? ctx.args : std::string();
1485 const bool budgeted = !ctx.explicitly_named && std::isfinite(ctx.cost_budget);
1486 const double limit_ms =
1489 const auto reprice = [&](
const char *why) {
1490 ctx.compilation_cost_floor_ =
1491 std::max(ctx.compilation_cost_floor_, limit_ms);
1492 throw MethodRepricedException(why);
1494 if(budgeted && ctx.compilation_spent_ms_ >= limit_ms)
1495 reprice(
"compilation: time limit reached");
1496 const auto t0 = std::chrono::steady_clock::now();
1499 ExternalToolTimeLimit limit(
1500 budgeted ? limit_ms - ctx.compilation_spent_ms_ : 0.);
1502 }
catch(ExternalToolTimeout &e) {
1505 ctx.compilation_spent_ms_ += std::chrono::duration<double, std::milli>(
1506 std::chrono::steady_clock::now() - t0).count();
1509 ctx.actual_method = used.empty() ?
"compilation" :
"compilation:" + used;
1512 dDNNF buildDD(EvalContext &ctx)
const override {
1513 ctx.compilation_spent_ms_ = 0.;
1514 return buildOn(ctx.c, ctx.gate, ctx);
1516 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1517 ctx.compilation_spent_ms_ = 0.;
1520 std::string builder =
"compilation";
1521 if(ctx.explicitly_named)
1523 return evaluateViaDD(ctx, builder, buildOn);
1532 std::string name()
const override {
return "possible-worlds"; }
1534 bool inDefaultChain()
const override {
return true; }
1536 double estimatedCost(
const EvalContext &ctx,
const Tolerance &)
const override {
1540 bool applicable(
const EvalContext &ctx,
const Tolerance &)
const override {
1543 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1547 if(ctx.explicitly_named && !ctx.args.empty())
1550 double r = ctx.c.possibleWorlds(ctx.gate);
1551 ctx.actual_method =
"possible-worlds";
1560 std::string name()
const override {
return "monte-carlo"; }
1564 bool inDefaultChain()
const override {
return true; }
1565 bool isDeterministic()
const override {
return false; }
1567 double estimatedCost(
const EvalContext &ctx,
const Tolerance &tol)
const override {
1568 if(tol.epsilon <= 0.)
return std::numeric_limits<double>::infinity();
1570 * std::log(2.0 / tol.delta)
1571 / (tol.epsilon * tol.epsilon);
1573 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1574 unsigned long samples = monte_carlo_samples(parse_method_args(ctx.args));
1575 double r = ctx.c.monteCarlo(ctx.gate,
static_cast<unsigned>(samples));
1576 ctx.actual_method =
"monte-carlo";
1586 std::string name()
const override {
return "karp-luby"; }
1588 bool inDefaultChain()
const override {
return true; }
1589 bool isDeterministic()
const override {
return false; }
1592 std::vector<Feature> requiredFeatures()
const override {
1595 bool applicable(
const EvalContext &ctx,
const Tolerance &)
const override {
1600 double estimatedCost(
const EvalContext &ctx,
const Tolerance &tol)
const override {
1601 if(tol.epsilon <= 0.)
return std::numeric_limits<double>::infinity();
1602 const double m =
static_cast<double>(ctx.dnf_num_clauses_ > 0
1603 ? ctx.dnf_num_clauses_ : 1);
1604 return kCostKarpLuby *
static_cast<double>(ctx.circuit_size) * m
1605 * std::log(2.0 / tol.delta)
1606 / (tol.epsilon * tol.epsilon);
1608 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1609 std::vector<gate_t> clauses;
1610 std::vector<std::set<gate_t> > supports;
1611 if(!ctx.c.dnfShape(ctx.gate, clauses, supports)) {
1612 provsql_warning(
"method 'karp-luby' applies only to a DNF-shaped circuit "
1613 "(a monotone OR-of-ANDs over input leaves); negation, "
1614 "comparison, aggregation, random-variable and "
1615 "multivalued-input gates are not supported");
1616 provsql_error(
"method 'karp-luby' requires a DNF-shaped provenance "
1619 double r = evaluate_karp_luby(ctx.c, clauses, supports,
1620 parse_method_args(ctx.args));
1621 ctx.actual_method =
"karp-luby";
1634 std::string name()
const override {
return "stopping-rule"; }
1636 bool inDefaultChain()
const override {
return true; }
1637 bool isDeterministic()
const override {
return false; }
1641 double estimatedCost(
const EvalContext &ctx,
const Tolerance &tol)
const override {
1642 if(tol.epsilon <= 0.)
return std::numeric_limits<double>::infinity();
1644 * std::log(2.0 / tol.delta)
1645 / (tol.epsilon * tol.epsilon);
1647 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1663 std::string name()
const override {
return "sieve"; }
1665 bool inDefaultChain()
const override {
return true; }
1668 std::vector<Feature> requiredFeatures()
const override {
1671 bool applicable(
const EvalContext &ctx,
const Tolerance &)
const override {
1676 double estimatedCost(
const EvalContext &ctx,
const Tolerance &)
const override {
1678 return std::numeric_limits<double>::infinity();
1679 return kCostSieve *
static_cast<double>(ctx.circuit_size)
1682 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1686 if(ctx.explicitly_named && !ctx.args.empty())
1691 std::vector<gate_t> clauses;
1692 std::vector<std::set<gate_t> > supports;
1693 if(!ctx.c.dnfShape(ctx.gate, clauses, supports)) {
1694 provsql_warning(
"method 'sieve' applies only to a DNF-shaped circuit "
1695 "(a monotone OR-of-ANDs over input leaves); negation, "
1696 "comparison, aggregation, random-variable and "
1697 "multivalued-input gates are not supported");
1698 provsql_error(
"method 'sieve' requires a DNF-shaped provenance circuit");
1700 double r = ctx.c.sieve(clauses, supports);
1701 ctx.actual_method =
"sieve";
1714 std::string name()
const override {
return "d-tree"; }
1716 bool inDefaultChain()
const override {
return true; }
1724 std::vector<Feature> requiredFeatures()
const override {
1731 bool applicable(
const EvalContext &,
const Tolerance &)
const override {
1738 double estimatedCost(
const EvalContext &ctx,
const Tolerance &tol)
const override {
1739 const double S =
static_cast<double>(ctx.circuit_size);
1748 const double footprint = ctx.dnf_ok_ ? 0.
1750 return std::max(ctx.dtree_cost_floor_,
1762 return std::numeric_limits<double>::infinity();
1763 const double m =
static_cast<double>(ctx.dnf_num_clauses_ > 0
1764 ? ctx.dnf_num_clauses_ : 1);
1767 double evaluate(EvalContext &ctx,
const Tolerance &tol)
const override {
1771 std::vector<gate_t> clause_roots;
1772 std::vector<std::set<gate_t> > supports;
1773 const bool is_dnf = ctx.c.dnfShape(ctx.gate, clause_roots, supports);
1774 ctx.actual_method =
"d-tree";
1780 double eps = tol.epsilon;
1782 MethodArgs a = parse_method_args(ctx.args);
1783 if(a.has(
"epsilon")) {
1784 double dummy_delta = 0.;
1785 parse_eps_delta(a,
"d-tree", eps, dummy_delta);
1794 max_width = 2. * eps;
1803 ctx.c.dnfBounds(supports, l0, u0);
1807 max_width = 2. * eps * l0;
1818 unsigned long budget_steps = 0;
1819 if(!ctx.explicitly_named && std::isfinite(ctx.cost_budget)) {
1822 budget_steps =
static_cast<unsigned long>(
1823 std::max(1.0, ctx.cost_budget / ms_per_step));
1827 budget_steps = (budget_steps == 0) ? cap : std::min(budget_steps, cap);
1834 double budget_ms = 0.;
1835 if(!ctx.explicitly_named && std::isfinite(ctx.cost_budget))
1836 budget_ms = std::max(50., 10. * ctx.cost_budget);
1838 unsigned long steps = 0;
1839 provsql::DTreeInterval iv;
1846 }
catch(CircuitException &e) {
1849 if(ctx.explicitly_named || !std::isfinite(ctx.cost_budget)
1852 ctx.dtree_cost_floor_ = 2. * ctx.cost_budget;
1853 throw MethodRepricedException(e.
what());
1856 provsql_notice(
"calibrate kind=dtree path=%s S=%zu N=%zu steps=%lu budget=%lu",
1857 is_dnf ?
"dnf" :
"circuit", ctx.circuit_size, ctx.n_inputs,
1858 steps, budget_steps);
1859 const double est = 0.5 * (iv.
lower + iv.
upper);
1864 const double half = 0.5 * (iv.
upper - iv.
lower);
1866 emit_guarantee(
"relative", half / est, 0., 0, -1,
nullptr);
1868 emit_guarantee(
"additive", half, 0., 0, -1,
nullptr);
1877 std::string name()
const override {
return "weightmc"; }
1879 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1880 std::string opt = wmc_opt_from_args(parse_method_args(ctx.args),
"weightmc");
1881 emit_guarantee(
"relative", eps_from_wmc_opt(opt), -1., 0, -1,
"weightmc");
1882 double r = ctx.c.wmcCount(ctx.gate,
"weightmc", opt);
1883 ctx.actual_method =
"weightmc";
1891 std::string name()
const override {
return "wmc"; }
1893 double evaluate(EvalContext &ctx,
const Tolerance &)
const override {
1894 MethodArgs a = parse_method_args(ctx.args);
1895 std::string tool, tool_args;
1896 if(a.has(
"tool") || a.has(
"epsilon") || a.has(
"delta")) {
1897 reject_unknown_keys(a, {
"tool",
"epsilon",
"delta"},
"wmc");
1898 tool = a.get(
"tool");
1899 if(tool.empty() && !a.positional.empty())
1900 tool = a.positional[0];
1902 provsql_error(
"method 'wmc' requires a tool (tool=<name>)");
1903 if(a.has(
"epsilon") || a.has(
"delta")) {
1904 double eps = 0.8, delta = 0.5;
1905 parse_eps_delta(a,
"wmc", eps, delta);
1906 tool_args = a.get(
"delta") +
";" + a.get(
"epsilon");
1909 auto sep = ctx.args.find(
';');
1910 tool = (sep == std::string::npos) ? ctx.args : ctx.args.substr(0, sep);
1911 tool_args = (sep == std::string::npos) ? std::string()
1912 : ctx.args.substr(sep + 1);
1914 if(is_approx_wmc_tool(tool))
1915 emit_guarantee(
"relative", eps_from_wmc_opt(tool_args), -1., 0, -1,
1917 double r = ctx.c.wmcCount(ctx.gate, tool, tool_args);
1919 ctx.actual_method = tool.empty() ?
"wmc" :
"wmc:" + tool;
1935 +
"' does not construct a d-DNNF");
1943 std::string no_args;
1945 c, g,
nullptr,
false, no_args,
1985template<
class R,
class Run,
class Dropped>
1986R runPortfolio(EvalContext &ctx,
const Tolerance &tol,
1987 std::vector<const ProbabilityMethod *> portfolio, Run run,
2000 std::set<Feature> acquired;
2001 std::string last_error;
2002 bool have_last_error =
false;
2007 const ProbabilityMethod *best =
nullptr;
2008 double best_cost = std::numeric_limits<double>::infinity();
2009 double second_cost = std::numeric_limits<double>::infinity();
2010 std::set<Feature> pending;
2011 for(
const ProbabilityMethod *m : portfolio) {
2013 for(
Feature f : m->requiredFeatures())
2014 if(acquired.find(f) == acquired.end()) { ready =
false; pending.insert(f); }
2015 if(!ready || !m->applicable(ctx, tol))
2017 double cost = m->estimatedCost(ctx, tol);
2018 if(cost < best_cost) { second_cost = best_cost; best_cost = cost; best = m; }
2019 else if(cost < second_cost) { second_cost = cost; }
2025 ctx.cost_budget = second_cost;
2028 bool have_pending =
false;
2030 double cheapest_fc = std::numeric_limits<double>::infinity();
2032 double fc = ctx.featureCost(f);
2033 if(fc < cheapest_fc) { cheapest_fc = fc; cheapest_f = f; have_pending =
true; }
2038 if(std::min(best !=
nullptr ? best_cost
2039 : std::numeric_limits<double>::infinity(),
2040 have_pending ? cheapest_fc
2041 : std::numeric_limits<double>::infinity())
2043 throw CircuitException(
2044 "an evaluation outside the Boolean circuit is cheaper");
2046 if(best !=
nullptr && (!have_pending || best_cost <= cheapest_fc)) {
2052 if(!best->handlesMultivalued())
2053 ctx.ensureMultivaluedRewritten();
2058 auto t0 = std::chrono::steady_clock::now();
2060 double ms = std::chrono::duration<double, std::milli>(
2061 std::chrono::steady_clock::now() - t0).count();
2062 provsql_notice(
"calibrate kind=method which=%s S=%zu N=%zu m=%zu w=%u "
2063 "D=%u cost=%g ms=%g", best->name().c_str(),
2064 ctx.circuit_size, ctx.n_inputs, ctx.dnf_num_clauses_,
2065 ctx.tw_proxy_, ctx.tw_max_degree_, best_cost, ms);
2074 "budget=%g newcost=%g why=%s", best->name().c_str(),
2075 ctx.circuit_size, best_cost, second_cost,
2076 best->estimatedCost(ctx, tol), e.what());
2080 if(!have_last_error) {
2081 last_error = e.what();
2082 have_last_error =
true;
2084 }
catch(CircuitException &e) {
2089 "budget=%g why=%s", best->name().c_str(),
2090 ctx.circuit_size, best_cost, second_cost, e.
what());
2091 last_error = e.
what();
2092 have_last_error =
true;
2093 portfolio.erase(std::remove(portfolio.begin(), portfolio.end(), best),
2095 if(std::optional<R> r = dropped(best))
2096 return std::move(*r);
2098 }
else if(have_pending) {
2100 auto t0 = std::chrono::steady_clock::now();
2101 ctx.acquireFeature(cheapest_f);
2102 double ms = std::chrono::duration<double, std::milli>(
2103 std::chrono::steady_clock::now() - t0).count();
2104 provsql_notice(
"calibrate kind=feature which=%s S=%zu cost=%g ms=%g",
2107 ctx.circuit_size, cheapest_fc, ms);
2109 ctx.acquireFeature(cheapest_f);
2111 acquired.insert(cheapest_f);
2115 throw CircuitException(last_error);
2116 throw CircuitException(
"no applicable probability method in the portfolio");
2125 std::vector<const ProbabilityMethod *> portfolio;
2132 && (tol.
delta > 0. || m->isDeterministic()))
2133 portfolio.push_back(m.get());
2136 return std::optional<double>();
2144 return runPortfolio<double>(ctx, tol, std::move(portfolio),
2147 const std::vector<const ProbabilityMethod *> all = portfolio;
2149 -> std::optional<double> {
2150 if(failed->name() !=
"independent")
2151 return std::nullopt;
2154 return std::nullopt;
2156 return std::nullopt;
2160 struct NothingToFold {};
2162 std::vector<std::string> used;
2170 const double p = runPortfolio<double>(sub, tol, all,
2173 if(std::find(used.begin(), used.end(), sub.
actual_method) == used.end())
2177 eval.
whole = []() ->
double {
throw NothingToFold(); };
2180 std::string name =
"fold";
2181 for(
const std::string &u : used)
2186 }
catch(NothingToFold &) {
2198 return std::nullopt;
2200 return runPortfolio<double>(ctx, tol, std::move(portfolio),
2211 std::vector<const ProbabilityMethod *> portfolio;
2214 portfolio.push_back(m.get());
2215 return runPortfolio<dDNNF>(ctx, tol, std::move(portfolio),
2235 "a provenance root produced by the safe-query "
2236 "(read-once) rewriter"));
2239 "a provenance root produced by the joint-width UCQ "
2243 "a provenance root produced by the reachability "
2282 std::unordered_set<gate_t> seen;
2283 std::vector<gate_t> stack{root};
2284 while(!stack.empty()) {
2285 const gate_t g = stack.back();
2287 if(!seen.insert(g).second)
2292 std::vector<std::vector<std::size_t> > adj(l.
n);
2293 for(std::size_t j = 0; j < l.
n; ++j)
2294 for(
const auto &t : l.
out[j])
2295 adj[j].push_back(t.first);
2296 std::vector<std::size_t> comp_of(l.
n);
2298 for(std::size_t c = 0; c < comps.size(); ++c)
2299 for(
const auto v : comps[c])
2301 for(std::size_t c = 0; c < comps.size(); ++c) {
2302 if(comps[c].size() < 2)
2305 for(
const auto i : comps[c])
2306 for(
const auto &t : l.
in[i])
2307 if(comp_of[t.first] == c)
2310 2. *
static_cast<double>(comps[c].size() - 1) * terms;
2321 const std::string &method,
2322 const std::string &args,
2323 bool inv_free_cert,
const Tolerance &tol,
2325 std::string *actual_method_out)
2328 const bool is_path =
2329 method.empty() || method ==
"default" || method ==
"exact";
2336 bool skip_boolean_view =
false;
2337 double outside_cost = std::numeric_limits<double>::infinity();
2346 * std::log(2.0 / tol.
delta)
2351 outside_cost = sampling;
2352 }
else if(too_large) {
2354 skip_boolean_view =
true;
2358 "the Boolean circuit of this recursion on cyclic data would have "
2359 "about " + std::to_string(
static_cast<long long>(e.
expanded_gates))
2360 +
" gates, too many to build "
2361 "for an exact probability; ask for an approximation instead "
2362 "('additive' or 'relative', or 'monte-carlo'), which solves the "
2363 "recursion in each sampled world");
2378 if (!skip_boolean_view && !
circuitHasRV(gc, root) && !nested_agg &&
2379 !(sampleable_agg && tol.
delta > 0.)) {
2382 std::unordered_map<gate_t, gate_t> gc_to_bc;
2384 EvalContext ctx{&gc, root, token, c, gate, &gc_to_bc,
2385 inv_free_cert, args, !is_path,
2397 provsql_error(
"Wrong method '%s' for probability evaluation",
2405 if (actual_method_out !=
nullptr)
2420 "a deterministic (delta = 0) guarantee is not available for this "
2421 "circuit: it carries random-variable or HAVING-aggregate gates, for "
2422 "which only the (eps,delta) samplers apply -- use delta > 0");
2427 if (actual_method_out !=
nullptr) *actual_method_out = am;
2431 if (actual_method_out !=
nullptr) *actual_method_out =
"monte-carlo";
2433 gc, root,
static_cast<int>(monte_carlo_samples(parse_method_args(args))));
2441 "booleanSubcircuitProbability: a random-variable comparator could not "
2442 "be resolved to a Boolean and no Monte Carlo fallback is available "
2443 "(provsql.rv_mc_samples = 0)");
2444 if (actual_method_out !=
nullptr) *actual_method_out =
"monte-carlo";
2475 const MethodArgs &a,
double &result,
2476 std::string &actual_method)
2478 SampleSpec s = parse_sample_spec(a,
"stopping-rule");
2480 provsql_error(
"the relative / stopping-rule estimator is adaptive: give "
2481 "epsilon=E[,delta=D][,max_samples=M], not a fixed sample "
2483 const unsigned long cap = s.has_max ? s.max_samples : 10000000UL;
2484 unsigned long used = 0;
2485 bool reached =
false;
2488 if(reached || used == 0) {
2489 emit_guarantee(
"relative", s.eps, s.delta, used, -1,
"stopping-rule");
2491 const double eps_add = sqrt(log(2.0 / 0.05) / (2.0 * used));
2492 provsql_warning(
"relative estimate: reached the %lu-sample cap before the "
2493 "(epsilon=%g, delta=%g) relative target; reporting the "
2494 "additive guarantee at the samples spent (the event is "
2495 "likely rarer than this budget resolves -- raise "
2496 "max_samples)", cap, s.eps, s.delta);
2497 emit_guarantee(
"additive", eps_add, 0.05, used, -1,
"stopping-rule");
2499 actual_method =
"stopping-rule";
2508 if(actual_method.empty())
2511 bool changed =
false;
2513 while(start <= actual_method.size()) {
2514 size_t end = actual_method.find(
',', start);
2515 if(end == std::string::npos)
2516 end = actual_method.size();
2517 const std::string name = actual_method.substr(start, end - start);
2521 && (
"," + current +
",").find(
"," + name +
",") == std::string::npos) {
2522 if(!current.empty()) current +=
",";
2529 SetConfigOption(
"provsql.last_eval_method", current.c_str(),
2530 PGC_USERSET, PGC_S_SESSION);
2556 std::unordered_set<gate_t> seen;
2557 std::stack<gate_t> todo;
2561 while(!todo.empty()) {
2564 if(!seen.insert(g).second)
continue;
2569 most = std::max(most,
static_cast<unsigned>(gc.
getWires(g).size()));
2573 return any ? std::max(most, 1u) : 0;
2577 (
pg_uuid_t token,
const string &method,
const string &args,
bool *isnull)
2579 if(isnull !=
nullptr)
2605 const auto &w = gc.
getWires(gc_root);
2607 provsql_error(
"probability_evaluate: this is a conditioned distribution "
2608 "(a random_variable / agg_token X | C), not a Boolean "
2609 "event; query it with expected / variance / moment / "
2610 "support, which report the conditional distribution");
2612 provsql_error(
"probability_evaluate: malformed conditioned gate "
2613 "(expected 3 children [target, evidence, joint], got %zu)",
2617 bool ev_null =
false, jt_null =
false;
2618 double pe = DatumGetFloat8(
2620 if(ev_null || pe == 0.) {
2621 if(isnull !=
nullptr)
2625 double pj = DatumGetFloat8(
2628 if(isnull !=
nullptr)
2633 if(r > 1.) r = 1.;
else if(r < 0.) r = 0.;
2634 PG_RETURN_FLOAT8(r);
2650 const bool is_path =
2651 method.empty() || method ==
"default" || method ==
"exact"
2652 || method ==
"relative" || method ==
"additive";
2653 if(is_path || method ==
"mobius") {
2656 std::unordered_map<gate_t, gate_t> dummymap;
2665 PG_RETURN_FLOAT8(r);
2669 const std::string lineage = mobiusLineageOf(token);
2671 provsql_error(
"method '%s': this Möbius-route token carries no literal "
2672 "lineage (it was built measure-only); only the default / "
2673 "'mobius' method applies", method.c_str());
2686 bool inv_free_cert =
false;
2688 std::string ex = gc.
getExtra(gc_root);
2692 inv_free_cert =
true;
2698 provsql_notice(
"inversion-free certificate read back from circuit "
2699 "root: %d atoms, %d classes, root_class=%d",
2730 const bool mc_default = method.empty() || method ==
"default";
2731 if (method !=
"monte-carlo" && method !=
"stopping-rule"
2732 && method !=
"relative" && method !=
"additive"
2736 "probability_evaluate: a comparison over random variables "
2737 "could not be resolved analytically; raise "
2738 "provsql.rv_mc_samples above 0 to enable the Monte Carlo "
2739 "fallback, or call probability_evaluate(..., 'monte-carlo', "
2741 }
else if (!mc_default) {
2743 "probability_evaluate: a comparison over random variables "
2744 "could not be resolved analytically and the hybrid evaluator "
2745 "left it unresolved; call probability_evaluate(..., "
2746 "'monte-carlo', <n>) directly for an MC estimate");
2770 const bool named = !(method.empty() || method ==
"default");
2780 const unsigned cap =
2781 (named || nested_agg)
2784 std::optional<double> p;
2793 return Float8GetDatum(*p);
2796 provsql_error(
"probability_evaluate: method %s needs a circuit whose "
2797 "only random sources are at most %u input tuples",
2806 string actual_method;
2819 if(method ==
"relative" || method ==
"additive") {
2832 SampleSpec s = parse_sample_spec(parse_method_args(args), method.c_str());
2842 gc, gc_root,
"", args, inv_free_cert, tol,
2843 false, &actual_method);
2844 }
else if(method ==
"stopping-rule") {
2847 }
else if(method ==
"monte-carlo"
2856 unsigned long samples = monte_carlo_samples(parse_method_args(args));
2870 actual_method =
"monte-carlo";
2880 false, &actual_method);
2904 PG_RETURN_FLOAT8(result);
2913 Datum token = PG_GETARG_DATUM(0);
2920 if(!PG_ARGISNULL(1)) {
2921 text *t = PG_GETARG_TEXT_P(1);
2922 method = string(VARDATA(t),VARSIZE(t)-VARHDRSZ);
2925 if(!PG_ARGISNULL(2)) {
2926 text *t = PG_GETARG_TEXT_P(2);
2927 args = string(VARDATA(t),VARSIZE(t)-VARHDRSZ);
2930 bool isnull =
false;
2943 "resolve remains in the circuit (%s): supported are a "
2944 "comparison of an aggregate with a constant, between "
2945 "numeric aggregates, and between two array_agg results",
2947 }
catch(
const std::exception &e) {
2975 pg_uuid_t token = *DatumGetUUIDP(PG_GETARG_DATUM(0));
2980 std::vector<gate_t> clause_roots;
2981 std::vector<std::set<gate_t> > supports;
2982 if(!c.
dnfShape(root, clause_roots, supports))
2983 provsql_error(
"probability_bounds applies only to a DNF-shaped circuit "
2984 "(a monotone OR-of-ANDs over input leaves); negation, "
2985 "comparison, aggregation, random-variable and "
2986 "multivalued-input gates are not supported");
2988 double lower, upper;
2992 if(get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
2993 provsql_error(
"probability_bounds: expected composite return type");
2994 tupdesc = BlessTupleDesc(tupdesc);
2996 Datum values[2] = { Float8GetDatum(lower), Float8GetDatum(upper) };
2997 bool nulls[2] = {
false,
false };
2998 PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
2999 }
catch(
const std::exception &e) {
Exact closed-form HAVING COUNT(*) op C probability over safe-join lineage – the recursive marginal-ve...
Closed-form CDF resolution for trivial gate_cmp shapes.
Boolean-expression (lineage formula) semiring.
Boolean provenance circuit with support for knowledge compilation.
constexpr unsigned DNNF_CERT_INFO
d-DNNF certificate value for the (gate-type-specific) per-gate info field.
BooleanGate
Gate types for a Boolean provenance circuit.
@ OR
Logical disjunction of child gates.
@ AND
Logical conjunction of child gates.
@ IN
Input (variable) gate representing a base tuple.
static CircuitCache cache
Process-local singleton circuit gate cache.
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.
The single comparator-resolution pipeline and the single Boolean-subcircuit probability entry point,...
Closed-form Poisson-binomial CDF resolution for HAVING COUNT(*) op C gate_cmps.
Anytime interval-bounds probability for monotone DNFs (d-trees).
Strongly connected components of the dependency graph of an equation system (a recursive query,...
std::vector< std::vector< std::size_t > > fixSystemComponents(const std::vector< std::vector< std::size_t > > &out)
Strongly connected components of a directed graph, in the order in which equations along its edges ca...
Semiring-agnostic in-memory provenance circuit.
Peephole simplifier for continuous gate_arith sub-circuits.
Closed-form probability resolution for HAVING MIN(a) op C and MAX(a) op C gate_cmps.
Monte Carlo sampling over a GenericCircuit, RV-aware.
Cache of compiled d-DNNFs, and folding of independent parts.
Catalog of probability-evaluation methods (Strategy + registry).
Support-based bound check for continuous-RV comparators.
Abstract semiring interface for provenance evaluation.
In-process structured-d-DNNF construction over a query-derived variable order, for the inversion-free...
Closed-form probability resolution for HAVING SUM(a) op C gate_cmps via a weighted-sum DP.
Tree decomposition of a Boolean circuit for knowledge compilation.
Fix macro conflicts between PostgreSQL headers and the C++ STL/Boost.
Boolean circuit for provenance formula evaluation.
double karpLubyStopping(const std::vector< gate_t > &clauses, const std::vector< std::set< gate_t > > &supports, double eps, double delta, unsigned long max_samples, unsigned long &samples_used, bool &reached_target) const
Karp-Luby FPRAS with the self-adjusting stopping rule (adaptive sample count for a relative (eps,...
const std::set< gate_t > & getInputs() const
Return the set of input (IN) gate IDs.
double karpLuby(const std::vector< gate_t > &clauses, const std::vector< std::set< gate_t > > &supports, unsigned long samples) const
Karp-Luby FPRAS estimate of a DNF-shaped circuit's probability (fixed sample budget,...
dDNNF compilation(gate_t g, std::string compiler, std::string *resolved=nullptr) const
Compile the sub-circuit rooted at g to a dDNNF via an external tool.
void dnfBounds(const std::vector< std::set< gate_t > > &clauses, double &lower, double &upper) const
Cheap certified probability interval [lower,upper] of a monotone DNF, without compiling it (Olteanu-H...
bool dnfShape(gate_t g, std::vector< gate_t > &clauses, std::vector< std::set< gate_t > > &supports) const
Detect the DNF shape the Karp-Luby FPRAS requires.
static std::string checkCompiler(std::string compiler)
Exception type thrown by circuit operations on invalid input.
virtual char const * what() const noexcept
Return the error message as a C-string.
CircuitException(const std::string &m)
Construct with a descriptive error message.
A refusal by design, or a known gap, rather than an error.
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< gate_t >::size_type getNbGates() const
Return the total number of gates in the circuit.
FixSystemLinear linearizeFixSystem(gate_t sys) const
The equations of the gate_fixsystem sys, as linear forms over the gates that do not depend on its unk...
std::string getExtra(gate_t g) const
Return the string extra for gate g.
double getProb(gate_t g) const
Return the probability for gate g.
std::pair< unsigned, unsigned > getInfos(gate_t g) const
Return the integer annotation pair for gate g.
Top-down structured-d-DNNF builder over a query-derived variable order.
const dDNNF & dnnf() const
The constructed d-DNNF (root set, simplified).
static unsigned degeneracyLowerBound(const BooleanCircuit &bc, unsigned &max_degree)
Cheap degeneracy lower bound on the treewidth of bc's primal graph.
static constexpr int MAX_TREEWIDTH
Maximum supported treewidth.
A d-DNNF circuit supporting exact probabilistic and game-theoretic evaluation.
double probabilityEvaluation() const
Compute the exact probability of the d-DNNF being true.
Registry of ProbabilityMethod objects.
const ProbabilityMethod * byName(const std::string &name) const
Exact match on name(); nullptr if absent.
std::vector< std::unique_ptr< ProbabilityMethod > > methods_
double chooseAndRun(EvalContext &ctx, const Tolerance &tol) const
Run the auto-chooser for tol: the portfolio methods admissible for the tolerance and applicable,...
void registerMethod(std::unique_ptr< ProbabilityMethod > m)
static const MethodCatalog & instance()
The process-wide catalog, lazily populated with the built-in methods.
dDNNF chooseAndBuildDD(EvalContext &ctx, const Tolerance &tol) const
The d-DNNF analogue of chooseAndRun: cost-select among the producesDD() portfolio (interpret-as-dd / ...
Thrown by a method that gave up under its budget but learned a tighter cost estimate: the chooser kee...
CircuitException(const std::string &m)
Construct with a descriptive error message.
Strategy interface: one concrete subclass per probability method.
virtual dDNNF buildDD(EvalContext &ctx) const
Build the d-DNNF this method constructs (only when producesDD()).
virtual double evaluate(EvalContext &ctx, const Tolerance &tol) const =0
Run the method, returning the probability.
virtual bool handlesMultivalued() const
True iff the method evaluates the raw circuit, including multivalued (BID / gate_mulinput) gates,...
virtual std::string name() const =0
Stable identifier used for byName lookup and the provsql.last_eval_method report.
The SIGINT handler installed for the lifetime of the object, the previous one restored as it ends (a ...
Exception thrown when a semiring operation is not supported.
virtual char const * what() const noexcept
Return the error message as a C-string.
A gate kind this semiring does not interpret (a comparison, a semimodule multiplication,...
Constructs a d-DNNF from a Boolean circuit and its tree decomposition.
Provenance evaluation helper for HAVING-clause circuits.
Shared declaration for the Möbius-route probability sweep.
double probFoldedProbability(const BooleanCircuit &c, gate_t root, const ProbFoldEval &eval)
Probability of the circuit below root, folding the independent groups of AND and OR gates from the ro...
static const double kCostDnfShapeFeature
static const double kCostSieve
static const double kCostDTreeFootprint
DTreeInterval dtreeBounds(const BooleanCircuit &c, Clauses clauses, double max_width, unsigned long budget, unsigned long *steps_out, double budget_ms)
static const size_t kPossibleWorldsSanityMax
Sanity bound on the reachable-input count for the auto-chosen 2^N possible-worlds enumeration: above ...
double booleanSubcircuitProbability(GenericCircuit &gc, gate_t root, const std::string &method, const std::string &args, bool inv_free_cert, const Tolerance &tol, bool mc_fallback, std::string *actual_method_out)
Probability of the Boolean function rooted at root in gc – THE single entry point over the method por...
static const double kCostKarpLuby
std::optional< double > enumerateBooleanProbability(const GenericCircuit &gc, gate_t root, unsigned max_inputs)
The probability of root, exactly, over the possible worlds of the circuit as it is: the alternative t...
DTreeInterval dtreeBoundsCircuit(const BooleanCircuit &c, gate_t root, double max_width, unsigned long budget, unsigned long *steps_out, double budget_ms)
Certified probability interval of an arbitrary Boolean circuit, refined to a target width (the d-tree...
static const double kCostDTreeExact
static const double kCostTwProxyFeature
bool circuitHasNestedAggValue(const GenericCircuit &gc, gate_t root)
Whether a contribution of an aggregate is itself an aggregate result (a gate_semimod whose M side is ...
static const double kCostDTreeMsPerStepGeneral
static const double kCostCompilationFloor
static bool toleranceAdmits(ToleranceKind request, ToleranceKind method)
Admissibility of a method's guarantee under a requested tolerance.
double monteCarloRVStopping(const GenericCircuit &gc, gate_t root, double eps, double delta, unsigned long max_samples, unsigned long &samples_used, bool &reached_target)
Whole-circuit (eps,delta)-relative probability via the Dagum-Karp-Luby-Ross stopping rule.
static const double kCostStoppingRule
static const double kCostPossibleWorlds
bool circuitHasUnresolvedSampleableAgg(const GenericCircuit &gc, gate_t root)
Whether a surviving gate_agg exists and every one is sample-faithful (SUM / AVG / MIN / MAX / COUNT –...
Feature
A circuit feature a method's cost/applicability estimate depends on, but that is not free to acquire.
static const double kCompilationMinLimitMs
static const double kCostDTreeApprox
static const double kCostInversionFree
ToleranceKind
The contract the user grants – the "path".
static ExpansionEstimate estimateBooleanExpansion(const GenericCircuit &gc, gate_t root)
static const double kCostTreeDecomp
static const double kCostDTreeMsPerStepDnf
static const double kMaxBooleanExpansion
static double pow2_clamped(size_t k)
2^k with the exponent clamped to keep the cost finite (a clamped exponent still sorts the method dead...
bool circuitHasFixpoint(const GenericCircuit &gc, gate_t root)
Whether a gate_fixpoint (a row of a recursion on cyclic data) is reachable from root.
static const double kCostMonteCarlo
static const double kCostCompilation
static const double kCostBooleanExpansion
double monteCarloRV(const GenericCircuit &gc, gate_t root, unsigned samples)
Run Monte Carlo on a circuit that may contain gate_rv leaves.
double probCachedProbability(const BooleanCircuit &c, gate_t root, const ProbCacheCompileFn &compile, bool *ran_compiler, const ProbCacheOptions &options)
Probability of the circuit below root through the fold and the cache.
static const double kCompilationBudgetFactor
bool probCacheEligible(const BooleanCircuit &c, gate_t root)
Whether the circuit below root is one the cache and the fold handle: AND, OR and NOT gates over input...
bool circuitHasRV(const GenericCircuit &gc, gate_t root)
Walk the circuit reachable from root looking for any gate_rv.
dDNNF makeDDAuto(BooleanCircuit &c, gate_t g)
Cost-select a d-DNNF construction route for gate g of Boolean circuit c and build it – the default ma...
void resolveComparators(GenericCircuit &gc, gate_t root, bool simplify, bool decompose)
Run the comparator-resolution pipeline on gc, rewriting every gate_cmp (RV comparison,...
static const size_t kSieveSanityMaxClauses
Largest clause count for which the auto-chosen sieve (2^m inclusion-exclusion) is admitted (matches B...
static const double kCostIndependent
Datum probability_evaluate(PG_FUNCTION_ARGS)
PostgreSQL-callable wrapper for probability_evaluate().
static Datum probability_evaluate_internal(pg_uuid_t token, const string &method, const string &args, bool *isnull)
static std::map< gate_t, int > inversion_free_rank(const std::map< gate_t, StructuredDNNFBuilder::InputKey > &keys)
Flatten the per-input order keys into a total rank for the structured builder's order-only constructo...
static const char *const kPossibleWorldsAgg
Core implementation of probability evaluation for a circuit token.
double mobius_probability_of(pg_uuid_t token)
External entry point for the Möbius-route probability sweep (declared in mobius_evaluate....
Datum probability_bounds(PG_FUNCTION_ARGS)
PostgreSQL-callable wrapper for the d-tree leaf bound: probability_bounds(token uuid,...
static const unsigned kPossibleWorldsAggMaxInputs
Most inputs it enumerates the 2^n worlds of.
static void record_last_eval_method(const std::string &actual_method)
Record the method just used in the provsql.last_eval_method GUC (comma-separated, deduplicated across...
dDNNF buildInversionFreeDDNNF(pg_uuid_t token)
Compile a query certified inversion-free to its structured d-DNNF.
static bool collect_inversion_free_keys(const GenericCircuit &gc, gate_t gc_root, const std::unordered_map< gate_t, gate_t > &gc_to_bc, const BooleanCircuit &c, gate_t bc_root, std::map< gate_t, StructuredDNNFBuilder::InputKey > &out)
Collect the inversion-free per-input order keys for the structured builder.
static void run_stopping_rule(GenericCircuit &gc, gate_t gc_root, const MethodArgs &a, double &result, std::string &actual_method)
Whole-circuit (eps,delta)-relative estimate via the stopping rule (shared by the explicit 'stopping-r...
static unsigned maxAggContributions(const GenericCircuit &gc, gate_t root)
The most contributions an aggregation gate below root has, 0 when neither a comparison nor an aggrega...
bool provsql_absorptive_provenance
Derived flag: the session's provenance class is 'absorptive' or 'boolean' – licenses constructions so...
int provsql_verbose
Verbosity level; controlled by the provsql.verbose_level GUC.
bool provsql_simplify_on_load
Run universal cmp-resolution passes when getGenericCircuit returns; controlled by the provsql....
bool provsql_inversion_free
Insert the inversion-free structured-d-DNNF path into the default probability chain (after independen...
char * provsql_last_eval_method
Last probability evaluation method(s) used; exposed via provsql.last_eval_method.
int provsql_rv_mc_samples
Default sample count for analytical-evaluator MC fallbacks; 0 disables fallback (callers raise instea...
int provsql_dtree_max_subproblems
Debug/safety hard cap on d-tree subproblems before it bails (0 = off; the chooser auto-budgets at the...
int provsql_idp_fold
Backing variable of provsql.idp_fold: when an AND or OR root is split into independent groups evaluat...
bool provsql_interrupted
Set by provsql_sigint_handler: this backend received a cancel.
bool provsql_boolean_provenance
Derived flag: the session's provenance class is 'boolean' – enables the Boolean-only machinery (safe-...
int provsql_prob_cache
Backing variable of provsql.prob_cache: when the per-backend cache of compiled d-DNNFs,...
#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.
#define provsql_warning(fmt,...)
Emit a ProvSQL warning message (execution continues).
#define provsql_notice(fmt,...)
Emit a ProvSQL informational notice (execution continues).
void provsql_cancel_if_interrupted(void)
Raise PG's cancel if the evaluation stopped for one; nothing otherwise.
Cancellation of the long C++ evaluation loops.
Background worker and IPC primitives for mmap-backed circuit storage.
Shared-memory segment and inter-process pipe management.
Core types, constants, and utilities shared across ProvSQL.
@ PROVSQL_EVAL_OPT_ON
Also applied to a method called by name.
@ PROVSQL_EVAL_OPT_AUTO
Applied by the default method only (default).
@ gate_annotation
Transparent single-child wrapper carrying a query-level annotation in extra (inversion-free certifica...
@ gate_mobius
Signed Möbius combination: a MEASURE-only gate carrying one integer coefficient per child (in extra,...
@ gate_conditioned
Conditioning marker with two children [target, evidence]: measure-only, probability_evaluate returns ...
@ gate_fixsystem
Linear equation system x_i = f_i(x) of a recursive query, one equation per derived tuple: wires [x_1,...
@ gate_assumed
Structural marker over a single child whose sub-circuit was computed under a Boolean-provenance assum...
provsql_route
Tags identifying the planner-time route that produced a circuit.
@ PROVSQL_ROUTE_BOUNDED_JW
Joint-width UCQ compiler (src/UCQJointCompiler.h).
@ PROVSQL_ROUTE_SQ_REWRITE
Hierarchical-CQ read-once rewrite (src/safe_query.c).
@ PROVSQL_ROUTE_NONE
No route rewrite: ordinary lineage.
@ PROVSQL_ROUTE_REACHABILITY
Recursive-reachability compiler (src/reachability_evaluate.cpp).
static const char * provsql_route_name(provsql_route route)
The name of a route, as the probability dispatcher reports it and as the annotation wrapper of a mate...
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.
C++ utility functions for UUID manipulation.
SafeCert * safe_cert_parse(const char *str)
Parse a C-prefixed recipe string (as produced by safe_cert_serialise and read back from an annotation...
bool safe_cert_key_parse(const char *str, SafeCertKey *out)
Parse a K-prefixed order-key string into out.
Tractability certificate for the inversion-free UCQ(OBDD) path.
@ CERT_INVERSION_FREE
Inversion-free UCQ(OBDD) over TID inputs.
#define SAFE_CERT_EXTRA_PREFIX_RECIPE
Discriminator prefixes for the annotation gate's extra payload.
In-memory provenance circuit with semiring-generic evaluation.
std::size_t n
Number of unknowns.
std::vector< std::vector< std::pair< std::size_t, std::vector< gate_t > > > > in
Terms of each equation.
std::vector< std::vector< std::pair< std::size_t, std::vector< gate_t > > > > out
Terms, by unknown read.
Query-derived order recipe for the structured-d-DNNF builder.
int nclasses
Number of (compacted) equivalence classes.
int root_class
Compacted id of the root class (touches every atom).
int natoms
Number of atoms (range-table entries).
Per-evaluation circuit state threaded to a method's evaluate().
bool multivalued_rewritten
double cost_budget
Speculative-execution budget: the estimated cost (in the chooser's ms-ish units) of the next-cheapest...
double treedec_cost_floor_
Lower bound on tree-decomposition's cost, raised when the parts it builds (islands,...
bool hasFeature(Feature f) const
void ensureMultivaluedRewritten()
double featureCost(Feature f) const
Heuristic acquisition cost of f, in the same work units as a method's estimatedCost (so the chooser c...
double compilation_spent_ms_
Time, in ms, the external compiler has run in the current attempt.
size_t n_inputs
input count N (O(1) cost feature)
double dtree_cost_floor_
Lower bound on the d-tree's cost, raised each time it overruns a budget.
std::unordered_map< gate_t, gate_t > * gc_to_bc
void ensureDnfShape() const
std::string actual_method
void acquireFeature(Feature f)
bool explicitly_named
invoked via byName (vs the default chain)
void ensureTreewidthProxy() const
double outside_cost
Cost of an evaluation outside this Boolean view (sampling the equation systems of a recursion directl...
double treedec_spent_
Cost of the parts tree-decomposition has built in the current attempt.
size_t circuit_size
gate count S, the circuit-size parameter (O(1))
double compilation_cost_floor_
Lower bound on compilation's cost, raised when the external compiler is stopped for running past its ...
std::size_t dnf_num_clauses_
Size of a circuit with recursions on cyclic data, and of its Boolean expansion: the gates reachable f...
double expanded_gates
Gates of the Boolean expansion.
double circuit_gates
Gates reachable from the root.
What probCachedProbability may do, and what it reports back.
bool use_cache
Look compiled d-DNNFs up, and store new ones.
What a call to probCachedProbability actually did, so the caller can report it instead of the method ...
How probFoldedProbability evaluates what it cannot fold.
std::function< double()> whole
Probability of the whole circuit, when its root has nothing to fold.
std::function< double(BooleanCircuit &, gate_t, bool)> part
Probability of a part, given as a circuit of its own and its root; the flag tells a group of several ...
bool evaluate(const std::vector< long > &values, const std::vector< bool > &mask, long constant, ComparisonOperator op, std::unique_ptr< Aggregator > aggregator)
Evaluate whether the aggregation of values masked by mask satisfies op constant.