#!/usr/bin/env python3
"""Fable 5.2's estimator (see track.py's vocabulary) of a sweep, searches/tilted/sweep.py (2026-11-27; dreeves, of the
528:12 search's box: "i find it hard to believe that this lindy-only ETA is the best we can do").  A sweep enumerates
fixed lists of cosets, one list a profile, each coset once, so its work is countable.  The tracker runs it as

    python3 -B searchwatch/track.py run NAME SEARCH N:M --found DIR/found.jsonl searchwatch/sweep_eta.py DIR -- COMMAND ...

and each time it is run it appends one estimate, of the whole sweep, to the record that TRACK_RECORD names.

  DIR       the sweep's directory.  The sweep is its lists, whichever run started them: a list is a curve X.curve.json
            there with its log X.jsonl, so the runs of one sweep all give the same estimate, and a list is counted
            from the moment its curve is there.  found.jsonl there is the sweep's file of witnesses, a line each.
  model     DIR/model.json, {count, controls, recovery, why}, read at every estimate, so that a revised model needs
            no relaunch (2026-11-27, evening; until then the first two were arguments of each launch): count, the
            witnesses the count model expects before the sweep, over everything it counts; controls, the count
            model's record where the truth could be counted, each [cosets found with a witness, cosets it predicted]
            (at 544:10, 46 where it predicted 56.7); recovery, the chance that the enumeration finds a witness in a
            coset it sweeps; why, where the three come from.  Until the night of 2026-11-28 the model stated a
            calibration, one control's quotient, and the count times it was taken as exact: see doubt.
  doubt     (2026-11-28, night; dreeves, of probabilities that had fallen for hours and were put back by a revised
            model: "it's the epitome of 'fool me once, shame on you, fool me twice, shame on me'".)  The true count
            is the model's times q, and q is known as far as the controls tell it: a control that found x cosets
            where the model predicted p says of q what x + 1 events at exposure p say of a rate (a flat prior: a gamma
            law of shape x + 1 and rate p), and the cell is as likely to be like one control as like another.  Then
            no witness among s of the count's expected ones has chance keep(s), the mean over the controls of
            (p / (p + s))^(x + 1): exp(-s x / p) of a control too large to doubt, and less sure than that of a small
            one.  A sweep that finds nothing so gives weight to the controls, and to the q, under which that was
            likely: what is left of its count shrinks by more than the cosets swept.
  log       a list's, sweep.py's: a line a chunk of cosets, with the list's digest and length K, the cosets to
            sweep (count, at most K), the chunk's first and last coset, its nodes and the time it ended.
  curve     that list's expected witnesses, JSON {digest, K, W, floor, curve: [[k, the witnesses expected in its best
            k cosets], ...], cost: [[k, the nodes its planner expects its best k cosets to take], ...]}, k rising to
            K; read by straight lines, from 0 at k = 0.  cost is [] where the planner has no price for the list (a
            first pass: a later one is priced by the pass before it on the same cosets).  One of another list stops
            the estimator.

  plan      DIR/plan.jsonl, a line a list the sweep is to take: {name, W, floor, count, credit, nodes}; a line
            without one of the six stops the estimator (2026-11-28, evening: until then a line of a list begun
            was read for its name, count and nodes alone).  A planned
            list with no curve yet (NAME.curve.json) has not begun, or has no first chunk: it counts by its kind
            (2026-11-28; dreeves, of the ETA chart, whose time to go had jumped at each list a launcher started:
            "these ETAs sure don't look calibrated"), and its credit, the expected witnesses its pass would add in a
            curve's units, counts in finds (that morning: a stage whose launcher starts its lists a few at a time
            read 2% where it held 13%).  nodes (that afternoon) is the list's price: what its planner expects it to
            take from its first coset to its count, or 0 where it states none.  A list not begun with a price counts
            at it, times PRICED, in place of its kind: a list of a kind the sweep has not yet swept (the first lists
            at width 220, floor 4) has no measure there, and read as the latest lists of any kind, a hundredth of its
            nodes.  (A list begun is priced by its curve's cost: see work.)  A list begun counts to its plan's count where that is more than its log was ever asked for
            (a cut list's last line keeps that as `was`, so the plan line of before a cut does not undo it): a later
            stage takes a list further (sweep.py: a larger COUNT extends it), and the extension is the sweep's work
            from the moment it is planned.
  kind      a list's width, floor and count (a curve states W and floor).  What a list of a kind takes, in nodes:
            what the lists of that kind swept to their counts took, the RECENT latest of them to end (a cut list is
            none: its last line has `was`);
            with none, what its kind's lists under way are forecast to take in all by their own cost; with none of
            those either, the same of any kind.
  work      in nodes.  done: the logs' nodes.  A priced list's nodes to come (2026-11-28, night; dreeves, of the cost
            by position: "that sounds like a can-opener question"): the price of its cosets left, times its ratio of
            nodes to price, which is the plan's (PRICED) for a prior worth KAPPA of the list and the list's own so
            far, at SHAPED, for the cosets swept:  (P - p) (KAPPA P PRICED + d SHAPED) / (KAPPA P + p),  P its
            price to its count, p the price of the cosets swept, d their nodes.  Not begun (p = d = 0) that is PRICED
            times its price; it holds from the first chunk on.  On 132 width-210 lists at floor 4, each priced at 41
            times floor 3's nodes by position, the rest of a list lay between the low and the high of that at 92 to
            100 in 100 of the shares swept from a hundredth to four fifths, and the median within 3 in 100 of it
            (scratch/calibrated-20261128/blend_forecast.py); the forecast below, of an unpriced list, read 0.87 to
            2.07 of the rest at a twentieth swept.  An unpriced list's nodes to come: its latest chunks' nodes a coset (LATEST: the
            chunks that end in the last tenth of its swept cosets), taken as the cost at their middle position, falling
            as position^-b down the rest of its list.  DECAY's three b give the total's low end, median and high end;
            at 528:12 a coset's tree had 6.0e6 nodes at position 500, 2.6e6 at 10,000, 1.3e6 at 100,000 and 5.9e5 at
            900,000, b from 0.28 to 0.35.  An unpriced list with less than EARLY of its cosets swept says little of
            its own cost (its top cosets are its dearest): it is forecast as a list of its kind, less its nodes
            done, where there is a measure of its kind.  A planned list not begun: at its
            price or, with none, as a list of its kind (or, with no measure, as the lists under way).  The low, median and high of a kind are the tenth, middle and ninetieth
            hundredths of what its lists took.  rate: the nodes a second of the lists running, by their latest
            chunks: those not swept to their counts whose newest chunk is within ACTIVE seconds of the directory's
            newest (with none, the lists that close to it: a record's rate is positive).
  to_go     the nodes to come, all lists', at that rate: the lists share the machine's cores, and the planned ones
            wait for them; or the longest of the lists' own times where that is longer (a list's: its nodes to come
            at its speed, the wall seconds a node of the middle one of its latest chunks, by seconds a node; of two
            middle ones, the quicker.  A chunk's wall seconds: from the chunk before it; the first's, its CPU
            seconds.  So the first chunk of a list taken up again holds the wait between its two runs, and the
            middle chunk's speed passes it by: until 2026-11-28 the latest chunks' seconds were summed over their
            nodes, and as a stage that takes lists further began, the page's time to go read 588 hours).  Times SPEED:
            of 944 forecasts of the rests of 236 lists swept whole, a tenth took under 0.89 of the time their speed
            gave, half under 1.14 and a tenth over 1.54 (scratch/sweepeta-20261128/speed.py), so the band holds the
            speed's spread and not the nodes' alone, and its middle the slower chunks that the middle one passes by.
            (0.8, 1.0, 1.7 that morning, from 43 lists, by the summed seconds.  Until 2026-11-28 the longest of the
            lists' own times, of the lists begun.)
  pending   the cosets left to sweep, the planned lists' too; finished, those swept.
  prior     1 - keep(M), M the model's count: the witnesses are taken as Poisson, at the count times q (see doubt).
  exists    1 - keep(M) / keep(S), S = recovery c, c the curves' expected witnesses at the cosets swept: what the sweep
            would have found by now; 1 once found.jsonl has a line.  (Of a count beyond doubt, 1 - exp(-(M - S)).)
  finds     1 - keep(T) / keep(S), T = recovery C, C the curves' expected witnesses in the cosets the sweep takes (each
            log's count: a long list may be swept a part at a time, 2026-11-27 night; the whole lists until then): the chance that the sweep
            itself finds a witness in the cosets it has left (2026-11-27; dreeves: "if the chance that the current
            search ... finds a witness is very different from that then that should also be shown on the page"); 1 once
            found.jsonl has a line.  C holds the planned lists' credits too (2026-11-28), so it rises when a list
            joins the plan, not when it begins.  T is at most M (asserted, that evening): lists and a plan that
            would find more witnesses than the count says exist have a wrong credit or curve, and finds would read
            over exists.  Given nothing found, neither exists nor finds can rise but by a change of the model or of
            the plan: the plan is to hold the whole sweep from its start, down to the yield at which it stops.

Quals: quals_sweep_eta.py
"""
import sys
sys.dont_write_bytecode = True
import os, glob, json, math, time
import numpy as np
import track

