# Max-fee posterior screen Credit: Taylor (gtmcknight), whose pinned replica, Gaussian filter and qt1 reference are the basis of this variant. ## Design Source: [qt1 reference](https://api.imdnotdead.fun/artifacts/8a6e303b662e1a5ea9bb47f31acedd3988ef65b3ddb66d074517aa59ad41ca40), [Taylor's model and update](https://raw.githubusercontent.com/gtmcknight/amm-sim/4812a6382311624e1506aca131ca35c378f930d9/research/solved/README.md), and [QMS1 data](https://api.imdnotdead.fun/artifacts/17d249ab0c33fc44931d9b105cf3f9e3846a560bd518b67310c2a56defacdecc). Only quoting changes at a first own trade with `0.005 < pi < 0.995`. Using the incoming rival estimate, form two independent hypotheses: arb price `exp(lp)`, rival clipped into its band, phase 0, zero uncertainty; retail price `exp(mt)`, rival clipped into its band then updated by this trade, phase 1, uncertainty `sqrt(vt)`, with the component's own synced flag. Each lookup already converts the offsets to qt1 fees. Return the larger bid fee and larger ask fee separately. Pi gates this path but does not weight the maximum. No constants were tuned. The original Gaussian posterior, carried rival estimate, synced flag, count, timestamp and spot update remain intact; chosen fees are stored with qt1's original clamp. A temporary synced change for retail lookup is restored in `finally`. Fee changes naturally alter later inputs and trajectories; preservation means identical state-update rules, not identical state across divergent simulations. Arb/retail oracle arguments are unused. Before editing, `gates.py` reproduced all twelve documented Gate P values to six decimals. Extracted Strategy.sol SHA-256 was `c68887cff61180e12ba2b1ceb333edf76a830f91f63b5d775a8806fb9ec08aca`; decoded blob was 10,167 bytes with SHA-256 `3ac7cb8811ecfb6a17f499aa4e9b70dd55f7fb6432b3aec3b904e11a3dece38e`. Both match [the supplied artifacts](https://api.imdnotdead.fun/artifacts/8a6e303b662e1a5ea9bb47f31acedd3988ef65b3ddb66d074517aa59ad41ca40). Baseline replica checks were 443.1017411146794, 571.454483381923, 525.908441161234 for seeds 10000..10002. A separate replay on seed 70000 verified 8,215 callbacks, including 5,021 new-path calls: filter/rival state equals the original reference updated from the same incoming state; ordinary calls return identical fees; ambiguous calls use phase 0/sd 0 and phase 1 lookups. This replay was not part of the screen and did not tune the policy. ## Screen ```json { "variant": "max-fee", "base": "qt1-ref", "seeds": "60000..60511 inclusive", "n": 512, "mean_diff": -4.631679601960211, "se": 0.055831942178207826, "worst5": [ [ 60250, -8.608026207324656 ], [ 60329, -7.715360427429914 ], [ 60091, -7.6535525625914715 ], [ 60157, -7.6486632108707795 ], [ 60464, -7.561138225548177 ] ], "mean_edge_variant": 524.6442264635302, "mean_edge_base": 529.2759060654904, "new_path_calls_per_run": 5442.44921875, "lookups_per_first_trade": { "ambiguous": { "paired_bid_ask_lookups": 2, "side_lookups": 4 }, "other": { "paired_bid_ask_lookups": 1, "side_lookups": 2 } } } ``` The max-fee variant loses to qt1 on this screen; do not promote it on the strength of this result. Full requested window, not a partial result. Every screen seed was evaluated once per policy with `multiprocessing.Pool(8)` under `python3 -I`, standard library only. Each replica run uses its default 10,000 steps. The first 16 pairs took 24.834 seconds, projecting 794.686 seconds for 512, below 40 minutes. Those same 16 pairs are included, not rerun. Total batch wall time: 220.961 seconds. Standard error is sample standard deviation of paired differences divided by sqrt(n); worst5 sorts ascending by difference, then seed. Local measurements above are generated by the harness below, not claims from the linked sources. Replica edge units are not board points. No holdout or engine seeds were consumed. ## Code Complete `scratch/mix.py` (actual local path `test/scratch/mix-max-fee/mix.py`), requires the unchanged decoded blob: ```python """Max-fee variant of qt1 reference: Taylor's (gtmcknight) Gaussian filter (as port-3's standalone.Coarse / trim-2) + real.py's qm fee rule over the DECODED qm-spline tables (QMS1 blob, sha256 3ac7cb88...). Standard library only. usage: from qmref import QMRef; QMRef('blob.bin') is a replica2 policy (wants_j). Init fees = real.py's init: the full plain pol_mid table at (0,0,0) = 0.002823606104386589 each. """ import math, struct SIG2 = .000945 ** 2 LD_M, LD_S = math.log(11.12e-4), 1.176 INIT = 0.002823606104386589 MAXF = 0.1 def phi(x): return math.exp(-.5 * x * x) / 2.5066282746310002 def Phi(x): return .5 * (1 + math.erf(x / 1.4142135623730951)) def trunc(m, v, lo, hi): if v <= 0: return float(lo <= m <= hi), m, 0. sd = math.sqrt(v); a = (lo - m) / sd; b = (hi - m) / sd; z = Phi(b) - Phi(a) if z < 1e-12: return z, lo if m < lo else hi, v * .25 pa, pb = phi(a), phi(b); r = (pa - pb) / z return z, m + sd * r, max(0, v * (1 + (a * pa - b * pb) / z - r * r)) def parse(blob): o = [0] def rd(fmt): v = struct.unpack_from('<' + fmt, blob, o[0]); o[0] += struct.calcsize('<' + fmt); return v assert blob[:4] == b'QMS1'; o[0] = 4 form, ntab, nw, w0, h, ns = rd('BBHHBB'); assert form == 3 S = list(rd('%dB' % ns)); n2 = rd('B')[0]; W2L = list(rd('%dh' % n2)); fb = rd('B')[0] tabs = [] for _ in range(ntab): nr, nc, nk = rd('BBB') kr = list(rd('%dH' % (nr - 4))); kc = list(rd('%dH' % (nc - 4))); ks = list(rd('%dH' % (nk - 4))) assert nk == 4 and not ks tabs.append([nr, nc, nk, kr, kc]) for t in tabs: t.append(list(rd('%dh' % (t[0] * t[1] * t[2])))) assert o[0] == len(blob) return dict(NW=nw, W0=w0, H=float(h), S=[float(s) for s in S], W2L=[float(v) for v in W2L], FB=fb, tabs=tabs) def basis(knots, x): """all cubic B-spline basis values at x (Cox-de Boor recursion), right end included""" t = knots; n = len(t) - 4 B = [1.0 if t[m] <= x < t[m + 1] else 0.0 for m in range(len(t) - 1)] if x >= t[-1]: last = max(m for m in range(len(t) - 1) if t[m] < t[m + 1]); B = [0.0] * (len(t) - 1); B[last] = 1.0 for d in range(1, 4): Bn = [0.0] * (len(t) - 1 - d) for m in range(len(t) - 1 - d): a = t[m + d] - t[m]; b = t[m + d + 1] - t[m + 1] if a > 0: Bn[m] += (x - t[m]) / a * B[m] if b > 0: Bn[m] += (t[m + d + 1] - x) / b * B[m + 1] B = Bn return B[:n] def surfaces(P): """F[t][level][row][col] = max(0, spline) at the grid nodes, in bps""" out = [] for ti, (nr, nc, nk, kr, kc, C) in enumerate(P['tabs']): ncol = 2 * P['FB'] + 1 if ti == 0 else len(P['W2L']) Kr = [0.0] * 4 + [v / 64 for v in kr] + [P['NW'] - 1.0] * 4 Kc = [0.0] * 4 + [v / 64 for v in kc] + [ncol - 1.0] * 4 Ks = [0.0] * 4 + [len(P['S']) - 1.0] * 4 Br = [basis(Kr, i) for i in range(P['NW'])]; Bc = [basis(Kc, j) for j in range(ncol)] Bs = [basis(Ks, l) for l in range(len(P['S']))] F = [] for l in range(len(P['S'])): D = [[sum(Bs[l][s] * C[(s * nr + r) * nc + c] for s in range(nk)) / 8.0 for c in range(nc)] for r in range(nr)] E = [[sum(D[r][c] * Bc[j][c] for c in range(nc)) for j in range(ncol)] for r in range(nr)] F.append([[max(0.0, sum(Br[i][r] * E[r][j] for r in range(nr))) for j in range(ncol)] for i in range(P['NW'])]) out.append(F) return out class Tables: """A/B exactly as qms_decode.to_qm writes them (rounded to 6 decimals)""" def __init__(self, blob): P = parse(blob); self.P = P NW = P['NW']; w = [(i - P['W0']) * P['H'] for i in range(NW)] self.A = {}; self.B = {} for tag, F in zip(['0c', '1s', '1c', '2s', '2c'], surfaces(P)): A = [[[round(F[l][i][j] + w[i], 6) for j in range(len(F[l][i]))] for i in range(NW)] for l in range(len(F))] self.A[tag] = A self.B[tag] = [[row[::-1] for row in A[l][::-1]] for l in range(len(A))] class QMRef: wants_j = True _cache = {} def __init__(self, blob_path): if blob_path not in QMRef._cache: QMRef._cache[blob_path] = Tables(open(blob_path, 'rb').read()) self.T = QMRef._cache[blob_path]; P = self.T.P self.S = P['S']; self.W0 = P['W0']; self.NW = P['NW']; self.h = P['H']; self.FB = P['FB']; self.W2L = P['W2L'] self.m = math.log(100); self.v = 0.; self.tlast = 0; self.cnt = 0; self.s2h = 100.; self.fb = self.fa = .003 self.sp = 100.; self.synced = False; self.new_path_calls = 0 def _pos2(self, v): W = self.W2L; n = len(W) if v <= W[0]: return 0.0 if v >= W[n - 1]: return float(n - 1) lo, hi = 0, n - 1 while hi - lo > 1: mid = (lo + hi) // 2 if W[mid] <= v: lo = mid else: hi = mid return lo + (v - W[lo]) / (W[hi] - W[lo]) def lookup(self, w, w2, phs, sd): # real.py RealPolicy.lookup S = self.S; k = 0 while k < len(S) - 2 and sd >= S[k + 1]: k += 1 tt = min(1.0, max(0.0, (sd - S[k]) / (S[k + 1] - S[k]))) tag = '0c' if phs == 0 else (str(phs) + ('s' if self.synced else 'c')) A, B = self.T.A[tag], self.T.B[tag] pw = min(self.NW - 1.0, max(0.0, w / self.h + self.W0)) l2 = w2 / self.h if phs == 0: l2 = min(self.FB, max(-self.FB, l2)); p2 = l2 + self.FB; n2 = 2 * self.FB + 1 else: p2 = self._pos2(l2); n2 = len(self.W2L) i = min(int(pw), self.NW - 2); j = min(int(p2), n2 - 2); f = pw - i; g = p2 - j def bl(Tb): return (Tb[i][j] * (1 - f) + Tb[i + 1][j] * f) * (1 - g) + (Tb[i][j + 1] * (1 - f) + Tb[i + 1][j + 1] * f) * g a = bl(A[k]) * (1 - tt) + bl(A[k + 1]) * tt b = bl(B[k]) * (1 - tt) + bl(B[k + 1]) * tt fa = 1.0 - math.exp(-(a - w) * 1e-4) if a > w else 0.0 fb = 1.0 - math.exp(-(b + w) * 1e-4) if b > -w else 0.0 return fb, fa def init(self, *args): self.fb = self.fa = INIT; return INIT, INIT def on_trade(self, is_buy, ax, ay, t, x, y, arb=False, p=100., s2=100., j=0): s = y / x; dt = t - self.tlast; is_arb = False; parts = None if dt >= 1: self.cnt = 0; lo = math.log(self.sp * (1 - self.fb)); hi = math.log(self.sp / (1 - self.fa)); m, v = self.m, self.v for _ in range(min(dt - 1, 12)): v += SIG2; _, m, v = trunc(m, v, lo, hi) v += SIG2 lp = math.log(s * (1 - self.fb)) if is_buy else math.log(s / (1 - self.fa)); sd = math.sqrt(v) la = phi((lp - m) / sd) / sd; Z, mt, vt = trunc(m, v, lo, hi); d = max(abs(math.log(s / self.sp)), 1e-9) lr = Z * .26 * phi((math.log(d) - LD_M) / LD_S) / (d * LD_S) pi = la / (la + lr) if la + lr > 0 else 0.; is_arb = pi > .5 if .005 < pi < .995: # Component-specific rival hypotheses use the incoming rival estimate. arb_price = math.exp(lp) arb_rival = max(arb_price * .997, min(arb_price / .997, self.s2h)) ret_price = math.exp(mt) ret_rival = max(ret_price * .997, min(ret_price / .997, self.s2h)) ret_synced = False cand = s * (1 - self.fb) / .997 if is_buy else s * .997 / (1 - self.fa) if (cand < ret_rival) if is_buy else (cand > ret_rival): ret_rival = cand; ret_synced = True parts = (lp, arb_rival, mt, vt, ret_rival, ret_synced) m2 = pi * lp + (1 - pi) * mt; self.m, self.v = m2, pi * (lp - m2) ** 2 + (1 - pi) * (vt + (mt - m2) ** 2) elif is_arb: self.m, self.v = lp, 0. else: self.m, self.v = mt, vt pe = math.exp(self.m); self.s2h = max(pe * .997, min(pe / .997, self.s2h)); self.synced = False if not is_arb: cand = s * (1 - self.fb) / .997 if is_buy else s * .997 / (1 - self.fa) if (cand < self.s2h) if is_buy else (cand > self.s2h): self.s2h = cand; self.synced = True self.cnt += 1; ph = 1 if self.cnt == 1 else 2 else: ph = 0 self.tlast = t; self.sp = s if parts is None: fb, fa = self.lookup((math.log(s) - self.m) * 1e4, (math.log(self.s2h) - self.m) * 1e4, ph, math.sqrt(self.v) * 1e4) else: lp, arb_rival, mt, vt, ret_rival, ret_synced = parts saved_synced = self.synced try: self.synced = False ab, aa = self.lookup((math.log(s) - lp) * 1e4, (math.log(arb_rival) - lp) * 1e4, 0, 0.) self.synced = ret_synced rb, ra = self.lookup((math.log(s) - mt) * 1e4, (math.log(ret_rival) - mt) * 1e4, 1, math.sqrt(vt) * 1e4) finally: self.synced = saved_synced fb, fa = max(ab, rb), max(aa, ra) self.new_path_calls += 1 self.fb, self.fa = min(MAXF, max(0.0, fb)), min(MAXF, max(0.0, fa)) return fb, fa ``` ## Commands All shell commands were run from the task workspace. All temporary state is under `test/scratch/mix-max-fee`, using the task's permitted scratch exception. No engine setup or installation was needed for this replica-only item. The following ledger lists executed commands; heredoc bodies for the substantive scripts follow it. ```sh mkdir -p test/scratch/mix-max-fee curl -LsSf https://api.imdnotdead.fun/artifacts/8a6e303b662e1a5ea9bb47f31acedd3988ef65b3ddb66d074517aa59ad41ca40 -o test/scratch/mix-max-fee/q.md curl -LsSf https://api.imdnotdead.fun/artifacts/17d249ab0c33fc44931d9b105cf3f9e3846a560bd518b67310c2a56defacdecc -o test/scratch/mix-max-fee/data.md git clone -q https://github.com/gtmcknight/amm-sim test/scratch/mix-max-fee/taylor git -C test/scratch/mix-max-fee/taylor checkout -q 4812a6382311624e1506aca131ca35c378f930d9 rg -n '^##|sha256' test/scratch/mix-max-fee/q.md test/scratch/mix-max-fee/data.md rg --files test/scratch/mix-max-fee/taylor/research/solved sed -n '350,700p' test/scratch/mix-max-fee/q.md cat test/scratch/mix-max-fee/taylor/research/solved/gates.py cat test/scratch/mix-max-fee/taylor/research/solved/README.md sed -n '1,100p' test/scratch/mix-max-fee/taylor/research/solved/replica2.py python3 -I test/scratch/mix-max-fee/taylor/research/solved/gates.py # Wrote build.py using a quoted heredoc (complete body below). python3 -I test/scratch/mix-max-fee/build.py # Wrote screen.py using a quoted heredoc (complete body below). python3 -I test/scratch/mix-max-fee/screen.py check python3 -I test/scratch/mix-max-fee/screen.py 60000 60016 # Wrote check.py using a quoted heredoc (complete body below). python3 -I test/scratch/mix-max-fee/check.py python3 -I test/scratch/mix-max-fee/screen.py 60016 60144 sed -n '31,44p' test/scratch/mix-max-fee/q.md sed -n '117,129p' test/scratch/mix-max-fee/data.md # Wrote report.py using a quoted heredoc: report assembly, schema/size checks, source-quote substring checks. python3 -I test/scratch/mix-max-fee/screen.py 60144 60272 # Wrote commands.txt using a quoted heredoc and corrected its artifact URL before report assembly. # Inspected completed-pair count/mean using python3 -I with json,pathlib,statistics (144 pairs; provisional only). python3 -I test/scratch/mix-max-fee/screen.py 60272 60400 # Edited report.py using python3 -I to state the negative-screen recommendation explicitly. python3 -I test/scratch/mix-max-fee/screen.py 60400 60512 # Wrote validate.py via quoted heredoc, validating output schema, embedded code, size and paths. # Appended this ledger with a quoted heredoc. Shell output polls used write_stdin; no new commands. # Non-shell tool: searched available web tools; web.run opened Q, Data and pinned README (artifact web opens failed; curl succeeded). python3 -I test/scratch/mix-max-fee/report.py python3 -I test/scratch/mix-max-fee/validate.py # Queried named-output git status and ignore status: artifacts/ is excluded; outputs stay untracked for daemon upload. git status --short -- artifacts/goal/batches/e1-lead-mix/items/mix-max-fee git check-ignore -v artifacts/goal/batches/e1-lead-mix/items/mix-max-fee/result.md # Final bookkeeping: corrected the ignore-status wording in this ledger with python3 -I, # then reassembled and revalidated the report (no experiment changes). python3 -I test/scratch/mix-max-fee/report.py python3 -I test/scratch/mix-max-fee/validate.py ``` Extraction/variant construction (`build.py`): ```python import pathlib,re,base64,hashlib p=pathlib.Path(__file__).resolve().parent q=(p/'q.md').read_text(); d=(p/'data.md').read_text() ref=re.search(r'```python\n(.*?)```',q[q.index('## Python reference') :],re.S).group(1) sol=re.search(r'```solidity\n(.*?)```',q[q.index('## Strategy.sol'):],re.S).group(1) assert hashlib.sha256(sol.encode()).hexdigest()=='c68887cff61180e12ba2b1ceb333edf76a830f91f63b5d775a8806fb9ec08aca' blob=base64.b64decode(re.search(r'```[^\n]*\n(.*?)```',d[d.index('## Data:'):],re.S).group(1)) assert len(blob)==10167 and hashlib.sha256(blob).hexdigest()=='3ac7cb8811ecfb6a17f499aa4e9b70dd55f7fb6432b3aec3b904e11a3dece38e' (p/'blob.bin').write_bytes(blob); (p/'qmref.py').write_text(ref) mix=ref.replace('"""qt1 reference:', '"""Max-fee variant of qt1 reference:') mix=mix.replace('self.sp = 100.; self.synced = False','self.sp = 100.; self.synced = False; self.new_path_calls = 0') mix=mix.replace('s = y / x; dt = t - self.tlast; is_arb = False','s = y / x; dt = t - self.tlast; is_arb = False; parts = None') needle=' if .005 < pi < .995:\n' insert=''' if .005 < pi < .995: # Component-specific rival hypotheses use the incoming rival estimate. arb_price = math.exp(lp) arb_rival = max(arb_price * .997, min(arb_price / .997, self.s2h)) ret_price = math.exp(mt) ret_rival = max(ret_price * .997, min(ret_price / .997, self.s2h)) ret_synced = False cand = s * (1 - self.fb) / .997 if is_buy else s * .997 / (1 - self.fa) if (cand < ret_rival) if is_buy else (cand > ret_rival): ret_rival = cand; ret_synced = True parts = (lp, arb_rival, mt, vt, ret_rival, ret_synced) ''' mix=mix.replace(needle,insert) needle=' fb, fa = self.lookup((math.log(s) - self.m) * 1e4, (math.log(self.s2h) - self.m) * 1e4, ph, math.sqrt(self.v) * 1e4)' insert=''' if parts is None: fb, fa = self.lookup((math.log(s) - self.m) * 1e4, (math.log(self.s2h) - self.m) * 1e4, ph, math.sqrt(self.v) * 1e4) else: lp, arb_rival, mt, vt, ret_rival, ret_synced = parts saved_synced = self.synced try: self.synced = False ab, aa = self.lookup((math.log(s) - lp) * 1e4, (math.log(arb_rival) - lp) * 1e4, 0, 0.) self.synced = ret_synced rb, ra = self.lookup((math.log(s) - mt) * 1e4, (math.log(ret_rival) - mt) * 1e4, 1, math.sqrt(vt) * 1e4) finally: self.synced = saved_synced fb, fa = max(ab, rb), max(aa, ra) self.new_path_calls += 1''' assert needle in mix;mix=mix.replace(needle,insert) (p/'mix.py').write_text(mix) print('hashes verified; files extracted; variant written') ``` Timing and paired screen (`screen.py`): ```python # Taylor (gtmcknight) replica and qt1 reference; max-fee paired screening harness. import sys,pathlib,time,json,multiprocessing,statistics,math P=pathlib.Path(__file__).resolve().parent sys.path.insert(0,str(P));sys.path.insert(0,str(P/'taylor/research/solved')) import replica2 as R import qmref,mix B=str(P/'blob.bin') def pair(seed): base=R.run(seed,qmref.QMRef(B))['edge'] m=mix.QMRef(B); edge=R.run(seed,m)['edge'] return [seed,edge-base,edge,base,m.new_path_calls] def main(): if sys.argv[1]=='check': out=[R.run(s,qmref.QMRef(B))['edge'] for s in range(10000,10003)] assert all(abs(a-b)<.00000051 for a,b in zip(out,[443.101741,571.454483,525.908441])) print(json.dumps(out));return start,end=map(int,sys.argv[1:3]);t=time.monotonic() with multiprocessing.Pool(8) as pool: rows=pool.map(pair,range(start,end)) elapsed=time.monotonic()-t (P/f'rows-{start}-{end}.json').write_text(json.dumps({'seconds':elapsed,'rows':rows})) print(json.dumps({'start':start,'end':end,'n':len(rows),'seconds':elapsed,'projected_512_seconds':elapsed*512/len(rows)}),flush=True) if __name__=='__main__':main() ``` State/lookup check (`check.py`): ```python # Taylor (gtmcknight) qt1 reference: verify that max-fee changes only quoting. import sys,pathlib,json P=pathlib.Path(__file__).resolve().parent sys.path.insert(0,str(P));sys.path.insert(0,str(P/'taylor/research/solved')) import qmref,mix,replica2 class Checked(mix.QMRef): callbacks=0 def lookup(self,*a): self.calls.append(a) return super().lookup(*a) def on_trade(self,*a,**kw): baseline=qmref.QMRef(str(P/'blob.bin')) baseline.__dict__.update(self.__dict__) before=self.new_path_calls self.calls=[] out=super().on_trade(*a,**kw) original=baseline.on_trade(*a,**kw) for k in ('m','v','s2h','synced','cnt','tlast','sp'): assert getattr(self,k)==getattr(baseline,k), k changed=self.new_path_calls-before assert len(self.calls)==(2 if changed else 1) if changed: assert self.calls[0][2:]==(0,0.) assert self.calls[1][2]==1 else:assert out==original self.callbacks+=1 return out p=Checked(str(P/'blob.bin')) replica2.run(70000,p) print(json.dumps({'callbacks':p.callbacks,'new_path_calls':p.new_path_calls,'state_and_lookup_checks':'passed'})) ``` ## Problems No endpoint, dependency or numerical failures in the experiment. The web reader could not open the two IMD artifact URLs; curl retrieved both successfully, and their relevant hashes were verified. Sources quotes below are copied from the retrieved files. This is a Python screen only: no Solidity port, bytecode-size measurement, gas measurement, engine evaluation, Gate F, or 10000..12047 holdout is claimed. Those broader goal gates remain for downstream work. The local checks carry no independent verification authority.