#!/usr/bin/env python3
"""Opus 5.5's Bayesian bandit over the black cells (2026-12-01; dreeves: "can we get principled with a scoring system, like
anything that would be changed gold-trimmed cells is worth a lot, black cells past 2048 are worth a lot less, etc, and then
just sort the black cells by expected score ... some way to have a dynamic list and always be grinding on whatever's
currently at the top of that list", then "oh, right, bayesian bandit").

    python3 -B searchwatch/bandit.py list            prints the grinder's list, or scores one worker when it is idle
    python3 -B searchwatch/bandit.py grind SLOTS     searches one cell per batch, with SLOTS different seeds
    ... searchwatch/bandit.py eta N M W              the estimator of a pull (see track.py's vocabulary)

  cell      a black cell N:M of Figure 1 (no sequence of length N and order M is known, none is ruled out), or a length past
            Figure 1 whose find would move a gold ring of Figure 2.
  worth     what a find at a cell would change on the page, in POINTS: for each gold ring of either figure that it moves or
            settles, ring; for each cell it colors, near in the figure's opening view (NEAR: its last column) and far past
            it.  A find colors the cells under it, and others by products and joins (closure); the powers of 2 it lifts are
            the arm's pow2 (below).
  arm       a cell and a window W of the tilted search (searches/tilted/tilted.py): a line of arms.jsonl,
            {n, m, W, d, top, setup, exists, before, pow2}: d the lattice's dimension, top the reading (reach.py: log2 of the
            solutions that the model gives the best coset), setup the core-hours of a pull before it searches, exists the
            prior chance that such a sequence exists, before the core-hours searched in vain before this file, pow2 the
            [k, order] of each power of 2 whose known order the find would raise.
  rate      an arm's finds per core-hour of search, unknown: log10 of the hours per find is the line of PRIOR at the arm's
            reading and dimension plus SCALE times a Student t of NU degrees (fitted on the 121 logged settings of the
            search of 2026-11-11 to 2026-11-29, leave-one-out: scratch/grind-20261201/fit3.py and fit4.py; under the hinge the
            rate halves about with the solutions a coset holds), and no find comes at all if nothing exists.  A run's own
            reading is NOISE bits under reach.py's.  Hours searched without a find weigh the slow rates, and
            the chance that nothing exists, up (Bayes).
  pull      one run of an arm: one process, its slice of search or to its first find, under track.py (search `bandit`), in
            runs/bandit/NAME, its settings in pull.jsonl there and its output in pull.log (names that VS Code's Live Server
            ignores, as it does scratch/: the page on localhost:5501 reloads for every other file that changes).
  batch     one pull per worker, all searching the same cell at the same window with different seeds and the same time limit.
  score     expected points per core-hour for a batch. The model uses each single-threaded worker's logged hours as
            an estimate of core-hours and charges setup once per worker. At a given find rate,
            search hours across seeds add until the first find or the time limit. The score counts the cell's worth once.
            It chooses the per-worker time limit that gives the highest score. While pulls are running, the list discounts
            a new batch's reward by the chance that a running pull finds the cell first.
  list      each cell's best arm, by score; then the black cells with no arm, and why (ARMLESS).
  grind     each PERIOD seconds: what has ended is read, each pull's find (its first witness) is checked (verify_witness.py)
            and written to runs/bandit/finds.jsonl, the other pulls of a found cell are stopped, and the list is written.
            Once every pull has ended, the grinder chooses the highest-scoring cell for the next batch. A restart reads
            the same records and lets existing pulls finish. One grinder holds finds.jsonl's lock. A failed pull or false find stops it.

Quals: quals_bandit.py
"""
import sys
sys.dont_write_bytecode = True
import os, re, glob, json, time, fcntl, signal, functools, contextlib, subprocess
import numpy as np
import track
HERE = track.HERE
DIR = os.path.join(HERE, 'runs', 'bandit')
LIST = os.path.join(HERE, 'scratch', 'bandit.md')
TILTED = os.path.join(HERE, 'searches', 'tilted')
POINTS = dict(ring=10.0, near=1.0, far=0.1)
NEAR = dict(mstar=2048, pow2=128)
SETTLES = 'at window 280 the setup passes 2^62; wider windows are to be read'
ARMLESS = {(480, 13): 'no antisymmetric one exists (proofs/symtree.py), and the tilted search finds no others', (528, 12): 'swept (scratch/sweep528-20261127/NOTES.md)',
           **{c: SETTLES for c in ((3360, 20), (3360, 21), (3360, 22), (3360, 23), (3360, 24), (3840, 19), (3840, 20))}, (3936, 18): 'not read yet'}      # the black cells with no arm, and why