DECAY = (0.4, 0.3, 0.2)          # b for the total's lo, median, hi
LATEST = 0.9                     # a log's latest chunks end past this share of its swept cosets
EARLY = 0.02                     # a list with less than this share of its cosets swept is forecast by its kind
ACTIVE = 900                     # seconds: a list is running if its newest chunk is this close to the directory's newest
RECENT = 5                       # a kind is measured by this many of its lists, the latest to end: lists run in the order of their profiles' ranks, and a later rank's is cheaper
SPEED = (0.9, 1.15, 1.55)        # a time to go's lo, median, hi, over what the speeds read give (measured: see to_go)
PRICED = (0.9, 1.05, 1.2)        # a price's lo, median, hi: of 132 width-210 lists at floor 4, priced at 41 times floor 3's nodes on their cosets, a tenth took under 0.91 of the price, half under 1.06, a tenth over 1.18
KAPPA = 0.1                      # what a list's price is worth beside its own nodes, as a share of the list (see work)
SHAPED = (0.9, 0.97, 1.05)       # a list's ratio of nodes to price so far, as its rest's: lo, median, hi (the ratio falls a little down a list; measured: see work)


def log_work(rows, curve):
    """A list's (nodes done, cosets swept, cosets left, nodes to come by its own cost at each of DECAY, wall seconds a node
    (its speed: see to_go), expected witnesses swept, expected witnesses in the cosets the sweep takes (its count's, of a
    list swept in part), kind, its newest chunk's time, whether it measures its kind: swept to its count and not cut,
    the cosets from which its own forecast counts: none of a priced list, EARLY of an unpriced one).  Of a priced list
    the nodes to come are the blend's (see work) at lo, median, hi."""
    assert len({(r['digest'], r['K']) for r in rows} | {(curve['digest'], curve['K'])}) == 1, 'the curve is of another list'
    ks, cs = zip(*curve['curve'])
    assert list(ks) == sorted(set(ks)) and ks[-1] == curve['K'] and all(c >= 0 for c in cs) and list(cs) == sorted(cs), 'the curve does not cover its list'
    cost = [(0, 0.0)] + [tuple(x) for x in curve['cost']]
    assert all(a[0] < b[0] and a[1] <= b[1] for a, b in zip(cost, cost[1:])) and (cost[-1][0], cost[-1][1] > 0) in ((0, False), (curve['K'], True)), 'the cost is not the list\'s'
    swept, count = rows[-1]['last'] + 1, rows[-1]['count']
    walls = [rows[0]['cpu_s']] + [b['time'] - a['time'] for a, b in zip(rows, rows[1:])]
    late = [(r, w) for r, w in zip(rows, walls) if r['last'] + 1 > LATEST * swept]
    nodes, cosets = (sum(v) for v in zip(*((r['nodes'], r['last'] + 1 - r['first']) for r, w in late)))
    pace = sorted(w / r['nodes'] for r, w in late)[(len(late) - 1) // 2]            # the middle chunk's wall seconds a node
    mid = (late[0][0]['first'] + swept) / 2
    done = sum(r['nodes'] for r in rows)
    P, p = (float(np.interp(k, *zip(*cost))) for k in (count, swept))            # the list's price to its count, and that of the cosets swept
    come = ([(P - p) * (KAPPA * P * a + done * b) / (KAPPA * P + p) for a, b in list(zip(PRICED, SHAPED)) * bool(curve['cost'])]      # a priced list: the blend
            or [nodes / cosets * mid ** b * (count ** (1 - b) - swept ** (1 - b)) / (1 - b) for b in DECAY])                              # an unpriced one: its latest chunks' cost, falling
    at = lambda k: float(np.interp(k, (0,) + ks, (0.0,) + cs))
    return (done, swept, count - swept, come, pace, at(swept), at(count),
            (curve['W'], curve['floor'], count), rows[-1]['time'], swept == count and 'was' not in rows[-1], EARLY * count * (not curve['cost']))


def estimate(model, witnesses, works, plans):
    """The estimate, without its time, of a sweep whose lists' works are works (log_work's) and whose planned lists
    without a curve yet are plans, each (its kind, its credit, its price), by its model (model.json)."""
    planned = [kind for kind, credit, nodes in plans]
    assert set(model) == {'count', 'controls', 'recovery', 'why'} and type(model['why']) is str, 'model.json holds count, controls, recovery and why'
    M, controls, recovery = model['count'], model['controls'], model['recovery']
    assert M > 0 and 0 < recovery <= 1 and controls and all(len(c) == 2 and c[0] >= 0 and c[1] > 0 for c in controls), model
    keep = lambda s: sum(math.exp(-(found + 1) * math.log1p(s / predicted)) for found, predicted in controls)      # see doubt: its mean over the controls, times their number
    done, cosets, left = (sum(w[i] for w in works) for i in range(3))
    under = [w for w in works if w[2] > 0]                                  # the lists under way: not swept to their counts
    shown = [w for w in under if w[1] >= w[10]]                             # of them, those whose own forecast counts: the priced ones, and the others past their first cosets
    whole = lambda w: w[0] + w[3][1]                                        # what a list under way is forecast to take in all, by its own cost
    last = lambda ws: [w[0] for w in sorted(ws, key=lambda w: w[8])[-RECENT:]]   # the nodes of the latest of them to end
    measures = lambda kind: (last([w for w in works if w[9] and w[7] == kind]) or [whole(w) for w in shown if w[7] == kind]
                             or last([w for w in works if w[9]]) or [whole(w) for w in shown])   # what a list of the kind takes (see kind)
    levels = lambda v: [float(x) for x in np.quantile(v, (0.1, 0.5, 0.9))]
    price = lambda nodes: [f * nodes for f in PRICED] * (nodes > 0)        # a list's price at PRICED's three levels; nothing where the plan states none
    # a list under way: by its own forecast where that counts, or where nothing measures its kind; else by its kind, less its nodes done
    own = lambda w: w in shown or not measures(w[7])
    comes = [(lambda: [max(0.0, x - w[0]) for x in levels(measures(w[7]))], lambda: w[3])[own(w)]() for w in under]
    queue = [price(nodes) or levels(measures(kind) or [whole(w) for w in under]) for kind, credit, nodes in plans]
    come = [sum(c[j] for c in comes + queue) for j in range(3)]
    newest = max(w[8] for w in works)
    close = [w for w in works if w[8] >= newest - ACTIVE]
    rate = sum(1 / w[4] for w in ([w for w in close if w[2] > 0] or close))
    go = [SPEED[j] * max([c[j] * w[4] for c, w in zip(comes, under)] + [come[j] / rate]) for j in range(3)]
    S, begun = (recovery * sum(w[i] for w in works) for i in (5, 6))                        # what the sweep would have found by now, and by its lists' counts, of the count's witnesses
    T = begun + recovery * sum(credit for kind, credit, nodes in plans)                     # and by its plan's end
    assert 0 <= S <= T <= M, 'the lists and the plan hold more witnesses than the count'
    band = lambda v: dict(lo=v[0], median=v[1], hi=v[2])
    return dict(event='estimate', basis='sweep', unit='nodes', done=done, rate=rate,
                total=band([done + c for c in come]), to_go=band(go), prior=1 - keep(M) / len(controls),
                exists=max(1 - keep(M) / keep(S), min(1, witnesses)),
                finds=max(1 - keep(T) / keep(S), min(1, witnesses)), pending=left + sum(kind[2] for kind in planned), finished=cosets)


if __name__ == '__main__':
    assert __debug__ and len(sys.argv) == 2, __doc__
    d = sys.argv[1]
    plan = [{k: x[k] for k in ('name', 'W', 'floor', 'count', 'credit', 'nodes')} for x in map(json.loads, open(os.path.join(d, 'plan.jsonl')))]      # a line states all six
    asked = {x['name']: x['count'] for x in plan}
    def rows_of(curve):
        """The list's log, its last line's count the plan's where the plan asks for more than the log was ever asked for."""
        rows = [json.loads(s) for s in open(curve[:-len('.curve.json')] + '.jsonl')]
        ask = asked.get(os.path.basename(curve)[:-len('.curve.json')], 0)
        return rows[:-1] + [dict(rows[-1], count=(rows[-1]['count'], ask)[ask > rows[-1].get('was', rows[-1]['count'])])]      # the one branch: an extension, or the log as it stands
    works = [log_work(rows_of(curve), json.load(open(curve))) for curve in sorted(glob.glob(os.path.join(d, '*.curve.json')))]
    plans = [((x['W'], x['floor'], x['count']), x['credit'], x['nodes']) for x in plan if not os.path.exists(os.path.join(d, x['name'] + '.curve.json'))]
    track.append(os.environ[track.RECORD], dict(estimate(json.load(open(os.path.join(d, 'model.json'))), sum(1 for _ in open(os.path.join(d, 'found.jsonl'))), works, plans), time=time.time()))
