#!/usr/bin/env python3 """Steady-state verification for the SQLite SimPoint release. For every selected SimPoint window (warmup segment + SimPoint segment, i.e. exactly the instructions that end up in the released archive) this attributes 100% of the executed instructions to functions of the traced binary, then checks two things: 1. the window is dominated by query-execution functions (VDBE engine, B-tree descent, cursor movement, record decoding, pager page access); 2. no instruction in the window belongs to a database-creation, schema- initialization, dataset-loading or SQL-compilation function. Output: per-segment profile files plus excluded_phase_check.tsv and summary.md. """ import bisect import glob import json import os import sys from collections import defaultdict W = "/work/simpoint_flow/sqlite" OUT = f"{W}/validation/steady_state" SEG_SIZE = 60_000_000 # Functions that only ever run during the phases the user asked to exclude. EXCLUDED = { "database creation / schema DDL": [ "sqlite3StartTable", "sqlite3EndTable", "sqlite3CreateIndex", "sqlite3AddColumn", "sqlite3AddPrimaryKey", "sqlite3CreateView", "sqlite3BtreeCreateTable", "sqlite3RootPageMoved", ], "schema initialization / load": [ "sqlite3InitOne", "sqlite3InitCallback", "sqlite3ReadSchema", "schemaIsValid", "sqlite3AnalysisLoad", "loadStat4", "sqlite3Analyze", "analyzeOneTable", "sqlite3LocateTable", ], "dataset population / writes": [ "sqlite3BtreeInsert", "sqlite3BtreeDelete", "balance", "balance_nonroot", "balance_deeper", "allocateBtreePage", "freePage2", "sqlite3PagerWrite", "pager_write", "sqlite3PagerCommitPhaseOne", "sqlite3PagerCommitPhaseTwo", "insertCell", "fillInCell", "clearCell", "dropCell", ], "SQL compilation (statement preparation)": [ "sqlite3RunParser", "sqlite3Parser", "sqlite3GetToken", "keywordCode", "sqlite3Prepare", "sqlite3LockAndPrepare", "yy_reduce", "yy_find_shift_action", "sqlite3WhereBegin", "whereLoopAddBtreeIndex", "sqlite3VdbeAddOp3", "resolveExprStep", "sqlite3VdbeMakeReady", "sqlite3NestedParse", ], } # Query-execution functions we positively expect to dominate. EXPECTED_PREFIXES = ( "sqlite3VdbeExec", "sqlite3_step", "sqlite3Btree", "btree", "moveTo", "getAndInitPage", "getPage", "sqlite3GetVarint", "vdbeRecordCompare", "sqlite3VdbeRecordCompare", "sqlite3VdbeSerialGet", "getCellInfo", "sqlite3VdbeMemFromBtree", "sqlite3_column", "columnMem", "columnMallocFailure", "sqlite3VdbeCursorMoveto", "sqlite3VdbeHalt", "allocateCursor", "unixFetch", "sqlite3PagerGet", "sqlite3PagerAcquire", "sqlite3VdbeIntValue", "releaseMemArray", "sqlite3VdbeMemRelease", "sqlite3BtreeNext", "sqlite3BtreePrevious", "sqlite3VdbeReset", "sqlite3_reset", "sqlite3_bind", "sqlite3VdbeMemSetInt64", # per-query read-transaction begin/end: query execution state management, # not dataset writes (the connection is opened SQLITE_OPEN_READONLY and # runs with PRAGMA query_only=ON, so no write path is reachable). "sqlite3BtreeBeginTrans", "btreeBeginTrans", "sqlite3BtreeCommitPhaseOne", "sqlite3BtreeCommitPhaseTwo", ) def load_symbols(nm_path): syms = [] for line in open(nm_path): parts = line.split(None, 2) if len(parts) < 3: continue addr, typ, name = parts[0], parts[1], parts[2].strip() if typ.lower() not in ("t", "w", "i"): continue try: syms.append((int(addr, 16), name)) except ValueError: pass syms.sort() return [a for a, _ in syms], [n for _, n in syms] def main(): os.makedirs(OUT, exist_ok=True) addrs, names = load_symbols(f"{W}/sqlite_query.nm") pcmap = glob.glob(f"{W}/fingerprint/pcmap.*")[0] bbfp = glob.glob(f"{W}/fingerprint/bbfp.[0-9]*[0-9]")[0] bb = {} with open(pcmap) as f: f.readline() for line in f: fields = line.rstrip("\n").split(",") if len(fields) >= 3: bb[int(fields[1])] = int(fields[0]) selected = [] for line in open(f"{W}/simpoints/selected.txt"): s, c = line.split() selected.append((int(s), int(c))) selected.sort() # segment index (0-based) -> {function: instructions} want = set() for seg, _ in selected: want.add(seg) want.add(seg - 1) per_seg = defaultdict(lambda: defaultdict(int)) idx = -1 for line in open(bbfp): if not line.startswith("T"): continue idx += 1 if idx not in want: continue acc = per_seg[idx] for tok in line[1:].split(): if not tok.startswith(":"): continue bb_id, cnt = tok[1:].split(":") pc = bb.get(int(bb_id), 0) if pc < addrs[0] or pc > addrs[-1] + 0x10000: acc["[libc / ld.so / vdso]"] += int(cnt) else: i = bisect.bisect_right(addrs, pc) - 1 acc[names[i]] += int(cnt) excl_rows = [] summary = [] for seg, cluster in selected: prof = defaultdict(int) for s in (seg - 1, seg): for k, v in per_seg[s].items(): prof[k] += v total = sum(prof.values()) with open(f"{OUT}/function_profile-segment-{seg}.txt", "w") as f: f.write(f"# cluster {cluster}, SimPoint segment {seg}\n") f.write(f"# released archive = warmup segment {seg-1} + segment {seg}\n") f.write(f"# instructions attributed: {total}\n") f.write(f"{'share%':>8} {'instructions':>14} function\n") for name, n in sorted(prof.items(), key=lambda kv: -kv[1]): f.write(f"{100.0*n/total:8.4f} {n:14d} {name}\n") query_share = sum(v for k, v in prof.items() if k.startswith(EXPECTED_PREFIXES)) for category, fns in EXCLUDED.items(): hit = sum(prof.get(fn, 0) for fn in fns) present = [fn for fn in fns if prof.get(fn, 0) > 0] excl_rows.append((seg, cluster, category, hit, ",".join(present) if present else "-")) summary.append((seg, cluster, total, query_share, sorted(prof.items(), key=lambda kv: -kv[1])[:6])) with open(f"{W}/validation/steady_state/excluded_phase_check.tsv", "w") as f: f.write("segment\tcluster\texcluded_phase_category\tinstructions_in_window\tfunctions_seen\n") for row in excl_rows: f.write("\t".join(str(x) for x in row) + "\n") with open(f"{OUT}/summary.md", "w") as f: f.write("# Steady-state verification\n\n") f.write("Attribution covers 100% of the instructions in each released " "archive (warmup segment + SimPoint segment, 120,000,000 " "instructions each).\n\n") f.write("| segment | cluster | instructions | query-execution share | top functions |\n") f.write("|---|---|---|---|---|\n") for seg, cluster, total, qs, top in summary: tops = ", ".join(f"{n} ({100.0*v/total:.1f}%)" for n, v in top) f.write(f"| {seg} | {cluster} | {total} | {100.0*qs/total:.2f}% | {tops} |\n") f.write("\nExcluded-phase functions found in any released window: " f"{sum(r[3] for r in excl_rows)} instructions.\n") print(open(f"{OUT}/summary.md").read()) print(open(f"{W}/validation/steady_state/excluded_phase_check.tsv").read()) if __name__ == "__main__": main()