-- ---------------------------------------------------------------------- -- provsql 1.14.0 -> 1.14.1 -- -- * A row an aggregate reads no value from (a NULL argument, a row its -- FILTER leaves out) stays in the aggregate's family, as a semimod over -- the new constant gate_novalue(). -- * add_provenance fills the provsql column by a table rewrite and -- analyzes it. -- * Random UUIDs come from gen_random_uuid(), built in from PostgreSQL 13 -- on, instead of the uuid_generate_v4() of uuid-ossp. -- ---------------------------------------------------------------------- SET search_path TO provsql; -- ---------------------------------------------------------------------- -- 1. Rows an aggregate reads no value from -- ---------------------------------------------------------------------- CREATE OR REPLACE FUNCTION gate_novalue() RETURNS uuid AS $$ SELECT public.uuid_generate_v5(provsql.uuid_ns_provsql(),'novalue'); $$ LANGUAGE SQL IMMUTABLE PARALLEL SAFE; CREATE OR REPLACE FUNCTION provenance_semimod_skipping(val anyelement, token UUID) RETURNS UUID AS 'provsql','provenance_semimod_skipping' LANGUAGE C COST 100 PARALLEL SAFE IMMUTABLE; CREATE OR REPLACE FUNCTION agg_valued_children(token uuid) RETURNS uuid[] AS $$ SELECT coalesce(array_agg(c ORDER BY o), ARRAY[]::uuid[]) FROM unnest(provsql.get_children(token)) WITH ORDINALITY AS u(c, o) WHERE NOT (provsql.get_gate_type(c) = 'semimod' AND (provsql.get_children(c))[2] = provsql.gate_novalue()) $$ LANGUAGE sql STABLE STRICT PARALLEL SAFE SET search_path=provsql,pg_temp,public; CREATE OR REPLACE FUNCTION agg_possible_values(input anyelement, with_null boolean DEFAULT false) RETURNS text[] AS $$ DECLARE max_values CONSTANT int := 1000; -- an explosion multiplies the rows token uuid; fn text; ns text; vals text[]; n int; counted int; first int; sums numeric[]; one numeric; scalar_agg boolean; arms uuid[]; cv uuid; cvals text[]; BEGIN /* The planner hands the aggregate result itself (an agg_token), whatever * the type the query declares for that column. */ IF pg_typeof(input) <> 'provsql.agg_token'::regtype THEN RAISE EXCEPTION USING ERRCODE = 'feature_not_supported', MESSAGE = 'ProvSQL: only the result of an aggregate can be exploded ' 'into one row per value it takes over the possible worlds', DETAIL = 'provsql-reason: explode-not-an-aggregate; scope: deliberate'; END IF; token := input::uuid; IF provsql.get_gate_type(token) = 'case' THEN /* A guarded selection -- COALESCE(sum(x), 0), a CASE over aggregates -- * takes the values of its arms, [guard_1, value_1, ..., default]: an * aggregate's own, or a constant's. Each arm is selected where its * aggregate has a value, so an aggregate arm offers no NULL. */ arms := provsql.get_children(token); vals := ARRAY[]::text[]; FOR i IN 1 .. coalesce(array_length(arms, 1), 0) LOOP CONTINUE WHEN i % 2 = 1 AND i < array_length(arms, 1); CASE provsql.get_gate_type(arms[i]) WHEN 'value' THEN /* gate_null(), the value of an aggregate with no contribution at * all, is never selected: its guard, that the aggregate has a value, * holds in no world. The guarded selections exploded here * (COALESCE onto a constant) are never NULL. */ IF coalesce(provsql.get_extra(arms[i]), '') NOT IN ('', 'NULL') THEN vals := vals || provsql.get_extra(arms[i]); END IF; WHEN 'agg', 'case' THEN vals := vals || provsql.agg_possible_values( provsql.agg_token_make(arms[i], 0)); ELSE RAISE EXCEPTION USING ERRCODE = 'feature_not_supported', MESSAGE = 'ProvSQL: an arithmetic expression over aggregate ' 'results cannot be exploded into one row per value it ' 'takes over the possible worlds', DETAIL = 'provsql-reason: explode-arithmetic; scope: gap'; END CASE; END LOOP; vals := ARRAY(SELECT DISTINCT v FROM unnest(vals) AS v); IF array_length(vals, 1) > max_values THEN RAISE EXCEPTION USING ERRCODE = 'feature_not_supported', MESSAGE = format('ProvSQL: this expression over aggregate results ' 'takes more than %s values over the possible worlds, ' 'too many to explode it into one row per value', max_values), HINT = 'mark it plain() to read its plain value', DETAIL = 'provsql-reason: explode-too-many-values; scope: gap'; END IF; RETURN ARRAY(SELECT v FROM unnest(vals) AS v ORDER BY v::numeric NULLS LAST); END IF; IF provsql.get_gate_type(token) <> 'agg' THEN RAISE EXCEPTION USING ERRCODE = 'feature_not_supported', MESSAGE = 'ProvSQL: an arithmetic expression over aggregate results ' 'cannot be exploded into one row per value it takes over ' 'the possible worlds', DETAIL = 'provsql-reason: explode-arithmetic; scope: gap'; END IF; SELECT p.proname, s.nspname INTO fn, ns FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace s ON s.oid = p.pronamespace WHERE p.oid = (provsql.get_infos(token)).info1; vals := ARRAY(SELECT provsql.get_extra((provsql.get_children(sm))[2]) FROM unnest(provsql.agg_valued_children(token)) AS sm); n := coalesce(array_length(vals, 1), 0); /* NULL is a value of the aggregate like any other -- the one it takes where * no row contributes, which an aggregation over the whole table reaches in * the world holding none of its rows (a grouped one has no row there at all). * Whether to offer it is the caller's to decide: the rewriting asks for it * only where it can annotate that row with the aggregate having no value, * and never for a count, which is 0 rather than NULL over no row. */ scalar_agg := with_null; IF (ns, fn) = ('pg_catalog', 'count') THEN /* A count contributes 1 per row it counts and 0 per row it does not -- a * row whose value is NULL, as the null-padded row of an outer join is -- * so its values are the numbers of rows counted, up to how many there are * to count. Zero is one of them where a row that is not counted can be * the only one there, or where the aggregation is over the whole table; a * group of counted rows only has none of its rows in no world, a group * being no group without a row. */ counted := (SELECT count(*) FROM unnest(vals) AS v WHERE v IS NOT NULL AND v <> '0'); first := CASE WHEN (provsql.get_infos(token)).info2 < 0 OR counted < n THEN 0 ELSE 1 END; IF counted + 1 - first > max_values THEN RAISE EXCEPTION USING ERRCODE = 'feature_not_supported', MESSAGE = format('ProvSQL: the result of %s() aggregates %s rows, ' 'so it takes too many values over the possible ' 'worlds to explode it into one row per value', fn, n), HINT = 'mark it plain() to read its plain value', DETAIL = 'provsql-reason: explode-too-many-values; scope: gap'; END IF; RETURN ARRAY(SELECT i::text FROM generate_series(least(first, counted), counted) AS i); END IF; IF (ns, fn) NOT IN (('pg_catalog', 'min'), ('pg_catalog', 'max'), ('pg_catalog', 'sum'), ('provsql', 'choose')) THEN RAISE EXCEPTION USING ERRCODE = 'feature_not_supported', MESSAGE = format('ProvSQL: the result of %s() cannot be exploded into ' 'one row per value it takes over the possible worlds: ' 'only count(), min(), max(), sum() and choose() have ' 'values that can be enumerated', fn), HINT = 'compare it in a HAVING clause, or mark it plain() to read its ' 'plain value', DETAIL = 'provsql-reason: explode-aggregate-kind; scope: gap'; END IF; /* An aggregate of aggregate results -- sum(revenue) over a view of * totals -- has contributions that are no constants but aggregate results * themselves, each taking several values: their own (agg_possible_values * of their gate), a NULL among them contributing nothing. A sum takes the * subset sums choosing one value of each contribution there, a minimum * (maximum, choice) one of their values. The combinations no world * realises (two contributions that depend on each other) are emitted too, * and their rows have a provenance of zero. */ IF EXISTS (SELECT 1 FROM unnest(provsql.agg_valued_children(token)) AS sm WHERE provsql.get_gate_type(sm) = 'semimod' AND provsql.get_gate_type((provsql.get_children(sm))[2]) <> 'value') THEN sums := ARRAY[]::numeric[]; vals := ARRAY[]::text[]; FOR cv IN SELECT (provsql.get_children(sm))[2] FROM unnest(provsql.agg_valued_children(token)) AS sm WHERE provsql.get_gate_type(sm) = 'semimod' LOOP cvals := CASE WHEN provsql.get_gate_type(cv) = 'value' THEN ARRAY[provsql.get_extra(cv)] ELSE provsql.agg_possible_values( provsql.agg_token_make(cv, 0)) END; cvals := ARRAY(SELECT v FROM unnest(cvals) AS v WHERE coalesce(v, '') NOT IN ('', 'NULL')); IF (ns, fn) = ('pg_catalog', 'sum') THEN sums := ARRAY(SELECT DISTINCT s FROM (SELECT unnest(sums) AS s UNION ALL SELECT v::numeric FROM unnest(cvals) AS v UNION ALL SELECT a + b::numeric FROM unnest(sums) AS a, unnest(cvals) AS b) AS u); ELSE vals := ARRAY(SELECT DISTINCT v FROM (SELECT unnest(vals) AS v UNION ALL SELECT unnest(cvals)) AS u); END IF; IF coalesce(array_length(sums, 1), 0) > max_values OR coalesce(array_length(vals, 1), 0) > max_values THEN RAISE EXCEPTION USING ERRCODE = 'feature_not_supported', MESSAGE = format('ProvSQL: the result of %s() takes more than %s ' 'values over the possible worlds, too many to ' 'explode it into one row per value', fn, max_values), HINT = 'mark it plain() to read its plain value', DETAIL = 'provsql-reason: explode-too-many-values; scope: gap'; END IF; END LOOP; IF (ns, fn) = ('pg_catalog', 'sum') THEN RETURN ARRAY(SELECT s::text FROM unnest(sums) AS s ORDER BY s) || CASE WHEN scalar_agg THEN ARRAY[NULL::text] ELSE ARRAY[]::text[] END; END IF; RETURN ARRAY(SELECT v FROM unnest(vals) AS v ORDER BY v) || CASE WHEN scalar_agg THEN ARRAY[NULL::text] ELSE ARRAY[]::text[] END; END IF; IF EXISTS (SELECT 1 FROM unnest(vals) AS v WHERE v IS NULL) THEN RAISE EXCEPTION USING ERRCODE = 'feature_not_supported', MESSAGE = format('ProvSQL: the result of %s() aggregates a NULL value, ' 'so it cannot be exploded into one row per value it ' 'takes over the possible worlds: a comparison with ' 'NULL does not say that the result is NULL', fn), DETAIL = 'provsql-reason: explode-null-value; scope: gap'; END IF; IF (ns, fn) = ('pg_catalog', 'sum') THEN /* The value of a sum is the sum of the rows that are there, so its values * are its subset sums, reached by adding the contributions one at a time, * equal sums collapsing (three rows of 1 take three values, not eight). * The empty subset is the NULL above, which a scalar aggregation takes and * a grouped one does not (a group without a row is no group). The planner only sends sums over an * integer column here, whose subset sums the evaluator's own arithmetic * reaches exactly. */ sums := ARRAY[]::numeric[]; FOREACH one IN ARRAY ARRAY(SELECT v::numeric FROM unnest(vals) AS v) LOOP sums := ARRAY(SELECT DISTINCT s FROM (SELECT unnest(sums) AS s UNION ALL SELECT one UNION ALL SELECT unnest(sums) + one) AS u); IF array_length(sums, 1) > max_values THEN RAISE EXCEPTION USING ERRCODE = 'feature_not_supported', MESSAGE = format('ProvSQL: the result of %s() takes more than %s ' 'values over the possible worlds, too many to ' 'explode it into one row per value', fn, max_values), HINT = 'mark it plain() to read its plain value', DETAIL = 'provsql-reason: explode-too-many-values; scope: gap'; END IF; END LOOP; RETURN ARRAY(SELECT s::text FROM unnest(sums) AS s ORDER BY s) || CASE WHEN scalar_agg THEN ARRAY[NULL::text] ELSE ARRAY[]::text[] END; END IF; IF n > max_values THEN RAISE EXCEPTION USING ERRCODE = 'feature_not_supported', MESSAGE = format('ProvSQL: the result of %s() aggregates %s rows, so ' 'it takes too many values over the possible worlds to ' 'explode it into one row per value', fn, n), HINT = 'mark it plain() to read its plain value', DETAIL = 'provsql-reason: explode-too-many-values; scope: gap'; END IF; /* One row per distinct contributed value: each is the minimum (maximum, * choice) of the world where only its own row is. */ RETURN ARRAY(SELECT DISTINCT v FROM unnest(vals) AS v ORDER BY v) || CASE WHEN scalar_agg THEN ARRAY[NULL::text] ELSE ARRAY[]::text[] END; END $$ LANGUAGE plpgsql STABLE STRICT PARALLEL SAFE; CREATE OR REPLACE FUNCTION agg_gate_null_event(g uuid, want_null boolean) RETURNS uuid AS $$ DECLARE t provsql.provenance_gate; p uuid; parts uuid[]; prev uuid[]; ch uuid[]; region uuid; arm uuid; BEGIN t := provsql.get_gate_type(g); IF t = 'agg' THEN SELECT provsql.provenance_plus(coalesce(array_agg((provsql.get_children(c))[1]), ARRAY[]::uuid[])) INTO p FROM unnest(provsql.agg_valued_children(g)) AS c WHERE provsql.get_gate_type(c) = 'semimod'; RETURN CASE WHEN want_null THEN provsql.provenance_monus(provsql.gate_one(), p) ELSE p END; ELSIF t = 'arith' THEN SELECT array_agg(provsql.agg_gate_null_event(c, want_null)) INTO parts FROM unnest(provsql.get_children(g)) AS c; IF parts IS NULL THEN RETURN CASE WHEN want_null THEN provsql.gate_zero() ELSE provsql.gate_one() END; END IF; /* NULL where one operand is; not NULL where every one is not */ RETURN CASE WHEN want_null THEN provsql.provenance_plus(parts) ELSE provsql.provenance_times(VARIADIC parts) END; ELSIF t = 'value' THEN RETURN CASE WHEN (coalesce(provsql.get_extra(g), '') IN ('', 'NULL')) = want_null THEN provsql.gate_one() ELSE provsql.gate_zero() END; ELSIF t = 'case' THEN /* A guarded selection, [guard_1, value_1, ..., default]: NULL (not NULL) * where the arm it selects is -- the arm's region, its guard and none of * the earlier ones (the default: none of them), times the arm's own * event. COALESCE(sum(x), 0) selects the sum where it has a value and 0 * elsewhere, so is NULL nowhere. */ parts := ARRAY[]::uuid[]; prev := ARRAY[]::uuid[]; ch := provsql.get_children(g); FOR i IN 1 .. coalesce(array_length(ch, 1), 0) BY 2 LOOP IF i = array_length(ch, 1) THEN region := CASE WHEN cardinality(prev) = 0 THEN provsql.gate_one() ELSE provsql.provenance_monus(provsql.gate_one(), provsql.provenance_plus(prev)) END; arm := ch[i]; ELSE region := CASE WHEN cardinality(prev) = 0 THEN ch[i] ELSE provsql.provenance_times( ch[i], provsql.provenance_monus(provsql.gate_one(), provsql.provenance_plus(prev))) END; arm := ch[i + 1]; prev := prev || ch[i]; END IF; parts := parts || provsql.provenance_times( region, provsql.agg_gate_null_event(arm, want_null)); END LOOP; RETURN provsql.provenance_plus(parts); END IF; RAISE EXCEPTION USING MESSAGE = 'ProvSQL: IS [NOT] NULL on this expression over aggregates, read ' 'from a subquery, is not supported', DETAIL = 'provsql-reason: nulltest-not-aggregate; scope: gap', ERRCODE = 'feature_not_supported'; END $$ LANGUAGE plpgsql STABLE PARALLEL SAFE SET search_path=provsql,pg_temp,public; CREATE OR REPLACE FUNCTION agg_raw_moment( token agg_token, k integer, prov UUID = gate_one(), method text = NULL, arguments text = NULL) RETURNS DOUBLE PRECISION AS $$ DECLARE aggregation_function VARCHAR; child_pairs uuid[]; pair_children uuid[]; n integer; i integer; j integer; vals float8[]; toks uuid[]; total float8; total_probability float8; tup integer[]; d integer; prod_v float8; distinct_tok uuid[]; conj_token uuid; prob float8; sign_max float8; is_scalar boolean; defined_tok uuid; BEGIN IF token IS NULL OR k IS NULL THEN RETURN NULL; END IF; IF k < 0 THEN RAISE EXCEPTION 'agg_raw_moment(): k must be non-negative (got %)', k; END IF; -- Aggregate-carrier CASE (a gate_case over aggregate branches): a first-match -- guarded selection. The moment is CONDITIONAL on the CASE's value being -- defined (NULL only when it never is, mirroring the MIN/MAX convention): -- E[pick^k | defined ∧ prov] -- = Σ_i P(region_i ∧ def_i) · E[value_i^k | region_i ∧ def_i] -- / Σ_i P(region_i ∧ def_i), -- where region_i = (¬g_1 ∧ … ∧ ¬g_{i-1}) ∧ g_i ∧ prov is the world set that -- selects branch i (the default's region is "all guards false") and def_i is -- the branch's defined event (agg_defined_event: gate_one for sum / count / -- constants, "some row present" for min / max / avg, recursive for a nested -- CASE). Both factors are exact: probability() over the region ∧ def event, -- and the conditional aggregate moment (a recursive agg_raw_moment on the -- branch aggregate, which conditions on its own definedness within the -- region, so the two factors weigh the same worlds). The regions are -- mutually exclusive, so the terms sum with no inclusion-exclusion, and -- correlation between a guard and its branch (shared input tuples) is -- carried by the conditioning, exactly as HAVING carries it. When every -- branch is defined everywhere, the defined mass equals P(prov) and the -- formula reduces to the plain region-weighted sum. IF get_gate_type(token) = 'case' THEN IF k = 0 THEN RETURN 1; END IF; DECLARE wires uuid[] := get_children(token); nw integer := array_length(get_children(token), 1); m integer := (array_length(get_children(token), 1) - 1) / 2; running_neg uuid := gate_one(); region_full uuid; prov_p float8; p float8; total float8 := 0; def_mass float8 := 0; ci integer; vuid uuid; bm float8; BEGIN prov_p := probability(prov); IF prov_p IS NULL OR prov_p <= 0 THEN RETURN NULL; -- impossible conditioning event END IF; -- Branches 1..m are the guarded WHENs; branch m+1 is the ELSE default, -- whose region is "all guards false". FOR ci IN 1 .. m + 1 LOOP IF ci <= m THEN region_full := provenance_times(running_neg, wires[2 * ci - 1], prov); vuid := wires[2 * ci]; running_neg := provenance_times(running_neg, provenance_not(wires[2 * ci - 1])); ELSE region_full := provenance_times(running_neg, prov); vuid := wires[nw]; END IF; p := probability(provenance_times(region_full, agg_defined_event(vuid))); IF p > 0 THEN -- E[value_i^k | region_i ∧ def_i]: a constant branch is a Dirac -- (c^k, exact); a single aggregate or nested CASE is exact via -- agg_raw_moment (whose MIN/MAX/CASE arms condition on their own -- definedness within the region); an arithmetic / composite branch -- takes the Monte-Carlo scalar path (which composes with the -- aggregate leaves). IF get_gate_type(vuid) = 'value' THEN bm := power(CAST(get_extra(vuid) AS float8), k); ELSIF get_gate_type(vuid) IN ('agg', 'case') THEN bm := agg_raw_moment(agg_token_make(vuid, 0), k, region_full, method, arguments); ELSE bm := rv_moment(vuid, k, false, region_full); END IF; total := total + p * bm; def_mass := def_mass + p; END IF; END LOOP; IF def_mass <= 0 THEN RETURN NULL; -- the CASE's value is never defined under prov END IF; RETURN total / def_mass; END; END IF; IF get_gate_type(token) <> 'agg' THEN IF get_gate_type(token) IN ('arith', 'conditioned') THEN -- An arithmetic combination of aggregates (SUM(x) + SUM(y), SUM(x) / 2), -- or a conditioning of one: the scalar evaluator, exact over the -- possible worlds of few inputs, sampled otherwise RETURN rv_moment((token)::uuid, k, false, prov); ELSE RAISE EXCEPTION USING MESSAGE='Wrong gate type for agg_raw_moment computation', DETAIL = 'provsql-reason: moment-not-an-aggregate; scope: deliberate'; END IF; END IF; IF k = 0 THEN RETURN 1; END IF; SELECT pp.proname::varchar FROM pg_proc pp WHERE oid=(get_infos(token)).info1 INTO aggregation_function; child_pairs := agg_valued_children(token); n := COALESCE(array_length(child_pairs, 1), 0); -- A contribution whose value is itself an aggregate (an avg of a count, a -- max of a sum, an aggregate of an arithmetic expression over aggregates: -- provenance_semimod_nested) takes one value per possible world, not a -- constant read off its gate, so none of the closed forms below applies to -- it. The scalar evaluator reads such a value in every world. IF EXISTS (SELECT 1 FROM unnest(child_pairs) AS c WHERE get_gate_type((get_children(c))[2]) <> 'value') THEN RETURN rv_moment((token)::uuid, k, false, prov); END IF; IF aggregation_function = 'sum' OR aggregation_function = 'count' THEN -- count(*) and count(col) both keep the COUNT identity at the gate level, -- their value being the SUM of per-row 1 / 0-or-1 indicators, so their -- moments are computed exactly like SUM. -- -- The value exists only where a contributing row does: SUM over no row is -- SQL NULL, and a grouped aggregation has no row there at all. So the -- moment conditions on that event, as the MIN / MAX arms do, and -- @c expected(sum(x)) of a group equals @c expected(sum(x), provenance()). -- A scalar COUNT is the exception: its row is always there and counts a -- real 0 over no row. is_scalar := (get_infos(token)).info2 < 0; -- the scalar flag, high bit -- Extract per-child token + value arrays. vals := ARRAY[]::float8[]; toks := ARRAY[]::uuid[]; FOR i IN 1..n LOOP pair_children := get_children(child_pairs[i]); toks := toks || pair_children[1]; vals := vals || CAST(get_extra(pair_children[2]) AS float8); END LOOP; defined_tok := CASE WHEN aggregation_function = 'count' AND is_scalar THEN gate_one() WHEN n = 0 THEN gate_zero() ELSE provenance_plus(toks) END; IF n = 0 THEN -- No contributing row at all: a real 0 for a scalar COUNT, SQL NULL -- (never defined) otherwise. RETURN CASE WHEN defined_tok = gate_one() THEN 0 ELSE NULL END; END IF; -- Collapsed fast path: a correlated COUNT / SUM whose per-row selection -- events share a single continuous latent has an O(G·n) 1-D quadrature, -- vastly cheaper than the O(n^k) tuple enumeration below (which is the -- O(n^2) pair-probability bottleneck for the variance). Only fires -- unconditionally (prov = one) and for k in {1, 2}; agg_collapsed_moment -- returns NULL when the shared-latent pattern does not match, and we -- fall through to the exact enumeration. Its moment counts the worlds -- without a row as 0, which contribute nothing, so it only needs the -- conditional normalisation below. IF prov = gate_one() AND k <= 2 THEN total := agg_collapsed_moment((token)::uuid, k); IF total IS NOT NULL THEN IF defined_tok = gate_one() THEN RETURN total; END IF; prob := probability_evaluate(defined_tok, method, arguments); IF prob IS NULL OR prob <= 0 THEN RETURN NULL; END IF; RETURN total / prob; END IF; END IF; -- Independent rows: the first two moments from one probability per row. -- Rows of different independence components (agg_row_components: no -- source of randomness in common) are independent, so a pair of them is -- present with the product of their probabilities, and -- E[S] = sum_i v_i p_i, -- E[S^2] = sum_i v_i^2 p_i + (sum_i v_i p_i)^2 - sum_c (sum_{i in c} v_i p_i)^2 -- + sum_{i <> j in one component} v_i v_j P(t_i and t_j): -- n probability evaluations, plus one per pair within a component, -- instead of one per pair -- n^2, each a Monte Carlo estimate when the -- rows' events compare random variables. Unconditional only (an outer -- event couples the rows). IF prov = gate_one() AND k <= 2 THEN DECLARE comp integer[] := agg_row_components((token)::uuid); p float8[] := ARRAY[]::float8[]; s1 float8 := 0; sc float8[]; ncomp integer; pair_tok uuid[]; BEGIN FOR i IN 1..n LOOP p := p || probability_evaluate(toks[i], method, arguments); s1 := s1 + vals[i] * p[i]; END LOOP; IF k = 1 THEN total := s1; ELSE ncomp := (SELECT max(c) FROM unnest(comp) AS c); sc := array_fill(0::float8, ARRAY[ncomp]); total := 0; FOR i IN 1..n LOOP total := total + vals[i] * vals[i] * p[i]; sc[comp[i]] := sc[comp[i]] + vals[i] * p[i]; END LOOP; total := total + s1 * s1; FOR i IN 1..ncomp LOOP total := total - sc[i] * sc[i]; END LOOP; FOR i IN 1..n LOOP FOR j IN 1..n LOOP CONTINUE WHEN i = j OR comp[i] <> comp[j]; pair_tok := ARRAY(SELECT DISTINCT unnest(ARRAY[toks[i], toks[j]])); total := total + vals[i] * vals[j] * CASE WHEN array_length(pair_tok, 1) = 1 THEN p[i] ELSE probability_evaluate(provenance_times(VARIADIC pair_tok), method, arguments) END; END LOOP; END LOOP; END IF; IF defined_tok = gate_one() THEN RETURN total; END IF; prob := probability_evaluate(defined_tok, method, arguments); IF prob IS NULL OR prob <= 0 THEN RETURN NULL; -- never defined: SQL NULL END IF; RETURN total / prob; END; END IF; -- Enumerate all k-tuples (i_1, ..., i_k) in {1..n}^k. tup is the -- current tuple; we step through them in lexicographic order. total := 0; tup := array_fill(1, ARRAY[k]); LOOP prod_v := 1; FOR j IN 1..k LOOP prod_v := prod_v * vals[tup[j]]; END LOOP; SELECT array_agg(DISTINCT toks[idx]) INTO distinct_tok FROM unnest(tup) AS idx; IF prov <> gate_one() THEN distinct_tok := distinct_tok || prov; END IF; conj_token := provenance_times(VARIADIC distinct_tok); prob := probability_evaluate(conj_token, method, arguments); total := total + prod_v * prob; d := k; WHILE d >= 1 AND tup[d] = n LOOP tup[d] := 1; d := d - 1; END LOOP; EXIT WHEN d = 0; tup[d] := tup[d] + 1; END LOOP; -- Conditional on the value existing (and on prov): every k-tuple of the -- sum above names a row, so the worlds without one contribute 0 and only -- the normalisation is left. IF defined_tok <> gate_one() THEN IF prov <> gate_one() THEN defined_tok := provenance_times(prov, defined_tok); END IF; prob := probability_evaluate(defined_tok, method, arguments); IF prob IS NULL OR prob <= 0 THEN RETURN NULL; -- never defined: SQL NULL END IF; RETURN total / prob; -- already conditional; skip the generic norm END IF; ELSIF aggregation_function = 'min' OR aggregation_function = 'max' THEN -- Rank enumeration: per distinct value v, P(MIN = v) is the -- probability that some t_i with v_i=v is true and all t_j with -- smaller v are false. For MAX we negate values so the same -- "smaller-than" rank logic computes MIN-of-negated, then flip. -- The outer multiplier picks up the right sign for the k-th moment -- of MAX: E[MAX^k] = (-1)^k * E[MIN(-v)^k], so sign_max = (-1)^k. sign_max := CASE WHEN aggregation_function = 'max' THEN power(-1::float8, k) ELSE 1 END; -- MIN/MAX over the empty input world are NULL (no elements), not ±Infinity: -- SQL returns one row with a NULL value. The moment is therefore CONDITIONAL -- on the aggregate being defined (non-empty) -- the empty world is excluded -- and the result renormalised by P(prov AND non-empty). (count, whose empty -- value 0 is a real value, keeps the empty world; sum keeps it too, as 0.) IF n = 0 THEN RETURN NULL; -- structurally empty: MIN/MAX undefined END IF; -- Numerator E[MIN^k . 1{prov AND non-empty}] (the rank sum naturally omits -- the empty world, since every term requires a present token). WITH tok_value AS ( SELECT (get_children(c))[1] AS tok, (CASE WHEN aggregation_function='max' THEN -1 ELSE 1 END) * CAST(get_extra((get_children(c))[2]) AS DOUBLE PRECISION) AS v FROM UNNEST(child_pairs) AS c ) SELECT sign_max * COALESCE(SUM(p * power(v, k)), 0) FROM ( SELECT t1.v AS v, probability_evaluate( CASE WHEN prov = gate_one() THEN provenance_monus(provenance_plus(ARRAY_AGG(t1.tok)), provenance_plus(ARRAY_AGG(t2.tok))) ELSE provenance_times(prov, provenance_monus(provenance_plus(ARRAY_AGG(t1.tok)), provenance_plus(ARRAY_AGG(t2.tok)))) END, method, arguments) AS p FROM tok_value t1 LEFT OUTER JOIN tok_value t2 ON t1.v > t2.v GROUP BY t1.v) tmp INTO total; -- Denominator P(prov AND non-empty) = P(prov (x) (+) tokens). SELECT probability_evaluate( CASE WHEN prov = gate_one() THEN provenance_plus(ARRAY_AGG(tok)) ELSE provenance_times(prov, provenance_plus(ARRAY_AGG(tok))) END, method, arguments) FROM (SELECT (get_children(c))[1] AS tok FROM UNNEST(child_pairs) AS c) s INTO total_probability; IF total_probability <= 0 THEN RETURN NULL; -- never defined under prov: MIN/MAX undefined END IF; RETURN total / total_probability; -- already conditional; skip generic norm ELSIF aggregation_function = 'avg' THEN -- AVG = SUM/COUNT is a ratio of two correlated world-dependent -- quantities, so the k-tuple expansion above does not apply. Like -- MIN/MAX, AVG over the empty world is NULL, so its moment conditions -- on the aggregate being defined (COUNT >= 1), NULL when it never is. -- Two routes: -- * EXACT (independent rows, unconditional): the joint (sum, count) -- PMF folded in C by agg_avg_moment_exact -- -- E[AVG^k | COUNT>=1] = Σ_{(s,c), c>=1} (s/c)^k pmf(s,c) / P(c>=1). -- * Monte-Carlo scalar fallback otherwise (an outer conditioning -- event, shared leaves, compound contributors): rv_moment samples -- the agg gate per world; its NaN-skip on empty draws implements -- the same conditional-on-defined convention, at the -- provsql.rv_mc_samples budget (0 raises, per convention). IF n = 0 THEN RETURN NULL; -- structurally empty: AVG undefined END IF; -- Conditioning on an event that AVG being defined implies -- some row -- among a set holding AVG's rows present, as provenance() of a GROUP BY -- row is, the group possibly having rows whose value is NULL -- is what -- the moment already does: the exact route applies. IF prov <> gate_one() THEN DECLARE inner_prov uuid := prov; prov_toks uuid[]; agg_toks uuid[]; BEGIN IF get_gate_type(inner_prov) = 'delta' THEN inner_prov := (get_children(inner_prov))[1]; END IF; IF get_gate_type(inner_prov) = 'plus' THEN prov_toks := get_children(inner_prov); ELSE prov_toks := ARRAY[inner_prov]; END IF; SELECT array_agg((get_children(c))[1]) INTO agg_toks FROM unnest(child_pairs) AS c; IF agg_toks <@ prov_toks THEN prov := gate_one(); END IF; END; END IF; IF prov = gate_one() THEN total := agg_avg_moment_exact((token)::uuid, k); IF total IS NOT NULL THEN RETURN total; END IF; END IF; RETURN rv_moment((token)::uuid, k, false, prov); ELSE RAISE EXCEPTION USING MESSAGE= 'Cannot compute moment for aggregation function ' || aggregation_function, DETAIL = 'provsql-reason: moment-aggregate-kind; scope: gap'; END IF; -- Conditional normalisation: E[X^k · 1_A] / P(A) = E[X^k | A]. IF prov <> gate_one() AND total <> 0 AND total <> 'Infinity'::float8 AND total <> '-Infinity'::float8 THEN total := total / probability_evaluate(prov, method, arguments); END IF; RETURN total; END $$ LANGUAGE plpgsql VOLATILE PARALLEL UNSAFE SET search_path=provsql SECURITY DEFINER; -- ---------------------------------------------------------------------- -- 2. add_provenance, whose body depends on the PostgreSQL version. Both -- are written with uuid_generate_v4(), for section 3 to replace. -- ---------------------------------------------------------------------- DO $do$ BEGIN IF current_setting('server_version_num')::int >= 140000 THEN EXECUTE $sql$ CREATE OR REPLACE FUNCTION add_provenance(_tbl regclass) RETURNS void AS $$ BEGIN -- Idempotence: a second add_provenance on an already-tracked table is -- a no-op with a NOTICE, so setup scripts and notebook cells can be -- re-run freely. IF EXISTS ( SELECT 1 FROM pg_attribute WHERE attrelid = _tbl AND attname = 'provsql' AND NOT attisdropped ) THEN RAISE NOTICE 'table % already has provenance tracking', _tbl; RETURN; END IF; -- See the common-version body for the rationale of dropping the -- column DEFAULT and UNIQUE in favour of provenance_guard + a -- plain index. EXECUTE format( 'ALTER TABLE %s ADD COLUMN provsql UUID DEFAULT public.uuid_generate_v4()', _tbl); EXECUTE format('ALTER TABLE %s ALTER COLUMN provsql DROP DEFAULT', _tbl); EXECUTE format('CREATE INDEX ON %s(provsql)', _tbl); EXECUTE format( 'CREATE TRIGGER provenance_guard BEFORE INSERT OR UPDATE OF provsql ' 'ON %s FOR EACH ROW EXECUTE FUNCTION provsql.provenance_guard()', _tbl); EXECUTE format('CREATE TRIGGER insert_statement AFTER INSERT ON %s REFERENCING NEW TABLE AS NEW_TABLE FOR EACH STATEMENT EXECUTE FUNCTION provsql.insert_statement_trigger()', _tbl); EXECUTE format('CREATE TRIGGER delete_statement AFTER DELETE ON %s REFERENCING OLD TABLE AS OLD_TABLE FOR EACH STATEMENT EXECUTE FUNCTION provsql.delete_statement_trigger()', _tbl); EXECUTE format('CREATE TRIGGER update_statement AFTER UPDATE ON %s REFERENCING OLD TABLE AS OLD_TABLE NEW TABLE AS NEW_TABLE FOR EACH STATEMENT EXECUTE FUNCTION provsql.update_statement_trigger()', _tbl); PERFORM provsql.set_table_info(_tbl::oid, 'tid'); PERFORM provsql.set_ancestors(_tbl::oid, ARRAY[_tbl::oid]); EXECUTE format('ANALYZE %s (provsql)', _tbl); END $$ LANGUAGE plpgsql SECURITY DEFINER; $sql$; ELSE EXECUTE $sql$ CREATE OR REPLACE FUNCTION add_provenance(_tbl regclass) RETURNS void AS $$ BEGIN -- Idempotence: a second add_provenance on an already-tracked table is -- a no-op with a NOTICE, so setup scripts and notebook cells can be -- re-run freely. IF EXISTS ( SELECT 1 FROM pg_attribute WHERE attrelid = _tbl AND attname = 'provsql' AND NOT attisdropped ) THEN RAISE NOTICE 'table % already has provenance tracking', _tbl; RETURN; END IF; -- No DEFAULT: the guard trigger mints the UUID, so the trigger can -- distinguish "user omitted" (NULL) from "user supplied a value". -- No UNIQUE: we no longer rely on it to keep the table TID -- the -- guard does that semantically -- and a UNIQUE would reject the -- legitimate cross-table UUID copy that just flips the table to -- OPAQUE. We keep a plain index for fast UUID-keyed lookups. EXECUTE format( 'ALTER TABLE %s ADD COLUMN provsql UUID DEFAULT public.uuid_generate_v4()', _tbl); EXECUTE format('ALTER TABLE %s ALTER COLUMN provsql DROP DEFAULT', _tbl); EXECUTE format('CREATE INDEX ON %s(provsql)', _tbl); EXECUTE format( 'CREATE TRIGGER provenance_guard BEFORE INSERT OR UPDATE OF provsql ' 'ON %s FOR EACH ROW EXECUTE FUNCTION provsql.provenance_guard()', _tbl); PERFORM provsql.set_table_info(_tbl::oid, 'tid'); -- Seed the base-ancestor set to {self}: a base TID table's atoms -- come from itself and no other relation. CTAS-derived tables -- inherit unions of source ancestor sets; that is handled by the -- CTAS hook (a separate slice), not here. PERFORM provsql.set_ancestors(_tbl::oid, ARRAY[_tbl::oid]); EXECUTE format('ANALYZE %s (provsql)', _tbl); END $$ LANGUAGE plpgsql SECURITY DEFINER; $sql$; END IF; END $do$; -- ---------------------------------------------------------------------- -- 3. Random UUIDs: where gen_random_uuid() is built in, every function of -- the extension that calls uuid_generate_v4() is redefined to call it. -- The comment in repair_key that names the generator changes everywhere. -- ---------------------------------------------------------------------- DO $do$ DECLARE f record; def text; BEGIN FOR f IN SELECT p.oid, pg_get_functiondef(p.oid) AS def FROM pg_proc p JOIN pg_depend d ON d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e' JOIN pg_extension e ON d.refclassid = 'pg_extension'::regclass AND d.refobjid = e.oid JOIN pg_language l ON p.prolang = l.oid WHERE e.extname = 'provsql' AND l.lanname IN ('sql', 'plpgsql') AND p.prokind = 'f' AND p.prosrc LIKE '%uuid_generate_v4()%' LOOP def := replace(f.def, 're-running uuid_generate_v4()', 're-running gen_random_uuid()'); IF current_setting('server_version_num')::int >= 130000 THEN def := replace(def, 'public.uuid_generate_v4()', 'pg_catalog.gen_random_uuid()'); END IF; EXECUTE def; END LOOP; END $do$; -- The planner hook consults provenance_semimod_skipping through the OID -- cache of the session; a backend warmed under 1.14.0 holds InvalidOid for it. SELECT reset_constants_cache();