"""Job #4599 (first look, route 141 rev 4): part (b) of the step. For the 4 moved queue rows, apply each return's patch to the fitting base #1822 recovered, then 3-way merge onto the PINNED currently served bytes with `git merge-file`, recording the /history version index merged onto. Rows (return: path, fitting base -> merged onto served): #12 research/kappa-not-L.md base v1 -> served v2 (#1785) #30 paper/kk-lower-bound.md base v1 -> served v5 #132 research/QUESTIONS.md base v7 (latest of v1-v7) -> served v10 #97 research/fixed-endpoint-discrepancy.md base v8 (latest of v1,v3,v6-v8) -> served v9 (#1709) Positive control (pre-registered): #1333's patch applied to fixed-endpoint-discrepancy.md v3 reproduces v4 (f4eb7e26...) byte for byte. git runs with core.autocrlf=false and every apply is restricted to the row's path with --include (a whole multi-file patch in a one-file scratch dir refuses spuriously, the #1453 defect #1822 named). Bytes come from GET /files/ (host root; one appended newline stripped; sha256 verified). Read-only; public endpoints only. Verdict per row: CLEAN (merge-file exit 0), CONFLICT (exit = number of conflict hunks; hunks named by the line of each <<<<<<< marker), or BASE-REFUSES (git apply --check fails on the named base). Also: whether the patch is already contained in the served bytes (git apply --check --reverse).""" import subprocess, json, hashlib, os, sys, tempfile, shutil HERE = os.path.dirname(os.path.abspath(__file__)); API = os.path.join(HERE, '..', 'api.sh') def get_blob(sha): out = subprocess.run(['bash', API, 'GET', f'https://solveathome.org/files/{sha}'], capture_output=True).stdout b = out[:-1] if out.endswith(b'\n') and hashlib.sha256(out[:-1]).hexdigest() == sha else out assert hashlib.sha256(b).hexdigest() == sha, f'sha mismatch for {sha[:12]}' return b def git(args, cwd, inp=None): return subprocess.run(['git', '-c', 'core.autocrlf=false', '-c', 'core.safecrlf=false'] + args, cwd=cwd, capture_output=True, input=inp) info = json.load(open(os.path.join(HERE, 'b', 'info.json'))) ROWS = [(12, 1), (30, 1), (132, 7), (97, 8)] out = [] def apply_patch(path, base_bytes, patch_text): d = tempfile.mkdtemp(); fp = os.path.join(d, path); os.makedirs(os.path.dirname(fp), exist_ok=True) open(fp, 'wb').write(base_bytes) pf = os.path.join(d, 'p.patch'); open(pf, 'w', encoding='utf-8', newline='').write(patch_text) chk = git(['apply', '--check', '-p1', f'--include={path}', 'p.patch'], d) if chk.returncode != 0: msg = chk.stderr.decode(errors='replace').strip().splitlines()[:2]; shutil.rmtree(d); return None, msg git(['apply', '-p1', f'--include={path}', 'p.patch'], d) res = open(fp, 'rb').read(); shutil.rmtree(d); return res, None def contained(path, cur_bytes, patch_text): d = tempfile.mkdtemp(); fp = os.path.join(d, path); os.makedirs(os.path.dirname(fp), exist_ok=True) open(fp, 'wb').write(cur_bytes); open(os.path.join(d, 'p.patch'), 'w', encoding='utf-8', newline='').write(patch_text) r = git(['apply', '--check', '--reverse', '-p1', f'--include={path}', 'p.patch'], d).returncode == 0; shutil.rmtree(d); return r # positive control ctl = info['97']; vmap = {v[0]: v[1] for v in ctl['versions']} p1333 = json.loads(subprocess.run(['bash', API, 'GET', 'return/1333'], capture_output=True).stdout).get('patch') or '' res, err = apply_patch(ctl['path'], get_blob(vmap[3]), p1333) ok_ctl = res is not None and hashlib.sha256(res).hexdigest() == vmap[4] out.append(f"{'PASS' if ok_ctl else 'FAIL'} control_1333_v3_to_v4 :: #1333 patch on v3 -> sha {hashlib.sha256(res).hexdigest()[:12] if res else err} (v4 {vmap[4][:12]})") rows = [] for rid, bv in ROWS: I = info[str(rid)]; vmap = {v[0]: v[1] for v in I['versions']}; cur_v = max(vmap); patch = open(os.path.join(HERE, 'b', f'p{rid}.patch'), encoding='utf-8', newline='').read() base = get_blob(vmap[bv]); cur = get_blob(vmap[cur_v]); assert vmap[cur_v] == I['served'] P, err = apply_patch(I['path'], base, patch) row = {'return': rid, 'path': I['path'], 'base_version': bv, 'merged_onto_version': cur_v, 'served_sha': I['served'][:12], 'already_in_served': contained(I['path'], cur, patch)} if P is None: row['verdict'] = 'BASE-REFUSES'; row['detail'] = err else: d = tempfile.mkdtemp() for nm, b in (('cur', cur), ('base', base), ('pat', P)): open(os.path.join(d, nm), 'wb').write(b) m = git(['merge-file', '-p', '-L', f'served-v{cur_v}', '-L', f'base-v{bv}', '-L', f'patched-#{rid}', 'cur', 'base', 'pat'], d) merged = m.stdout; n = m.returncode lines = merged.decode('utf-8', errors='replace').split('\n') hunks = [i + 1 for i, l in enumerate(lines) if l.startswith('<<<<<<< ')] row['verdict'] = 'CLEAN' if n == 0 else ('CONFLICT' if n > 0 else 'ERROR') row['conflicts'] = n; row['conflict_marker_lines'] = hunks[:10] row['merged_sha'] = hashlib.sha256(merged).hexdigest()[:12] if n == 0 else None row['merged_equals_served'] = (merged == cur) if n == 0 else None if n > 0: ctx = [] for h in hunks[:3]: seg = lines[h - 1:h + 6]; ctx.append(' | '.join(s[:70] for s in seg)) row['conflict_context'] = ctx shutil.rmtree(d) rows.append(row) out.append(f"ROW #{rid} {I['path']}: base v{bv} -> served v{cur_v}: {row['verdict']}" + (f", {row.get('conflicts')} conflict hunk(s) at merged lines {row.get('conflict_marker_lines')}" if row.get('conflicts') else '') + (f", merged sha {row['merged_sha']}, merged == served: {row['merged_equals_served']}" if row.get('merged_sha') else '') + f"; patch already contained in served: {row['already_in_served']}") print('\n'.join(out)) print('VERDICT ' + json.dumps({'control': ok_ctl, 'rows': [{k: r[k] for k in ('return', 'verdict', 'base_version', 'merged_onto_version', 'already_in_served')} for r in rows]})) json.dump(rows, open(os.path.join(HERE, 'merge4599.json'), 'w'), indent=1)