interplane-forge
INTERPLANE Forge
Brought by drakestapleton
interplane-forge / infra / test / count-snapshot.py
| 1 | #!/usr/bin/env python3 |
| 2 | """External snapshot contract oracle. Product and producer remain seeded Omega.""" |
| 3 | import hashlib, http.client, json, os, signal, subprocess, sys, time |
| 4 | from pathlib import Path |
| 5 | T, ROOT, PORT = Path(sys.argv[1]), Path(sys.argv[2]), int(sys.argv[3]) |
| 6 | H = T/'home' |
| 7 | DATA = H/'forge-data' |
| 8 | PUB = Path(os.environ['FORGED_PUBLIC_DIR']) |
| 9 | SNAP = PUB/'counts.snapshot' |
| 10 | RID = 'z631r2JJiVT8it4tST7RK24hpowi' |
| 11 | PREFIX = '/drakestapleton/cuda-crack' |
| 12 | |
| 13 | def request(path): |
| 14 | c = http.client.HTTPConnection('127.0.0.1', PORT, timeout=10) |
| 15 | try: |
| 16 | c.request('GET', path) |
| 17 | r = c.getresponse(); b = r.read() |
| 18 | assert r.status == 200, (r.status, b[:100]) |
| 19 | return b |
| 20 | finally: |
| 21 | c.close() |
| 22 | |
| 23 | def publish(b): |
| 24 | tmp = PUB/'.mirror.test' |
| 25 | tmp.write_bytes(b); tmp.replace(SNAP) |
| 26 | |
| 27 | def snapshot(stamp=None, rid=RID, vals=None): |
| 28 | stamp = int(time.time()) if stamp is None else stamp |
| 29 | vals = vals or ['7','8','9','10','1794162545','1794162545','1794162545','3','1',str(stamp)] |
| 30 | return f'1 {stamp}\n{rid} {" ".join(vals)}\n'.encode() |
| 31 | |
| 32 | def counts(): return json.loads(request(PREFIX+'.json'))['counts'] |
| 33 | def check_available(): |
| 34 | v = counts() |
| 35 | assert v['git_fetches']['count'] == 7, v |
| 36 | assert v['upload_pack_requests']['count'] is None, v |
| 37 | assert v['downloads']['count'] == 19, v |
| 38 | assert v['seeds']['count'] is None, v |
| 39 | assert b'<b>7</b>' in request(PREFIX) |
| 40 | |
| 41 | def unavailable(): |
| 42 | v = counts() |
| 43 | assert all(x['count'] is None for x in v.values()), v |
| 44 | assert b'not measured' in request(PREFIX) |
| 45 | assert request('/') |
| 46 | |
| 47 | def available(): |
| 48 | # since the Radicle-text removal (c1f107df) upload_pack_requests and seeds are retired: always null, |
| 49 | # and the Seeding line always says "not measured"; the counts a snapshot carries are the other two |
| 50 | v = counts() |
| 51 | assert v['git_fetches']['count'] is not None and v['downloads']['count'] is not None, v |
| 52 | assert v['upload_pack_requests']['count'] is None and v['seeds']['count'] is None, v |
| 53 | assert b'Clones and fetches over HTTPS: <b>not measured' not in request(PREFIX) |
| 54 | |
| 55 | def good(stamp=None, **changes): |
| 56 | stamp = int(time.time()) if stamp is None else stamp |
| 57 | v = ['7','8','9','10','1794162545','1794162545','1794162545','3','1',str(stamp)] |
| 58 | for i, x in changes.items(): v[int(i[1:])] = x |
| 59 | return v |
| 60 | |
| 61 | def row(rid=RID, vals=None): return snapshot(rid=rid, vals=vals).splitlines(keepends=True)[1] |
| 62 | |
| 63 | log = (T/'snapshot-server.log').open('wb') |
| 64 | p = subprocess.Popen(['bash', ROOT/'infra/spark/forged-sandbox.sh', T/'forged'], |
| 65 | stdout=log, stderr=log, start_new_session=True, |
| 66 | env=dict(os.environ, FORGED_LISTEN_PORT=str(PORT))) |
| 67 | try: |
| 68 | for _ in range(100): |
| 69 | assert p.poll() is None, p.returncode |
| 70 | try: |
| 71 | request('/'); break |
| 72 | except OSError: time.sleep(.05) |
| 73 | publish(snapshot()); check_available() |
| 74 | print('PASS positive HTML/JSON snapshot and atomic replacement without restart') |
| 75 | # Each refused case differs by one defect from an accepted twin with positive |
| 76 | # figures. The twin is shown available first, so a parser that accepted the |
| 77 | # defect would show counts and fail the refusal assertion. |
| 78 | now = int(time.time()) |
| 79 | cases = {'missing': (None, snapshot()), |
| 80 | 'stale': (snapshot(now-3601), snapshot(now-3500)), |
| 81 | 'future': (snapshot(now+60), snapshot(now)), |
| 82 | 'truncated': (snapshot()[:-1], snapshot()), |
| 83 | 'header-version': (snapshot().replace(b'1 ', b'2 ', 1), snapshot()), |
| 84 | 'header-field-extra': (snapshot().replace(b'\n', b' 0\n', 1), snapshot()), |
| 85 | 'nonnumeric': (snapshot(vals=good(f0='x')), snapshot()), |
| 86 | 'negative': (snapshot(vals=good(f0='-1')), snapshot()), |
| 87 | 'overflow': (snapshot(vals=good(f0='18446744073709551616')), |
| 88 | snapshot(vals=good(f0='18446744073709551615'))), |
| 89 | 'sum-overflow': (snapshot(vals=good(f2='18446744073709551615', f3='1')), |
| 90 | snapshot(vals=good(f2='18446744073709551614', f3='1'))), |
| 91 | 'status-invalid': (snapshot(vals=good(f8='3')), snapshot()), |
| 92 | 'seed-time-missing': (snapshot(vals=good(f9='0')), snapshot()), |
| 93 | 'since-after-collection': (snapshot(now, vals=good(now, f4=str(now+1))), |
| 94 | snapshot(now, vals=good(now, f4=str(now)))), |
| 95 | 'seed-time-after-collection': (snapshot(now, vals=good(now, f9=str(now+1))), snapshot(now)), |
| 96 | 'duplicate': (snapshot()+row(), snapshot()), |
| 97 | 'rid-nonalnum': (snapshot()+row('z-abc'), snapshot()+row('zabc')), |
| 98 | 'nul': (snapshot()+row('z\0abc'), snapshot()+row('zabc'))} |
| 99 | for fields in (12,50): |
| 100 | cases[f'row-fields-{fields}'] = (snapshot()[:-1]+b' 0'*(fields-11)+b'\n', snapshot()) |
| 101 | for cap in (65,10000): |
| 102 | cases[f'rid-field-{cap}'] = (snapshot()+row('z'+'a'*(cap-1)), snapshot()+row('z'+'a'*63)) |
| 103 | for cap in (20,21,10000): |
| 104 | b = snapshot(vals=good(f0='0'*(cap-1)+'7')) |
| 105 | if cap == 20: |
| 106 | publish(b); check_available(); print('PASS numeric field at 20 digits') |
| 107 | else: cases[f'numeric-field-{cap}'] = (b, snapshot(vals=good(f0='0'*19+'7'))) |
| 108 | # 257 lines (the header and FAMAX = 256 rows, server/util.om) is valid. Unknown public IDs cannot give |
| 109 | # the current project a value. (The table and these caps were 64 rows / 65 lines / 16384 bytes before |
| 110 | # 2026-11-14; server/count-snapshot.om grew them with the allow-list table.) |
| 111 | many = snapshot()+b''.join(row('zfixture'+str(i)) for i in range(255)) |
| 112 | publish(many); check_available(); print('PASS 257-line limit') |
| 113 | cases['lines-258'] = (many+row('zextra0'), many) |
| 114 | # Far beyond the line limit while staying under the file-size cap, so only the line cap can refuse it. |
| 115 | short = b''.join(f'zs{i} 0 0 0 0 0 0 0 0 0 0\n'.encode() for i in range(743)) |
| 116 | assert len((many+short).splitlines()) == 1000 and len(many+short) < 65536, len(many+short) |
| 117 | cases['lines-1000-under-file-cap'] = (many+short, many) |
| 118 | cases['lines-10000'] = (many+b''.join(row('zextra'+str(i)) for i in range(9743)), many) |
| 119 | # RID length at its accepted limit, alongside the actual requested project. |
| 120 | publish(snapshot()+row('z'+'a'*63)); check_available() |
| 121 | print('PASS RID field at 64 bytes') |
| 122 | # Build a valid maximal line and valid whole files at and just over the byte cap. |
| 123 | zero = ['0'*20]*10 |
| 124 | line256 = row('z'+'a'*45, zero) |
| 125 | assert len(line256) == 257 |
| 126 | publish(snapshot()+line256); check_available(); print('PASS valid line at 256 bytes') |
| 127 | cases['line-bytes-257'] = (snapshot()+row('z'+'a'*46, zero), snapshot()+line256) |
| 128 | cases['line-bytes-10000'] = (snapshot()+b'z'*10000+b'\n', snapshot()+line256) |
| 129 | def sized(total): |
| 130 | nums = good() |
| 131 | rows = [row(vals=[v.zfill(20) for v in nums])] |
| 132 | rows += [row(('z'+str(i)).ljust(46,'a'), zero) for i in range(255)] |
| 133 | header = snapshot().splitlines(keepends=True)[0] |
| 134 | excess = len(header+b''.join(rows))-total |
| 135 | for i in range(1,256): |
| 136 | if excess <= 0: break |
| 137 | rid, rest = rows[i].split(b' ',1) |
| 138 | trim = min(excess, len(rid)-10) |
| 139 | rows[i] = rid[:-trim]+b' '+rest if trim else rows[i] |
| 140 | excess -= trim |
| 141 | out = header+b''.join(rows) |
| 142 | assert len(out) == total, (total, len(out)) |
| 143 | return out |
| 144 | exact = sized(65536) |
| 145 | publish(exact); check_available(); print('PASS valid snapshot at 65536 bytes') |
| 146 | # A well-formed 65537-byte file: only the byte cap can refuse it. |
| 147 | cases['file-bytes-65537'] = (sized(65537), exact) |
| 148 | cases['file-bytes-2000000'] = (exact+b'x'*(2000000-len(exact)), exact) |
| 149 | for name, (bad, twin) in cases.items(): |
| 150 | publish(twin); available() |
| 151 | if bad is None: SNAP.unlink() |
| 152 | else: publish(bad) |
| 153 | unavailable() |
| 154 | assert p.poll() is None, (name, p.returncode) |
| 155 | print('PASS accepted twin available; refused and alive', name) |
| 156 | # A symlink whose target is a valid snapshot visible inside the sandbox must still |
| 157 | # be refused: the reader opens with O_NOFOLLOW. The outside target is a second case. |
| 158 | inside = PUB/'.mirror.link-target' |
| 159 | inside.write_bytes(snapshot()) |
| 160 | (T/'valid-link-target.snapshot').write_bytes(snapshot()) |
| 161 | for kind in ('directory','symlink-inside-export','symlink-outside-export','fifo'): |
| 162 | publish(inside.read_bytes()); available() |
| 163 | SNAP.unlink() |
| 164 | if kind == 'directory': SNAP.mkdir() |
| 165 | elif kind == 'symlink-inside-export': SNAP.symlink_to(inside.name) |
| 166 | elif kind == 'symlink-outside-export': SNAP.symlink_to(T/'valid-link-target.snapshot') |
| 167 | else: os.mkfifo(SNAP) |
| 168 | unavailable(); print('PASS refused special file',kind) |
| 169 | if kind == 'directory': SNAP.rmdir() |
| 170 | else: SNAP.unlink() |
| 171 | inside.unlink() |
| 172 | publish(snapshot()); check_available() |
| 173 | print('PASS recovery without restart') |
| 174 | finally: |
| 175 | os.killpg(p.pid, signal.SIGTERM); p.wait(timeout=10); log.close() |
| 176 | |
| 177 | # Challenge the same HTTP test after removing only the freshness guard. |
| 178 | source = (T/'forged.om').read_text() |
| 179 | old = 'if gt sub now stamp 3600\nret false\nend' |
| 180 | assert source.count(old) == 1 |
| 181 | mutant = source.replace(old, 'note freshness guard removed by test') |
| 182 | (T/'stale-mutant.om').write_text(mutant) |
| 183 | with (T/'stale-mutant').open('wb') as out: |
| 184 | subprocess.run([Path(os.environ['HOME'])/'work/flux/omega-mv/seed/out/omc'], input=mutant.encode(), stdout=out, check=True) |
| 185 | (T/'stale-mutant').chmod(0o755) |
| 186 | publish(snapshot(int(time.time())-3601, vals=['7','8','9','10','1794162545','1794162545','1794162545','3','1',str(int(time.time())-3601)])) |
| 187 | log = (T/'stale-mutant.log').open('wb') |
| 188 | p = subprocess.Popen(['bash', ROOT/'infra/spark/forged-sandbox.sh', T/'stale-mutant'], stdout=log, stderr=log, |
| 189 | start_new_session=True, env=dict(os.environ, FORGED_LISTEN_PORT=str(PORT))) |
| 190 | try: |
| 191 | for _ in range(100): |
| 192 | assert p.poll() is None |
| 193 | try: request('/'); break |
| 194 | except OSError: time.sleep(.05) |
| 195 | check_available() |
| 196 | print('PASS stale mutant still serves the exact positive figures before refusal assertion') |
| 197 | try: unavailable() |
| 198 | except AssertionError: print('PASS stale-check mutation is killed by unavailable assertion') |
| 199 | else: raise AssertionError('staleness mutation survived') |
| 200 | finally: |
| 201 | os.killpg(p.pid, signal.SIGTERM); p.wait(timeout=10); log.close() |
| 202 | |
| 203 | # Existing producer on fixture logs: only numbers and RID may reach the export. |
| 204 | fixture = H/'count-inputs/dl.log' |
| 205 | fixture.write_text(f'1794162545.332 203.0.113.222 200 "/rad/{RID}.git/info/refs?service=git-upload-pack" "PRIVATE-UA-CANARY"\n') |
| 206 | result = subprocess.check_output([T/'forged','--counts-snapshot',T/'privacy-counts.log']) |
| 207 | (T/'producer-fixture.snapshot').write_bytes(result) |
| 208 | for word in (b'203.0.113.222', b'PRIVATE-UA-CANARY', b'/rad/', b'HTTP'): |
| 209 | assert word not in result |
| 210 | assert subprocess.run(['grep','-qE','203[.]0[.]113[.]222|PRIVATE-UA-CANARY', fixture]).returncode == 0 |
| 211 | assert subprocess.run(['grep','-E','203[.]0[.]113[.]222|PRIVATE-UA-CANARY', T/'producer-fixture.snapshot']).returncode == 1 |
| 212 | print('PASS producer output privacy grep control; fixture snapshot sha256='+hashlib.sha256(result).hexdigest()) |
| 213 | |
| 214 | # A batch with no counted event still advances the owner-side persistent cursor. |
| 215 | with fixture.open('a') as f: |
| 216 | f.write('1794162547.332 203.0.113.222 200 "/not-a-count" "PRIVATE-UA-CANARY"\n') |
| 217 | subprocess.run([T/'forged','--counts-snapshot',T/'privacy-counts.log'], stdout=subprocess.DEVNULL, check=True) |
| 218 | journal = (T/'privacy-counts.log').read_bytes() |
| 219 | cursors = [line.split() for line in journal.splitlines() if line.startswith(b'k 0 ')] |
| 220 | assert int(cursors[-1][-1]) == fixture.stat().st_size |
| 221 | again = subprocess.check_output([T/'forged','--counts-snapshot',T/'privacy-counts.log']) |
| 222 | assert (T/'privacy-counts.log').read_bytes() == journal |
| 223 | row = next(line.split() for line in again.splitlines() if line.startswith(RID.encode()+b' ')) |
| 224 | assert row[1] == b'1' |
| 225 | print('PASS empty-batch owner cursor persists; unchanged recollection neither recounts nor rewrites journal') |
| 226 | |
| 227 | # A source with no valid measurement epoch must discover its first later event. |
| 228 | saved_log = fixture.read_bytes() |
| 229 | fixture.write_text('0.000 127.0.0.1 200 "/not-a-count" "fixture"\n') |
| 230 | subprocess.run([T/'forged','--counts-snapshot',T/'initial-empty-counts.log'], stdout=subprocess.DEVNULL, check=True) |
| 231 | with fixture.open('a') as f: |
| 232 | f.write(f'1794162545.332 203.0.113.222 200 "/rad/{RID}.git/info/refs?service=git-upload-pack" "PRIVATE-UA-CANARY"\n') |
| 233 | first_event = subprocess.check_output([T/'forged','--counts-snapshot',T/'initial-empty-counts.log']) |
| 234 | row = next(line.split() for line in first_event.splitlines() if line.startswith(RID.encode()+b' ')) |
| 235 | assert row[1] == b'1' and row[5] == b'1794162545', row |
| 236 | fixture.write_bytes(saved_log) |
| 237 | print('PASS initially unmeasured source discovers first later event and its since time') |
| 238 | |
| 239 | # Actual supervisor starts and refreshes the producer. Its worker state is outside data. |
| 240 | import shutil |
| 241 | shutil.rmtree(T/'supervisor-counts-state', ignore_errors=True) |
| 242 | SNAP.unlink(missing_ok=True) |
| 243 | log = (T/'counts-supervisor.log').open('wb') |
| 244 | p = subprocess.Popen(['bash', ROOT/'infra/spark/forged-service.sh', '_loop'], stdout=log, stderr=log, |
| 245 | start_new_session=True, env=dict(os.environ, FORGED_BIN=str(T/'forged'), FORGED_PORT=str(PORT), |
| 246 | FORGED_COUNTS_INTERVAL='1', FORGED_COUNTS_STATE=str(T/'supervisor-counts-state'))) |
| 247 | try: |
| 248 | for _ in range(200): |
| 249 | assert p.poll() is None, p.returncode |
| 250 | try: |
| 251 | if counts()['git_fetches']['count'] == 1: break |
| 252 | except (OSError, AssertionError): pass |
| 253 | time.sleep(.05) |
| 254 | else: raise AssertionError('supervisor did not publish first count') |
| 255 | before = (DATA/'logs/forged.log').read_text().count('start '+str(T/'forged')) |
| 256 | with fixture.open('a') as f: |
| 257 | f.write(f'1794162546.332 203.0.113.221 200 "/rad/{RID}.git/info/refs?service=git-upload-pack" "PRIVATE-UA-CANARY"\n') |
| 258 | for _ in range(200): |
| 259 | assert p.poll() is None |
| 260 | if counts()['git_fetches']['count'] == 2: break |
| 261 | time.sleep(.05) |
| 262 | else: raise AssertionError('supervisor count refresh failed') |
| 263 | after = (DATA/'logs/forged.log').read_text().count('start '+str(T/'forged')) |
| 264 | assert before == after, (before, after) |
| 265 | print('PASS supervisor producer refresh changed 1 to 2 without server restart') |
| 266 | finally: |
| 267 | os.killpg(p.pid, signal.SIGTERM); p.wait(timeout=15); log.close() |