#!/usr/bin/env python3 """Differential oracle for MergeConstraintsIntoExisting(): random parent/child schemas, then ALTER TABLE ... INHERIT / ATTACH PARTITION; the output is every error message and the resulting catalog rows. Run it with the same seeds against a master server and a patched server (any build) and compare the two files: they must be identical. oracle.py run BINDIR WORKDIR OUT SEED0 NSEEDS [PORT] oracle.py sql SEED print the SQL of one case oracle.py summary OUT outcome classes of the target statements oracle.py compare OUT_A OUT_B per-case comparison; exit 1 if any case differs What a case mixes: NOT NULL (plain, named, NO INHERIT, NOT VALID), CHECK (same or different definition, NO INHERIT, NOT VALID, NOT ENFORCED), names that collide across kinds, child columns in another order, dropped columns, extra and missing child constraints and columns; plain inheritance, partitions, two parents, a re-attach after detach, a child that is itself partitioned or has its own inheritance child. """ import os, random, re, subprocess, sys COLS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] EXPRS = ['{c} > 0', '{c} < 100', '{c} <> 5', '{c} IS NOT NULL', '{c} + 1 > 0'] MODES = ['inherit', 'attach', 'multi', 'subpart', 'reattach', 'reinherit', 'grand'] DUMP = """SELECT c.relname, con.conname, con.contype, con.coninhcount, con.conislocal, con.connoinherit, con.convalidated, con.conenforced, con.conkey, pg_get_constraintdef(con.oid) FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid WHERE c.relnamespace = 'o'::regnamespace ORDER BY 1, 2; SELECT c.relname, a.attname, a.attnum, a.attnotnull, a.attinhcount, a.attislocal FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid WHERE c.relnamespace = 'o'::regnamespace AND c.relkind IN ('r', 'p') AND a.attnum > 0 ORDER BY 1, 3; SELECT inhrelid::regclass, inhparent::regclass, inhseqno FROM pg_inherits WHERE inhparent::regclass::text ~ '^(o\\.)?(p|p2|s)$' ORDER BY 1, 2;""" def nn_clause(r, table, col, allow_noinherit, names): """(inline clause, later statements) for a not-null constraint on col.""" k = r.random() if k < 0.55: return ' NOT NULL', [] if k < 0.80: nm = r.choice(names) if r.random() < 0.12 else r.choice([f'nn_{col}', f'{table}_{col}_x']) return f' CONSTRAINT {nm} NOT NULL', [] if k < 0.90 and allow_noinherit: return ' NOT NULL NO INHERIT', [] if k < 0.97: nm = r.choice(names) if r.random() < 0.1 else f'nv_{col}' return '', [f'ALTER TABLE {table} ADD CONSTRAINT {nm} NOT NULL {col} NOT VALID'] return ' NOT NULL', [] def flags(r, allow_noinherit, p_ni=0.08, p_nv=0.08, p_ne=0.08): k = r.random() if k < p_ni and allow_noinherit: return ' NO INHERIT' if k < p_ni + p_nv: return ' NOT VALID' if k < p_ni + p_nv + p_ne: return ' NOT ENFORCED' return '' def table(r, name, cols, nn, checks, partby=None, order=None, extra=0, predrop=False): """CREATE TABLE and follow-up statements. nn: {col: (clause, later)}; checks: [(name, expr, flags)].""" order = order or cols defs, later = [], [] if predrop: defs.append('zz int') for c in order: cl, lt = nn.get(c, ('', [])) defs.append(f'{c} int{cl}') later += lt for i in range(extra): defs.append(f'x{i} int' + (' NOT NULL' if r.random() < 0.5 else '')) inline = [f'CONSTRAINT {n} CHECK ({e}){f}' for n, e, f in checks if f != ' NOT VALID'] later += [f'ALTER TABLE {name} ADD CONSTRAINT {n} CHECK ({e}) NOT VALID' for n, e, f in checks if f == ' NOT VALID'] st = [f'CREATE TABLE {name} ({", ".join(defs + inline)})' + (f' PARTITION BY RANGE ({partby})' if partby else '')] if predrop: st.append(f'ALTER TABLE {name} DROP COLUMN zz') return st + later def case(seed): r = random.Random(seed) mode = r.choice(MODES) parted = mode in ('attach', 'subpart', 'reattach') cols = r.sample(COLS, r.randint(1, 6)) cknames = [f'k{i}' for i in range(1, 5)] # parent pnn = {c: nn_clause(r, 'p', c, not parted, cknames) for c in cols if r.random() < 0.6} pchecks = [] for n in r.sample(cknames + [f'p_{cols[0]}_not_null', f's_{cols[0]}_not_null'], r.randint(0, 4)): pchecks.append((n, r.choice(EXPRS).format(c=r.choice(cols)), flags(r, not parted))) st = table(r, 'p', cols, pnn, pchecks, partby=cols[0] if parted else None, predrop=r.random() < 0.15) # child: mostly a faithful copy, with a few deviations dev = 0.0 if r.random() < 0.35 else r.choice([0.05, 0.15, 0.4]) ccols = [c for c in cols if r.random() >= dev * 0.3] corder = ccols[:] if r.random() < 0.6: r.shuffle(corder) cnn = {} sub = mode == 'subpart' for c in ccols: if c in pnn: if r.random() >= dev: cnn[c] = (' NOT NULL', []) if r.random() < 0.5 else nn_clause(r, 's', c, not sub, cknames) elif r.random() < 0.3: cnn[c] = nn_clause(r, 's', c, not sub, cknames) cchecks = [] for n, e, f in pchecks: k = r.random() if k < dev * 0.5: continue # missing in the child if k < dev: e = r.choice(EXPRS).format(c=r.choice(ccols or cols)) # maybe another definition cf = f if r.random() < 0.6 else flags(r, not sub, 0.1, 0.1, 0.1) cchecks.append((n, e, cf)) for n in r.sample(['q1', 'q2', 'k4', 'k3'], r.randint(0, 2)): if n not in [x[0] for x in cchecks]: cchecks.append((n, r.choice(EXPRS).format(c=r.choice(ccols or cols)), flags(r, not sub))) st += table(r, 's', ccols, cnn, cchecks, partby=(ccols or cols)[0] if sub else None, order=corder, extra=r.randint(0, 2) if r.random() < 0.4 and not parted else 0, predrop=r.random() < 0.3) if sub: st.append('CREATE TABLE s1 PARTITION OF s FOR VALUES FROM (0) TO (5)') if mode == 'grand': st.append('CREATE TABLE g () INHERITS (s)') attach = 'ALTER TABLE p ATTACH PARTITION s FOR VALUES FROM (0) TO (10)' if mode in ('attach', 'subpart'): tgt = [attach] elif mode == 'reattach': tgt = [attach, 'ALTER TABLE p DETACH PARTITION s', attach] elif mode == 'reinherit': tgt = ['ALTER TABLE s INHERIT p', 'ALTER TABLE s NO INHERIT p', 'ALTER TABLE s INHERIT p'] elif mode == 'multi': c2 = [c for c in cols if r.random() < 0.7] or cols[:1] nn2 = {c: nn_clause(r, 'p2', c, True, cknames) for c in c2 if r.random() < 0.6} ck2 = [(n, e if r.random() < 0.8 else r.choice(EXPRS).format(c=r.choice(c2)), flags(r, True)) for n, e, f in pchecks if r.random() < 0.6] st += table(r, 'p2', c2, nn2, ck2) tgt = ['ALTER TABLE s INHERIT p', 'ALTER TABLE s INHERIT p2'] else: tgt = ['ALTER TABLE s INHERIT p'] return mode, st, tgt def sql(seed): mode, st, tgt = case(seed) out = [f'\\echo === case {seed} {mode}', 'DROP SCHEMA IF EXISTS o CASCADE;', 'CREATE SCHEMA o;'] if os.environ.get('ORACLE_COMPACT'): # with ignore_system_indexes=on the parent's constraints are visited in heap order, and # which of several violations is reported first depends on it; pruning happens at # different moments in the two builds, so start every case from a compact heap out.append('VACUUM FULL pg_constraint;') out += [s + ';' for s in st] for t in tgt: out += [f'\\echo --- target: {t}', t + ';'] out += ['\\echo --- catalog', DUMP] return '\n'.join(out) + '\n' def run(bindir, work, out, seed0, n, port='54761'): work = os.path.abspath(work) data, sock = os.path.join(work, f'oracle-data-{port}'), os.path.join(work, 'sock') subprocess.run(['rm', '-rf', data]); os.makedirs(sock, exist_ok=True) subprocess.run([f'{bindir}/initdb', '-D', data, '-U', 'postgres', '-A', 'trust', '--no-sync'], check=True, stdout=subprocess.DEVNULL) with open(os.path.join(data, 'postgresql.conf'), 'a') as f: f.write("fsync = off\nautovacuum = off\nlisten_addresses = ''\n") subprocess.run([f'{bindir}/pg_ctl', '-D', data, '-o', f'-p {port} -k {sock}', '-l', data + '.log', '-w', 'start'], check=True, stdout=subprocess.DEVNULL) try: script = 'SET search_path = o;\nSET client_min_messages = warning;\n' + \ ''.join(sql(s) for s in range(seed0, seed0 + n)) + '\\echo === end\n' p = subprocess.run([f'{bindir}/psql', '-X', '-q', '-At', '-h', sock, '-p', port, '-U', 'postgres', '-d', 'postgres', '-f', '-'], input=script, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) open(out, 'w').write(p.stdout) done = p.stdout.count('\n=== case ') + p.stdout.startswith('=== case ') ok = p.returncode == 0 and p.stdout.rstrip().endswith('=== end') and done == n # a crash of the backend (assertion) would cut the output short print(f'{out}: cases={done}/{n} psql_exit={p.returncode} complete={ok}') if not ok: sys.exit(1) finally: subprocess.run([f'{bindir}/pg_ctl', '-D', data, '-m', 'fast', '-w', 'stop'], stdout=subprocess.DEVNULL) subprocess.run(['rm', '-rf', data]) def cases(path): cur, d = None, {} for line in open(path): if line.startswith('=== case '): cur = line.split()[2] d[cur] = [] if cur: d[cur].append(line) return d def summary(path): """Outcome of each target statement, names replaced by "x"; and catalog facts reached.""" import collections cls, facts = collections.Counter(), collections.Counter() for seed, lines in cases(path).items(): mode = lines[0].split()[3] i = 0 while i < len(lines): if lines[i].startswith('--- target: '): kind = ' '.join(w for w in lines[i][12:].split() if w.isupper()) nxt = lines[i + 1] if i + 1 < len(lines) else '' res = re.sub(r'"[^"]*"', '"x"', re.sub(r'^psql::\d+: ', '', nxt.strip())) if 'ERROR' in nxt else 'OK' cls[(kind, res)] += 1 facts['mode ' + mode] += 1 if kind else 0 i += 1 for l in lines: p = l.rstrip('\n').split('|') if len(p) == 10 and p[0] == 's' and p[2] in ('c', 'n'): facts[f"child {p[2]} coninhcount={p[3]} conislocal={p[4]}"] += 1 for (kind, res), n in sorted(cls.items(), key=lambda x: (-x[1], x[0])): print(f'{n:7} {kind}: {res}') print() for k, n in sorted(facts.items()): print(f'{n:7} {k}') def compare(a, b): ca, cb = cases(a), cases(b) diff = [s for s in ca if ca[s] != cb.get(s)] + [s for s in cb if s not in ca] print(f'cases: {len(ca)} vs {len(cb)}; different: {len(diff)}') for s in diff[:5]: import difflib print(f'--- case {s}') print(''.join(list(difflib.unified_diff(ca.get(s, []), cb.get(s, []), 'a', 'b', n=1))[:14])) sys.exit(1 if diff or len(ca) != len(cb) else 0) if __name__ == '__main__': a = sys.argv[1:] if a and a[0] == 'run': run(a[1], a[2], a[3], int(a[4]), int(a[5]), *(a[6:7])) elif a and a[0] == 'sql': print(sql(int(a[1])), end='') elif a and a[0] == 'summary': summary(a[1]) elif a and a[0] == 'compare': compare(a[1], a[2]) else: sys.exit(__doc__)