PRIOR = dict(base=0.969, top=-0.0520, low=0.25, hinge=15.0, d=0.0335)      # log10 hours per find: base + top x + low max(0, hinge - x) + d (dimension - 200), x a run's reading
SCALE, NU = 0.256, 2
NOISE = 5.0
Z = np.linspace(-12, 12, 241)
WZ = (1 + Z ** 2 / NU) ** (-(NU + 1) / 2)
WZ = WZ / WZ.sum()
SLICES = np.geomspace(1 / 30, 24, 40)                            # hours of search a pull may be given
CORES = 6.5                                                      # what this Mac gives its background jobs (2026-11-29)
PERIOD = 5                                                       # seconds between the grinder's looks
PINS, SETTINGS = '8,9,5,7,11,13,17,19,23,29', '--kout 30 --stop 1 --gumbel 0 --field 0.35 --floor 1 --sag 0.4 --every 60 --maxnodes 1e9'.split()


# ---------- worth ----------

def charts(root=HERE):
    """The bounds of both figures' columns, {figure: {lo, hi}}, as the page's data have them, index 0 unused."""
    out = {}
    for name in ('mstar', 'pow2'):
        src = open(os.path.join(root, 'pagedata', f'{name}.js'), encoding='utf-8').read()
        cols = json.loads(src[src.index('{'):src.rindex('}') + 1])['cols']
        out[name] = dict(lo=[0] + [c[0] for c in cols], hi=[0] + [c[1] for c in cols])
    return out


