"""Run numerical and transactional fixtures used in original teaching.""" import math,sqlite3,json,pathlib z=1.96 def wilson(x,n): p=x/n;d=1+z*z/n;c=(p+z*z/(2*n))/d;w=z*math.sqrt(p*(1-p)/n+z*z/(4*n*n))/d return [c-w,c+w] w=wilson(1,20);assert abs(w[0]-.0088812194)<1e-9 and abs(w[1]-.2361358935)<1e-9 assert abs(wilson(0,20)[1]-.1611301255)<1e-9 assert all(abs(a-(1-b))<1e-12 for a,b in zip(wilson(19,20),reversed(w))) x=[1,2,3,4,5];y=[2,4,5,4,5];xb=sum(x)/5;yb=sum(y)/5 sxx=sum((a-xb)**2 for a in x);b=sum((a-xb)*(v-yb) for a,v in zip(x,y))/sxx;a=yb-b*xb sse=sum((v-a-b*u)**2 for u,v in zip(x,y));assert abs(sse-2.4)<1e-12 t=3.182446305284;intervals={} for u in [3,6]: h=.2+(u-xb)**2/sxx;fit=a+b*u intervals[u]={'mean':[fit-t*math.sqrt(.8*h),fit+t*math.sqrt(.8*h)],'individual':[fit-t*math.sqrt(.8*(1+h)),fit+t*math.sqrt(.8*(1+h))]} db=sqlite3.connect(':memory:');db.execute('CREATE TABLE old(invoice_id TEXT, amount_cents INTEGER)');db.executemany('INSERT INTO old VALUES(?,?)',[('A',100),('B',250)]);db.commit() db.execute('BEGIN IMMEDIATE');db.execute('CREATE TABLE candidate(invoice_id TEXT PRIMARY KEY NOT NULL,amount_cents INTEGER NOT NULL CHECK(amount_cents>=0))');db.execute('INSERT INTO candidate SELECT * FROM old') try:db.execute("INSERT INTO candidate VALUES('C',-5)");raise AssertionError('Constraint failed to reject negative value') except sqlite3.IntegrityError:db.rollback() assert db.execute('SELECT * FROM old ORDER BY invoice_id').fetchall()==[('A',100),('B',250)] assert not db.execute("SELECT name FROM sqlite_master WHERE name='candidate'").fetchall() db.execute('BEGIN IMMEDIATE');db.execute('CREATE TABLE candidate(invoice_id TEXT PRIMARY KEY NOT NULL,amount_cents INTEGER NOT NULL CHECK(amount_cents>=0))');db.execute('INSERT INTO candidate SELECT * FROM old') assert db.execute('SELECT * FROM candidate EXCEPT SELECT * FROM old').fetchall()==[] assert db.execute('SELECT * FROM old EXCEPT SELECT * FROM candidate').fetchall()==[] db.execute('DROP TABLE old');db.execute('ALTER TABLE candidate RENAME TO old');db.commit() db.execute('CREATE TABLE events(event_key TEXT PRIMARY KEY NOT NULL,amount INTEGER NOT NULL)') def accept(key,amount): with db: old=db.execute('SELECT amount FROM events WHERE event_key=?',(key,)).fetchone() if old:return 'replay' if old[0]==amount else 'conflict' db.execute('INSERT INTO events VALUES(?,?)',(key,amount));return 'accepted' assert [accept('batch-7',100),accept('batch-7',100),accept('batch-7',200)]==['accepted','replay','conflict'] assert db.execute('SELECT COUNT(*) FROM events').fetchone()[0]==1 result={'wilson_1_of_20':w,'regression':{'intercept':a,'slope':b,'SSE':sse,'intervals':intervals},'migration':'constraint failure rolled back; successful exact-pair copy committed','import':'first acceptance, identical replay, conflicting reuse checked','boundary':'Single-connection synthetic fixtures; no concurrency or production migration claim.'} print(json.dumps(result,indent=2))