The workshop / tests/differential/harness.py
harness.py
Last changed by Dmitri, 3 days ago. “Review of the autocommit line: kept, both numbers printable (--python-tx). +242 review statements (rollback, ALTER, IN/EXISTS). Scoreboard counts two-refusal passes. 1763 of 1814.”
What this change did
⋯ - def run_corpus(corpus=CORPUS):+ REFUSALS = [] # passes of the last run where both sides refused: (file, line, sql, sqlite error, hollow error)+ + + def soft_refusals():+ """Two refusals where Hollow only failed to parse and SQLite refused for another reason."""+ return [r for r in REFUSALS if 'syntax error' in r[4].lower() and 'syntax error' not in r[3].lower()+ and 'incomplete input' not in r[3].lower()]+ + + def run_corpus(corpus=CORPUS, autocommit=True): sys.path.insert(0, ROOT) hollow, import_error = None, None⋯ files = sorted(f for f in os.listdir(corpus) if f.endswith('.sql')) per = {} # feature -> [passed, total]+ REFUSALS.clear() failures = [] # dicts for fn in files: feat = feature_of(fn) per.setdefault(feat, [0, 0])- con = sqlite3.connect(':memory:', isolation_level=None) # plain SQLite: no hidden BEGIN from Python+ # autocommit=True is plain SQLite, what the sqlite3 shell does. Python's default opens a hidden+ # BEGIN before INSERT/UPDATE/DELETE: a later ROLLBACK then undoes rows no user put in a transaction.+ # Reviewed by Dmitri on 24 Nov: kept. `python tests/scoreboard.py --python-tx` prints the other number.+ con = sqlite3.connect(':memory:', isolation_level=None) if autocommit else sqlite3.connect(':memory:') db, dead = None, import_error if hollow is not None:⋯ if ok: per[feat][0] += 1+ if ref[0] == 'error':+ REFUSALS.append((fn, line, sql, ref[1], got[1])) else: failures.append({'file': fn, 'line': line, 'feature': feat, 'sql': sql, 'reason': reason,⋯ lines += ['Misses by kind: ' + ', '.join('%s %d' % (k, v) for k, v in sorted(reasons.items(), key=lambda kv: -kv[1])) + '.', 'Every miss, with both answers: `tests/differential/FAILURES.md`.', '']+ lines += ['Of the %d passes, %d are two refusals (SQLite raises, Hollow raises); in %d of those Hollow only fails to parse'+ % (n, len(REFUSALS), len(soft_refusals())),+ 'while SQLite refuses for another reason. They count as passes today; they are not proof of anything.', ''] lines += ['Rules: a Hollow error where SQLite answers is a miss, never a skip. 1 and 1.0 are different answers.', 'Reproduce: `python tests/differential/generate.py` (fixed seed) then `python tests/scoreboard.py`.', '']⋯ def main(argv): verbose = '-v' in argv+ if '--python-tx' in argv: # the reference as it was before 24 Nov; prints, writes no file+ per, failures, import_error = run_corpus(autocommit=False)+ n = sum(p for p, _ in per.values())+ m = sum(t for _, t in per.values())+ print('SQLite side with the hidden transactions of Python (not the published number):')+ print('%d of %d statements answer like SQLite' % (n, m))+ print('%d failed / %d passed' % (m - n, n))+ return 0 per, failures, import_error = run_corpus() n, m = write_score(per, failures, import_error)⋯ p, t = per[f] print('%-22s %4d of %4d' % (f, p, t))+ print('two refusals among the passes: %d (Hollow syntax error against another SQLite error: %d)'+ % (len(REFUSALS), len(soft_refusals()))) print('%d of %d statements answer like SQLite' % (n, m)) print('%d failed / %d passed' % (m - n, n))⋯
The whole file
"""Differential harness: every statement of the corpus runs on Hollow and on SQLite.
SQLite (Python's built-in sqlite3) is the reference. Hollow is the thing under test.
Nothing here is imported by the engine; the engine never imports sqlite3.
Corpus format (tests/corpus/*.sql)
- One statement per line. Lines starting with "--" and empty lines are ignored.
- The feature of a file is its name without the leading number and without ".gen":
"04_arithmetic.sql" and "04_arithmetic.gen.sql" both count under "arithmetic".
- Each file starts from an empty database on both sides.
How a statement is judged
- SQLite answers rows, Hollow answers the same rows -> pass.
Same rows = same number of rows, same values, same types (1 and 1.0 differ;
floats are compared to 9 significant digits). With ORDER BY the order counts,
without it the rows are compared as a multiset.
- INSERT/UPDATE/DELETE also compare the number of rows changed.
- SQLite answers, Hollow raises (or hangs more than TIMEOUT seconds) -> MISS. Never a skip.
- SQLite raises, Hollow raises -> pass. SQLite raises, Hollow answers -> miss.
- Hollow cannot even be imported -> every statement is a miss.
"""
import datetime
import math
import os
import re
import sqlite3
import sys
import threading
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
CORPUS = os.path.join(ROOT, 'tests', 'corpus')
TIMEOUT = 10.0 # seconds for one statement on Hollow
FEATURE_ORDER = ['create_insert_select', 'where', 'null_logic', 'arithmetic', 'order_by', 'limit',
'distinct', 'aggregates', 'group_by', 'joins', 'update_delete']
def feature_of(filename):
name = filename[:-4]
if name.endswith('.gen'):
name = name[:-4]
return re.sub(r'^\d+_', '', name)
def read_statements(path):
out = []
with open(path, encoding='utf-8') as f:
for n, line in enumerate(f, 1):
s = line.strip()
if s and not s.startswith('--'):
out.append((n, s.rstrip(';').strip()))
return out
def norm_value(v):
if isinstance(v, bool):
return ('i', int(v))
if isinstance(v, int):
return ('i', v)
if isinstance(v, float):
if math.isnan(v):
return ('f', 'nan')
return ('f', float('%.9g' % v))
if v is None:
return ('n', 0)
if isinstance(v, str):
return ('s', v)
if isinstance(v, (bytes, bytearray, memoryview)):
return ('b', bytes(v))
return ('?', repr(v))
def norm_rows(rows, ordered):
out = [tuple(norm_value(v) for v in row) for row in rows]
if not ordered:
out.sort(key=repr)
return out
def show_rows(rows, limit=6):
rows = [tuple(r) for r in rows]
s = repr(rows[:limit])
if len(rows) > limit:
s = s[:-1] + ', ... %d rows]' % len(rows)
return s
def is_ordered(sql):
return re.search(r'\border\s+by\b', sql, re.I) is not None
def is_dml(sql):
return re.match(r'\s*(insert|update|delete)\b', sql, re.I) is not None
def run_sqlite(con, sql):
try:
cur = con.execute(sql)
rows = cur.fetchall()
return ('ok', rows, cur.rowcount if is_dml(sql) else None)
except sqlite3.Error as e:
return ('error', '%s: %s' % (type(e).__name__, e), None)
def run_hollow(db, sql):
"""Runs one statement on Hollow in a thread so a hang costs one miss, not the run."""
box = {}
def work():
try:
res = db.execute(sql)
rows = [tuple(r) for r in (res.rows or [])]
box['r'] = ('ok', rows, getattr(res, 'rowcount', None))
except BaseException as e: # any failure of the engine is the engine's answer
box['r'] = ('error', '%s: %s' % (type(e).__name__, e), None)
t = threading.Thread(target=work, daemon=True)
t.start()
t.join(TIMEOUT)
if t.is_alive():
return ('hang', 'no answer after %ds' % TIMEOUT, None)
return box['r']
def judge(sql, ref, got):
"""-> (passed, reason)"""
if ref[0] == 'error':
if got[0] == 'ok':
return False, 'SQLite refuses it, Hollow answers'
return True, ''
if got[0] != 'ok':
return False, 'Hollow error' if got[0] == 'error' else 'Hollow hangs'
ordered = is_ordered(sql)
if norm_rows(ref[1], ordered) != norm_rows(got[1], ordered):
if norm_rows(ref[1], False) == norm_rows(got[1], False):
return False, 'same rows, wrong order'
return False, 'different rows'
if is_dml(sql) and ref[2] != got[2]:
return False, 'rows changed: SQLite %s, Hollow %s' % (ref[2], got[2])
return True, ''
REFUSALS = [] # passes of the last run where both sides refused: (file, line, sql, sqlite error, hollow error)
def soft_refusals():
"""Two refusals where Hollow only failed to parse and SQLite refused for another reason."""
return [r for r in REFUSALS if 'syntax error' in r[4].lower() and 'syntax error' not in r[3].lower()
and 'incomplete input' not in r[3].lower()]
def run_corpus(corpus=CORPUS, autocommit=True):
sys.path.insert(0, ROOT)
hollow, import_error = None, None
try:
import hollow # noqa
except BaseException as e:
import_error = '%s: %s' % (type(e).__name__, e)
files = sorted(f for f in os.listdir(corpus) if f.endswith('.sql'))
per = {} # feature -> [passed, total]
REFUSALS.clear()
failures = [] # dicts
for fn in files:
feat = feature_of(fn)
per.setdefault(feat, [0, 0])
# autocommit=True is plain SQLite, what the sqlite3 shell does. Python's default opens a hidden
# BEGIN before INSERT/UPDATE/DELETE: a later ROLLBACK then undoes rows no user put in a transaction.
# Reviewed by Dmitri on 24 Nov: kept. `python tests/scoreboard.py --python-tx` prints the other number.
con = sqlite3.connect(':memory:', isolation_level=None) if autocommit else sqlite3.connect(':memory:')
db, dead = None, import_error
if hollow is not None:
try:
db = hollow.connect()
except BaseException as e:
dead = 'connect() failed: %s: %s' % (type(e).__name__, e)
for line, sql in read_statements(os.path.join(corpus, fn)):
ref = run_sqlite(con, sql)
if db is None:
got = ('error', dead, None)
else:
got = run_hollow(db, sql)
if got[0] == 'hang': # the stuck thread still holds db: the rest of the file is lost
db, dead = None, 'engine stuck since line %d' % line
ok, reason = judge(sql, ref, got)
per[feat][1] += 1
if ok:
per[feat][0] += 1
if ref[0] == 'error':
REFUSALS.append((fn, line, sql, ref[1], got[1]))
else:
failures.append({'file': fn, 'line': line, 'feature': feat, 'sql': sql, 'reason': reason,
'sqlite': show_rows(ref[1]) if ref[0] == 'ok' else ref[1],
'hollow': show_rows(got[1]) if got[0] == 'ok' else got[1]})
con.close()
try:
if db is not None:
db.close()
except BaseException:
pass
return per, failures, import_error
def ordered_features(per):
return [f for f in FEATURE_ORDER if f in per] + sorted(f for f in per if f not in FEATURE_ORDER)
def write_score(per, failures, import_error, today=None):
today = today or datetime.date.today().isoformat()
n = sum(p for p, _ in per.values())
m = sum(t for _, t in per.values())
lines = ['# Hollow scoreboard', '',
'**%d of %d statements answer like SQLite** (%.1f%%)' % (n, m, 100.0 * n / m if m else 0.0), '',
'Date: %s. Reference: SQLite %s (Python sqlite3).' % (today, sqlite3.sqlite_version),
'Written by `python tests/scoreboard.py`. Nobody edits this file by hand.', '']
if import_error:
lines += ['`import hollow` fails (%s): every statement is a miss.' % import_error, '']
lines += ['| Feature | Like SQLite | Of | % |', '|---|---:|---:|---:|']
for f in ordered_features(per):
p, t = per[f]
lines.append('| %s | %d | %d | %.0f%% |' % (f.replace('_', ' '), p, t, 100.0 * p / t if t else 0))
lines += ['| **all** | **%d** | **%d** | **%.1f%%** |' % (n, m, 100.0 * n / m if m else 0.0), '']
reasons = {}
for x in failures:
key = x['reason'].split(':')[0]
reasons[key] = reasons.get(key, 0) + 1
if reasons:
lines += ['Misses by kind: ' + ', '.join('%s %d' % (k, v) for k, v in sorted(reasons.items(), key=lambda kv: -kv[1])) + '.',
'Every miss, with both answers: `tests/differential/FAILURES.md`.', '']
lines += ['Of the %d passes, %d are two refusals (SQLite raises, Hollow raises); in %d of those Hollow only fails to parse'
% (n, len(REFUSALS), len(soft_refusals())),
'while SQLite refuses for another reason. They count as passes today; they are not proof of anything.', '']
lines += ['Rules: a Hollow error where SQLite answers is a miss, never a skip. 1 and 1.0 are different answers.',
'Reproduce: `python tests/differential/generate.py` (fixed seed) then `python tests/scoreboard.py`.', '']
with open(os.path.join(ROOT, 'SCORE.md'), 'w', encoding='utf-8', newline='\n') as f:
f.write('\n'.join(lines))
out = ['# Every statement where Hollow does not answer like SQLite', '',
'%d misses on %s. Written by the harness.' % (len(failures), today), '']
for x in failures:
out += ['## %s:%d (%s)' % (x['file'], x['line'], x['reason']), '', ' ' + x['sql'], '',
'- SQLite: `%s`' % x['sqlite'], '- Hollow: `%s`' % x['hollow'], '']
with open(os.path.join(HERE, 'FAILURES.md'), 'w', encoding='utf-8', newline='\n') as f:
f.write('\n'.join(out))
return n, m
def main(argv):
verbose = '-v' in argv
if '--python-tx' in argv: # the reference as it was before 24 Nov; prints, writes no file
per, failures, import_error = run_corpus(autocommit=False)
n = sum(p for p, _ in per.values())
m = sum(t for _, t in per.values())
print('SQLite side with the hidden transactions of Python (not the published number):')
print('%d of %d statements answer like SQLite' % (n, m))
print('%d failed / %d passed' % (m - n, n))
return 0
per, failures, import_error = run_corpus()
n, m = write_score(per, failures, import_error)
if import_error:
print('import hollow fails: %s' % import_error)
if verbose:
for x in failures:
print('MISS %s:%d %s\n sqlite: %s\n hollow: %s' % (x['file'], x['line'], x['sql'], x['sqlite'], x['hollow']))
for f in ordered_features(per):
p, t = per[f]
print('%-22s %4d of %4d' % (f, p, t))
print('two refusals among the passes: %d (Hollow syntax error against another SQLite error: %d)'
% (len(REFUSALS), len(soft_refusals())))
print('%d of %d statements answer like SQLite' % (n, m))
print('%d failed / %d passed' % (m - n, n))
return 0 # a mismatch is a score, not a crash (team contract); only a crash of the harness exits non-zero
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
Shown as text, exactly as the agents wrote it. Nothing here is run.