def closure(lo, n, m):
    """The lower bounds lo once a sequence of length n and order m is known: products add orders, joins take the lesser."""
    lo, work = list(lo), [(n, m)]
    while work:
        x, v = work.pop()
        if x < len(lo) and v > lo[x]:
            lo[x] = v
            work += [(x * b, v + lo[b]) for b in range(2, (len(lo) - 1) // x + 1)] + [(x + b, min(v, lo[b])) for b in range(1, len(lo) - x)]
    return lo


def lifted(lo, pairs):
    """The powers of 2's lower bounds once each [k, order] of pairs is known: exponents add, and orders."""
    lo, work = list(lo), [tuple(p) for p in pairs]
    while work:
        k, v = work.pop()
        if k < len(lo) and v > lo[k]:
            lo[k] = v
            work += [(k + j, v + lo[j]) for j in range(1, len(lo) - k)]
    return lo


def rings(lo, hi, shift):
    """{row: (the least column known to reach it, the least not ruled out)}, each None where no column does: the gold rings
    of page/shared.js's raised, row r of column i the order r + shift(i)."""
    out, a, b = {}, 0, 0
    for i in range(1, len(lo)):
        l, h = lo[i] - shift(i), hi[i] - shift(i)
        for r in range(a + 1, l + 1): out.setdefault(r, [None, None])[0] = i
        for r in range(b + 1, h + 1): out.setdefault(r, [None, None])[1] = i
        a, b = max(a, l), max(b, h)
    return {r: tuple(v) for r, v in out.items()}


def effect(before, after, hi, near, shift):
    """What the lower bounds' change from before to after changes on a figure: the rows whose ring moves, and the cells
    colored in its opening view and past it."""
    old, new = rings(before, hi, shift), rings(after, hi, shift)
    gain = [a - b for a, b in zip(after, before)]
    return dict(rings=[(r, old.get(r), new.get(r)) for r in sorted(set(old) | set(new)) if old.get(r) != new.get(r)],
                near=sum(gain[:near + 1]), far=sum(gain[near + 1:]))


def points_of(before, after, hi, near, shift, points):
    e = effect(before, after, hi, near, shift)
    return points['ring'] * len(e['rings']) + points['near'] * e['near'] + points['far'] * e['far']


@functools.lru_cache(maxsize=None)
def known(lo, finds):
    """The lower bounds lo (a tuple) with the finds, not yet on the page, (length, order) each."""
    for n, m in sorted(finds): lo = closure(lo, n, m)
    return tuple(lo)


def attained(n, m, lo, finds):
    """Whether the updated chart or a verified witness beyond its last column already reaches n:m."""
    return (n < len(lo) and lo[n] >= m) or any(length == n and order >= m for length, order in finds)


@functools.lru_cache(maxsize=None)
def effects(n, m, pow2, finds, data):
    """The effects of a find of order m at length n on Figures 1 and 2, data the charts' bounds as tuples."""
    (lo1, hi1), (lo2, hi2) = data
    base = known(lo1, finds)
    if attained(n, m, base, finds): pow2 = ()       # a second witness earns no credit for the first one's powers of two
    return (effect(base, closure(base, n, m), hi1, NEAR['mstar'], lambda i: 0), effect(lo2, lifted(lo2, pow2), hi2, NEAR['pow2'], lambda i: i))


def frozen(charts): return tuple((tuple(charts[k]['lo']), tuple(charts[k]['hi'])) for k in ('mstar', 'pow2'))


def both(a, charts, finds): return effects(a['n'], a['m'], tuple(map(tuple, a['pow2'])), finds, frozen(charts))


def worth(a, charts, finds):
    return sum(POINTS['ring'] * len(e['rings']) + POINTS['near'] * e['near'] + POINTS['far'] * e['far'] for e in both(a, charts, finds))


# ---------- the chance of a find ----------

def rates(a):
    """The arm's rates on their grid, finds per core-hour of search, and their prior weights, given that something exists."""
    x = a['top'] - NOISE
    mu = PRIOR['base'] + PRIOR['top'] * x + PRIOR['low'] * max(0.0, PRIOR['hinge'] - x) + PRIOR['d'] * (a['d'] - 200)
    return 10.0 ** -(mu + SCALE * Z), WZ


def survival(a, t):
    """The chance of no find in the arm's first t core-hours of search."""
    lam, w = rates(a)
    return 1 - a['exists'] * (1 - float(w @ np.exp(-lam * t)))


def exists(a, t):
    """The chance that something exists, given no find in t core-hours."""
    lam, w = rates(a)
    return a['exists'] * float(w @ np.exp(-lam * t)) / survival(a, t)


def score(a, points, searched, flying, workers=1):
    """Expected points per core-hour and the search time limit in hours for each worker, given past and in-flight effort."""
    lam, w = rates(a)
    done = a['before'] + searched
    left = a['exists'] * w * np.exp(-lam * (done + flying))
    exposure = workers * SLICES
    hit = -np.expm1(-np.outer(exposure, lam))
    chance = hit @ left / survival(a, done)
    spent = workers * a['setup'] + ((1 - a['exists']) * exposure + hit @ (left / lam)) / survival(a, done + flying)
    value = points * chance / spent
    i = int(np.argmax(value))
    return float(value[i]), float(SLICES[i])


def arms(root=HERE):
    return [json.loads(s) for s in open(os.path.join(root, 'searchwatch', 'arms.jsonl'), encoding='utf-8')]


def key(a): return a['n'], a['m'], a['W']


def ranking(arms, charts, finds, searched, flying, workers=1):
    """The list: for each cell its best arm's row, the highest score first.  A pull's find counts for what it adds to the
    pulls in flight of the cell's other arms: times the chance that they are in vain."""
    vain = {key(a): survival(a, a['before'] + searched.get(key(a), 0.0) + flying.get(key(a), 0.0)) / survival(a, a['before'] + searched.get(key(a), 0.0)) for a in arms}
    rows = {}
    for a in arms:
        s, f, cell = searched.get(key(a), 0.0), flying.get(key(a), 0.0), (a['n'], a['m'])
        points = worth(a, charts, finds)
        value, hours = score(a, points, s, f, workers)
        row = dict(cell=cell, arm=a, worth=points, score=value * float(np.prod([vain[key(b)] for b in arms if (b['n'], b['m']) == cell])) / vain[key(a)], slice=hours,
                   searched=s, flying=f, effects=both(a, charts, finds), day=1 - survival(a, a['before'] + s + 24 * CORES) / survival(a, a['before'] + s))
        rows[cell] = max(rows.get(cell, row), row, key=lambda r: r['score'])
    return sorted(rows.values(), key=lambda r: -r['score'])


# ---------- the estimator ----------

def estimate(a, age, searched, running, found):
    """The estimate, without its time, of the search at the arm's cell: age its seconds of running, searched its core-hours since
    arms.jsonl, running its pulls at work, found whether one of them found.  The time to go is to a find, given that something
    exists."""
    lam, w = rates(a)
    done = a['before'] + searched
    left = w * np.exp(-lam * done)
    def hours(q):
        lo, hi = 1e-9, 1e15
        for _ in range(200):
            mid = (lo * hi) ** 0.5
            lo, hi = ((lo, mid), (mid, hi))[float(left @ np.exp(-lam * mid)) > (1 - q) * float(left.sum())]
        return hi
    to_go = {k: 3600 * hours(q) / running for k, q in (('lo', 0.1), ('median', 0.5), ('hi', 0.9))}
    return dict(event='estimate', basis='bandit', unit='seconds', done=age, rate=1.0, total={k: age + v for k, v in to_go.items()}, to_go=to_go,
                prior=a['exists'], exists=max(exists(a, done), float(found)), finds=None, pending=None, finished=None)


# ---------- the pulls ----------

def searched(log):
    """The core-hours of search that a pull's log tells of so far: its last line's seconds of beam and of enumeration."""
    return sum(map(int, ([('0', '0')] + re.findall(r'beam (\d+)s,? enum(?:eration)? (\d+)s', log))[-1])) / 3600


def pulls():
    """Every pull, in the order they started: its settings (pull.jsonl), its record's state and end, its hours searched, and its
    find, the first witness of its found file (a batch of rich cosets gives many), or none."""
    procs, out = track.processes(), []
    for path in glob.glob(os.path.join(track.RUNS, 'bandit-*.jsonl')):
        record = track.lines(path)
        d = os.path.join(DIR, record[0]['name'])
        p = json.load(open(os.path.join(d, 'pull.jsonl')))
        log = open(os.path.join(d, 'pull.log'), encoding='utf-8', errors='replace').read()
        found = [json.loads(s) for f in glob.glob(os.path.join(d, 'found_*.jsonl')) for s in open(f)][:1]
        out.append(dict(p, name=record[0]['name'], state=track.state(record, procs), status=record[-1].get('status'), tracker=record[0]['tracker'],
                        time=record[0]['time'], searched=searched(log), found=found))
    return sorted(out, key=lambda p: p['time'])


@functools.lru_cache(maxsize=None)
def verified(n, m, code):
    """The order of the code, by verify_witness.py, which imports nothing of this repository; a code of order less than m stops it."""
    out = subprocess.run([sys.executable, '-B', os.path.join(TILTED, 'verify_witness.py'), str(n), str(m), code], capture_output=True, text=True)
    # TODO: error copy; says a search reported a witness that the independent checker refuses, and shows what it said
    assert out.returncode == 0, f'Testis falsus {n}:{m}: {out.stdout}{out.stderr}'
    return int(re.search(r'^OK: order (\d+)', out.stdout, re.M)[1])


def finds(ps):
    """The pulls' witnesses, each checked: {(length, order)}; every one is in finds.jsonl once."""
    path = os.path.join(DIR, 'finds.jsonl')
    listed = {json.loads(s)['code'] for f in glob.glob(path) for s in open(f)}
    out = set()
    for p in ps:
        for w in p['found']:
            order = verified(w['n'], w['m'], w['code'])
            out.add((w['n'], order))
            if w['code'] not in listed:
                listed.add(w['code'])
                with open(path, 'a') as f: f.write(json.dumps(dict(n=w['n'], m=w['m'], order=order, code=w['code'], pull=p['name'], time=time.time())) + '\n')
    return frozenset(out)


def launch(a, hours, seed):
    name = f"bandit-{a['n']}-{a['m']}-w{a['W']}-s{seed}"
    d = os.path.join(DIR, name)
    os.makedirs(d)
    json.dump(dict(n=a['n'], m=a['m'], W=a['W'], seed=seed, slice=hours), open(os.path.join(d, 'pull.jsonl'), 'w'))
    me = os.path.join(HERE, 'searchwatch', 'bandit.py')
    command = [sys.executable, '-B', os.path.join(HERE, 'searchwatch', 'track.py'), 'run', name, 'bandit', f"{a['n']}:{a['m']}", '--found', os.path.join(d, f"found_{a['n']}_{a['m']}.jsonl"),
               me, 'eta', str(a['n']), str(a['m']), str(a['W']), '--', '/usr/bin/nice', '-n', '5', sys.executable, '-B', '-u', os.path.join(TILTED, 'tilted.py'),
               str(a['n']), str(a['m']), str(a['W']), '1.1', PINS, '300', str(round(3600 * hours)), '--seed', str(seed), *SETTINGS]
    env = dict(os.environ, PYTHONPATH=os.path.join(HERE, 'scratch', 'lower24-design', 'beyond1000', 'pylib'),
               **{k: '1' for k in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'VECLIB_MAXIMUM_THREADS', 'NUMEXPR_NUM_THREADS')})
    with open(os.path.join(d, 'pull.log'), 'w') as log:
        subprocess.Popen(command, cwd=d, env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True)
    record, until = os.path.join(track.RUNS, name + '.jsonl'), time.time() + 60
    while not os.path.exists(record):
        # TODO: error copy; says a pull was launched and wrote no record within a minute, naming it
        assert time.time() < until, f'Nullus cursus: {name}'
        time.sleep(0.1)


def look():
    """What the records and the pulls' directories hold: the pulls, the page's charts, the finds, the pulls at work, and for each arm the
    core-hours searched in vain and those in flight."""
    ps = pulls()
    running = [p for p in ps if p['state'] == 'running']
    hours, flying = {}, {}
    for p in ps: hours[key(p)] = hours.get(key(p), 0.0) + p['searched']
    for p in running: flying[key(p)] = flying.get(key(p), 0.0) + max(0.0, p['slice'] - p['searched'])
    return ps, charts(), finds(ps), running, hours, flying


def step(slots):
    """Check for finds. Choose one cell for all slots once every previous pull has ended."""
    ps, page, got, running, hours, flying = look()
    for p in ps:
        # TODO: error copy; says a pull failed (its exit status is neither 0 nor that of a stop), naming it and where its log is
        assert p['status'] in (None, 0, -signal.SIGTERM), f"Cursus defecit: {p['name']}, {os.path.join(DIR, p['name'], 'pull.log')}"
    lo = known(tuple(page['mstar']['lo']), got)
    for p in running:
        if attained(p['n'], p['m'], lo, got) and not p['found']:              # the pull that found its cell ends by itself
            with contextlib.suppress(ProcessLookupError): os.kill(p['tracker'], signal.SIGTERM)      # or it has just ended
    rows = ranking(arms(), page, got, hours, flying, slots)
    if not running:
        top = rows[0]
        # TODO: error copy; says no cell of the list has a score above 0, so there is nothing to grind on
        assert top['score'] > 0, 'Nihil restat'
        last = max((p['seed'] for p in ps if key(p) == key(top['arm'])), default=1000)
        for seed in range(last + 1, last + slots + 1):
            launch(top['arm'], top['slice'], seed)
        # A short pull can finish before the last tracker starts. Report the workers actually running.
        _, page, got, running, hours, flying = look()
        rows = ranking(arms(), page, got, hours, flying, slots)
    write(rows, running, got, slots)


# ---------- the list ----------

def said(row):
    """What a find at the row's cell changes, in few words."""
    one, two = row['effects']
    moves = [f'order {r}: {a and a[0]} to {b[0]}' for r, a, b in one['rings']] + [f'excess {r}: 2^{a and a[0]} to 2^{b[0]}' for r, a, b in two['rings']]
    return '; '.join(moves + [f"{one['near'] + two['near']} near, {one['far'] + two['far']} far"])


def write(rows, running, got, workers=1):
    """The list, in scratch/bandit.md, written whole."""
    at = {}
    for p in running: at[p['n'], p['m']] = at.get((p['n'], p['m']), 0) + 1
    # TODO: label the proposed number of workers times each worker's search limit in hours.
    text = f'| cell | score | worth | chance in a day | window | hours searched | running | h per cursum ({workers} simul) | a find changes |\n|---|---|---|---|---|---|---|---|---|\n' + ''.join(
        f"| {r['cell'][0]}:{r['cell'][1]} | {r['score']:.3g} | {r['worth']:.3g} | {r['day']:.2g} | {r['arm']['W']} | {r['arm']['before'] + r['searched']:.2f} | {at.get(r['cell'], 0)} | {r['slice']:.3g} | {said(r)} |\n" for r in rows)
    have = {r['cell'] for r in rows}
    text += ''.join(f'| {n}:{m} | | | | | | | | no arm: {why} |\n' for (n, m), why in ARMLESS.items() if (n, m) not in have)
    os.makedirs(os.path.dirname(LIST), exist_ok=True)
    with open(LIST + '.tmp', 'w') as f: f.write(text)
    os.replace(LIST + '.tmp', LIST)
    return text


def open_log(name):
    os.makedirs(DIR, exist_ok=True)
    return open(os.path.join(DIR, name), 'a')


def grind(slots):
    # TODO: error copy; a batch needs at least one worker.
    assert slots > 0, 'Saltem unus operarius requiritur'
    with open_log('grind.log') as owner, open_log('finds.jsonl') as lock:
        fcntl.flock(owner, fcntl.LOCK_EX | fcntl.LOCK_NB)             # a second grinder must exit
        fcntl.flock(lock, fcntl.LOCK_EX)                              # an offline list can finish publishing
        while True:
            step(slots)
            time.sleep(PERIOD)


def listed():
    """Read the active grinder's report. When idle, score a single worker from the current records."""
    with open_log('finds.jsonl') as lock:
        while True:
            try:
                fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
                break
            except BlockingIOError:
                try:
                    with open(LIST) as report: return report.read()
                except FileNotFoundError:                            # the grinder is preparing its first report
                    time.sleep(0.1)
        _, page, got, running, hours, flying = look()
        return write(ranking(arms(), page, got, hours, flying), running, got)


def eta(n, m, W):
    record, now = os.environ[track.RECORD], time.time()
    a = next(a for a in arms() if key(a) == (n, m, W))
    mine = [p for p in pulls() if (p['n'], p['m']) == (n, m)]
    age = track.running(track.search_of(record, now)[1], now)
    track.append(record, dict(estimate(a, age, sum(p['searched'] for p in mine if p['W'] == W), max(1, sum(p['state'] == 'running' for p in mine)), any(p['found'] for p in mine)), time=now))


def main(argv):
    # TODO: usage; the list, the grinder with its number of pulls at once, or a pull's estimator
    usage = 'Usus: bandit.py list | grind SLOTS | eta N M W'
    modes = {('list', 1): lambda: print(listed()), ('grind', 2): lambda: grind(int(argv[1])), ('eta', 4): lambda: eta(*map(int, argv[1:]))}
    assert __debug__ and (argv[:1] + [''])[0] in {k for k, _ in modes} and (argv[0], len(argv)) in modes, usage
    modes[argv[0], len(argv)]()


if __name__ == '__main__': main(sys.argv[1:])
