#!/usr/bin/env python3
"""Fable 5.2's quals for searchwatch/sweep_eta.py, the estimator 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").
Run from the repo:
    python3 -B quals/quals_sweep_eta.py [name ...]
Each qual is a function q_*: a passing qual returns, a failing one raises; each comment gives its replicata and
expectata; a failure's message or traceback gives the resultata.  Each copies searchwatch's track.py and sweep_eta.py
into a temporary directory and runs the estimator there on made-up logs, as the tracker runs it: on a sweep's
directory, which holds its lists and its model (model.json: the count model's witnesses, its calibration, the
enumeration's recovery).  Until the evening of 2026-11-27 the count and the recovery were arguments.  The last quals
replay a stage of the 528:12 sweep as recorded (quals_sweep_eta_recorded.json, beside this file), the estimator run on
the directory as it stood at every fifth minute, and hold its bands to what the stage took.
"""
import sys
sys.dont_write_bytecode = True
import os, json, math, shutil, functools, subprocess, tempfile, traceback
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))   # the repository's root, above quals/
sys.path.insert(0, os.path.join(HERE, 'searchwatch'))
import sweep_eta          # for two of its constants alone (KAPPA, SHAPED: see q_a_priced_list_is_forecast_by_its_price_and_its_ratio_so_far)
PY = sys.executable
LAMBDA, RECOVERY = 2.5, 0.9
# The sweep's model.json (2026-11-27, evening).  controls (2026-11-28, night, in place of calibration; a spec change with the
# estimator's): where the count model was set against a count, [cosets found with a witness, cosets it predicted].  This one
# leaves no doubt of the count (a million million found, as predicted), so the probabilities of the quals written before that
# night stand as they were, those of a count taken as exact (they had calibration 1.0).
MODEL = dict(count=LAMBDA, controls=[[1e12 - 1, 1e12]], recovery=RECOVERY, why='made up')


def sandbox():
    d = tempfile.mkdtemp(prefix='sweep-eta-quals-')
    os.mkdir(os.path.join(d, 'searchwatch')); os.mkdir(os.path.join(d, 'runs'))
    for name in ('track.py', 'sweep_eta.py'): shutil.copy(os.path.join(HERE, 'searchwatch', name), os.path.join(d, 'searchwatch'))
    return d


def chunk(digest, K, count, first, last, nodes, time, cpu=1.0):
    return dict(digest=digest, K=K, count=count, total=1.0, first=first, last=last, nodes=nodes, capped=0, mass=0.01, cpu_s=cpu, time=time, found=[])


def lay(d, logs, curves, found=(), model=MODEL, plan=(), name='p{}'.format):
    """Makes d's sweep directory anew: the logs (pI.jsonl), their curves (pI.curve.json) and the found file; and a record with its start line.  Returns the estimator's arguments and the record's path.  (name, 2026-11-28: the I-th list's name, for recorded lists, which have names of their own; a change of the harness alone.)"""
    sweep = os.path.join(d, 'sweep')
    shutil.rmtree(sweep, ignore_errors=True); os.mkdir(sweep)
    args = [sweep]
    with open(os.path.join(sweep, 'model.json'), 'w') as f: json.dump(model, f)
    with open(os.path.join(sweep, 'found.jsonl'), 'w') as f: f.write(''.join(json.dumps(x) + '\n' for x in found))
    with open(os.path.join(sweep, 'plan.jsonl'), 'w') as f: f.write(''.join(json.dumps(x) + '\n' for x in plan))   # the lists the sweep is to take (2026-11-28)
    for i, (rows, curve) in enumerate(zip(logs, curves)):
        log, cur = os.path.join(sweep, name(i) + '.jsonl'), os.path.join(sweep, name(i) + '.curve.json')
        with open(log, 'w') as f: f.write(''.join(json.dumps(x) + '\n' for x in rows))
        with open(cur, 'w') as f: json.dump(curve, f)
    rec = os.path.join(d, 'runs', 'job.jsonl')
    with open(rec, 'w') as f:
        f.write(json.dumps(dict(event='start', name='job', search='sweep', target='528:12', estimator='searchwatch/sweep_eta.py', command='job', cwd='/',
                                found=os.path.join(sweep, 'found.jsonl'), adopted=False, pid=1, tracker=1, time=1000.0)) + '\n')
    return args, rec


def estimates(d, args, rec):
    p = subprocess.run([PY, '-B', os.path.join('searchwatch', 'sweep_eta.py'), *args], cwd=d, env=dict(os.environ, TRACK_RECORD=rec, PYTHONPATH='searchwatch'),
                       capture_output=True, text=True, timeout=60)
    return p, [x for x in (json.loads(s) for s in open(rec)) if x['event'] == 'estimate']


def close(a, b, tol=1e-9): return abs(a - b) <= tol * max(1.0, abs(a), abs(b))


def to_come(cost, mid, done, count, b):
    """The nodes of the cosets done to count - 1, when a coset at position i costs cost (i / mid)^-b."""
    return cost * mid ** b * (count ** (1 - b) - done ** (1 - b)) / (1 - b)


# Two profiles' logs.  The first has swept 1,000 of 4,000 cosets in four chunks ending at times 1010, 1030, 1070, 1150; the
# second 500 of 1,000 in two chunks ending at 1020 and 1060.  The latest tenth of a log's swept cosets is its last chunk here.
A = [chunk('aa', 4000, 4000, 0, 249, 8000, 1010.0, cpu=9.0), chunk('aa', 4000, 4000, 250, 499, 6000, 1030.0),
     chunk('aa', 4000, 4000, 500, 749, 5000, 1070.0), chunk('aa', 4000, 4000, 750, 999, 4000, 1150.0)]
B = [chunk('bb', 1000, 1000, 0, 249, 3000, 1020.0, cpu=5.0), chunk('bb', 1000, 1000, 250, 499, 2000, 1060.0)]
# cost (2026-11-28, night): what the planner expects the list's first k cosets to take, in nodes, as the curve is its
# expected witnesses; [] of a list the planner has no price for, which is then forecast as before that night.
CA = dict(digest='aa', K=4000, W=190, floor=4, curve=[[500, 0.10], [1000, 0.16], [4000, 0.30]], cost=[])
CB = dict(digest='bb', K=1000, W=190, floor=4, curve=[[250, 0.02], [500, 0.03], [1000, 0.04]], cost=[])
# What a time to go is multiplied by.  2026-11-28, afternoon: 0.9, 1.15, 1.55, measured with the speed as the middle chunk's
# (q_the_wait_between_two_runs_of_a_list_is_no_chunk_s_time): 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, a tenth over 1.54.  (That morning 0.8, 1.0, 1.7, from 43
# lists, the speed then the latest chunks' seconds summed over their nodes; a spec change with the estimator's.)
SPEED = dict(lo=0.9, median=1.15, hi=1.55)


def q_the_estimate_is_the_logs_work():
    # Replicata: the estimator on the two logs above, with 2.5 witnesses expected before the sweep and recovery 0.9.
    # Expectata: one estimate, in the record's form (track.checked): basis sweep, unit nodes; done the logs' nodes, 28,000;
    # finished the cosets swept, 1,500, and pending those left, 3,500.  A log's nodes to come: its latest chunks' nodes
    # a coset (16 and 8), taken as the cost at their middle position (875 and 375), falling as position^-b down the rest
    # of its list, with b 0.3 for the median and 0.4 and 0.2 for the band (measured at 528:12: 0.28 to 0.35).  total is
    # done plus both logs' nodes to come; to_go the longer of the two logs' times, nodes to come at the wall seconds a
    # node of its latest chunks (80 / 4000 and 40 / 2000); rate the nodes a second of those chunks together, 100.  prior
    # 1 - exp(-2.5); exists 1 - exp(-(2.5 - 0.9 (0.16 + 0.03))), the curves read at the cosets swept; and (2026-11-27;
    # dreeves: the chance that the search itself finds a witness "should also be shown on the page") finds
    # 1 - exp(-0.9 (0.30 + 0.04 - 0.19)), from the witnesses expected in the cosets the lists have left.
    d = sandbox()
    try:
        args, rec = lay(d, [A, B], [CA, CB])
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        e = ests[0]
        sys.path.insert(0, os.path.join(d, 'searchwatch'))
        import track
        track.checked(track.lines(rec))
        assert (e['basis'], e['unit'], e['done'], e['finished'], e['pending']) == ('sweep', 'nodes', 28000, 1500, 3500), e
        come = {b: (to_come(16.0, 875.0, 1000, 4000, b), to_come(8.0, 375.0, 500, 1000, b)) for b in (0.2, 0.3, 0.4)}
        for key, b in (('lo', 0.4), ('median', 0.3), ('hi', 0.2)):
            assert close(e['total'][key], 28000 + sum(come[b])), (key, e['total'], come[b])
            # (times SPEED since 2026-11-28: the band of a time to go holds the speed's spread too; a spec change with the estimator's)
            assert close(e['to_go'][key], SPEED[key] * max(come[b][0] * 80 / 4000, come[b][1] * 40 / 2000)), (key, e['to_go'], come[b])
        assert e['total']['lo'] < e['total']['median'] < e['total']['hi'] and close(e['rate'], 4000 / 80 + 2000 / 40), e
        assert close(e['prior'], 1 - math.exp(-2.5)) and close(e['exists'], 1 - math.exp(-(2.5 - 0.9 * 0.19))), e
        assert close(e['finds'], 1 - math.exp(-0.9 * (0.30 + 0.04 - 0.19))), e
    finally:
        shutil.rmtree(d)


def q_a_finished_sweep_has_nothing_to_go():
    # Replicata: one log that has swept all 500 of its 500 cosets; its curve ends at 0.5 expected witnesses.
    # Expectata: total is done at all three levels, to_go 0 at all three, pending 0, finished 500, rate its last chunk's
    # (2,000 nodes in 20 s: a record's rate is positive), and exists 1 - exp(-(2.5 - 0.9 * 0.5)), below the prior; the
    # record holds to its form (track.checked).
    d = sandbox()
    try:
        rows = [chunk('cc', 500, 500, 0, 249, 3000, 1010.0), chunk('cc', 500, 500, 250, 499, 2000, 1030.0)]
        args, rec = lay(d, [rows], [dict(digest='cc', K=500, W=190, floor=4, curve=[[250, 0.3], [500, 0.5]], cost=[])])
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:])
        e = ests[0]
        assert e['total'] == dict(median=5000, lo=5000, hi=5000) and e['to_go'] == dict(median=0, lo=0, hi=0), e
        assert (e['done'], e['pending'], e['finished'], e['rate']) == (5000, 0, 500, 100), e
        sys.path.insert(0, os.path.join(d, 'searchwatch'))
        import track
        track.checked(track.lines(rec))
        assert close(e['exists'], 1 - math.exp(-(2.5 - 0.45))) and e['exists'] < e['prior'], e
        assert e['finds'] == 0, e   # 2026-11-27: nothing is left in which to find one
    finally:
        shutil.rmtree(d)


def q_exists_falls_with_the_cosets_swept_and_is_1_at_a_witness():
    # Replicata: the first log above cut after one, two and four chunks, each a run of the estimator; then four chunks
    # with a line in the found file.
    # Expectata: exists falls from run to run while nothing is found (the curve read at 250, 500 and 1,000 cosets, the
    # first by a straight line from 0), every one below the prior; with a witness it is 1.
    d = sandbox()
    try:
        seen = []
        for n in (1, 2, 4):
            args, rec = lay(d, [A[:n]], [CA])
            p, ests = estimates(d, args, rec)
            assert p.returncode == 0 and len(ests) == 1, (n, p.stderr[-2000:])
            seen.append(ests[0])
        for e, c in zip(seen, (0.05, 0.10, 0.16)):
            assert close(e['exists'], 1 - math.exp(-(2.5 - 0.9 * c))) and e['exists'] < e['prior'], (e, c)
            assert close(e['finds'], 1 - math.exp(-0.9 * (0.30 - c))), (e, c)   # 2026-11-27: the list's 0.30, less what is swept
        assert seen[0]['exists'] > seen[1]['exists'] > seen[2]['exists'] and seen[0]['finds'] > seen[1]['finds'] > seen[2]['finds']
        args, rec = lay(d, [A], [CA], found=[dict(code='0F', order=12)])
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and ests[0]['exists'] == 1 and ests[0]['finds'] == 1 and close(ests[0]['prior'], 1 - math.exp(-2.5)), (p.stderr[-2000:], ests)
    finally:
        shutil.rmtree(d)


def q_the_sweep_is_its_directory_s_lists():
    # Replicata: the directory with the first log and its curve alone; then with the second list's too; then with a
    # third list's log that has no curve yet (a sweep just started).
    # Expectata: the estimator takes no list by name: a list is a curve X.curve.json with its log X.jsonl.  The
    # first estimate is of the one list (1,000 cosets finished), the second of both (1,500), and the third is the
    # second again: a log is counted from the moment its curve is there.
    d = sandbox()
    try:
        args, rec = lay(d, [A], [CA])
        _, one = estimates(d, args, rec)
        args, rec = lay(d, [A, B], [CA, CB])
        _, two = estimates(d, args, rec)
        with open(os.path.join(args[0], 'p2.jsonl'), 'w') as f: f.write(json.dumps(chunk('dd', 500, 500, 0, 249, 900, 1015.0)) + '\n')
        p, three = estimates(d, args, rec)
        assert p.returncode == 0 and [len(x) for x in (one, two, three)] == [1, 1, 2], (p.stderr[-2000:], one, two, three)
        assert (one[0]['finished'], two[0]['finished'], three[1]['finished']) == (1000, 1500, 1500)
        assert {k: v for k, v in three[1].items() if k != 'time'} == {k: v for k, v in two[0].items() if k != 'time'}
    finally:
        shutil.rmtree(d)


def q_the_model_is_the_directory_s_and_its_calibration_scales_every_count():
    # Replicata: the two logs of the first qual, with a model.json of count 2.5, recovery 0.9 and calibration 0.8 (a
    # control's witnesses found over those the count model predicted); then with a model.json that lacks its
    # calibration, and with one that has a field more.
    # (2026-11-28, night; a spec change with the estimator's: the model states its controls, each [found, predicted], in
    # place of their quotient, so that the count is as sure as they make it: q_the_count_is_as_sure_as_its_controls.
    # Here one control of 0.8 million million found where a million million were predicted, which leaves no doubt of
    # the 0.8; the numbers below stand.  A model with no control, or with a control that predicted nothing, stops the
    # estimator too.)
    # Expectata (dreeves, 2026-11-27, asked whether the box should use the count as calibrated on the one cell where it
    # could be counted: "can-opener question"): the model is a file of the sweep's directory, read at every estimate,
    # so that a revised model needs no relaunch; every count of the model is taken at 0.8 of its value: prior
    # 1 - exp(-0.8 * 2.5), exists 1 - exp(-0.8 (2.5 - 0.9 * 0.19)), finds 1 - exp(-0.8 * 0.9 (0.34 - 0.19)); the work
    # and the time to go are as with any calibration.  A model.json without a field, or with one more, stops the
    # estimator, which then appends nothing.
    # Resultata before: the count and the recovery were arguments of each launch, so the ten runs already going kept
    # the count they were started with.
    d = sandbox()
    try:
        args, rec = lay(d, [A, B], [CA, CB])
        _, plain = estimates(d, args, rec)
        args, rec = lay(d, [A, B], [CA, CB], model=dict(MODEL, controls=[[8e11 - 1, 1e12]]))
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:])
        e = ests[0]
        assert close(e['prior'], 1 - math.exp(-0.8 * 2.5)) and close(e['exists'], 1 - math.exp(-0.8 * (2.5 - 0.9 * 0.19))), e
        assert close(e['finds'], 1 - math.exp(-0.8 * 0.9 * (0.34 - 0.19))), e
        assert all(e[k] == plain[0][k] for k in ('done', 'total', 'to_go', 'rate', 'pending', 'finished')), (e, plain[0])
        for model in ({k: v for k, v in MODEL.items() if k != 'controls'}, dict(MODEL, more=1), dict(MODEL, controls=[]), dict(MODEL, controls=[[3, 0]]), dict(MODEL, controls=[[-2, 4]])):
            args, rec = lay(d, [A, B], [CA, CB], model=model)
            p, ests = estimates(d, args, rec)
            assert p.returncode != 0 and not ests, (model, p.returncode, ests)
    finally:
        shutil.rmtree(d)


def q_a_list_swept_in_part_counts_its_part():
    # Replicata: the estimator on a list of 4,000 cosets of which the sweep takes the first 1,000 (its log's count),
    # 500 of them swept; the list's curve, to its 4,000.
    # Expectata (Fable 5.2, 2026-11-27, for lists at width 210, long ones swept a part at a time: sweep.py's "a larger
    # COUNT extends it"): the sweep is the part it takes.  pending the cosets left of the part, 500; finds
    # 1 - exp(-0.9 (0.16 - 0.10)), the witnesses expected in the part's cosets not yet swept, the curve read at the
    # count; exists as for any list, 1 - exp(-(2.5 - 0.9 0.10)).
    # Resultata before: finds counted the whole list's witnesses, 1 - exp(-0.9 (0.30 - 0.10)), which the sweep would
    # never reach.
    d = sandbox()
    try:
        part = [chunk('aa', 4000, 1000, 0, 249, 8000, 1010.0, cpu=9.0), chunk('aa', 4000, 1000, 250, 499, 6000, 1030.0)]
        args, rec = lay(d, [part], [CA])
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        e = ests[0]
        assert (e['finished'], e['pending']) == (500, 500), e
        assert close(e['finds'], 1 - math.exp(-0.9 * (0.16 - 0.10))), e
        assert close(e['exists'], 1 - math.exp(-(2.5 - 0.9 * 0.10))), e
    finally:
        shutil.rmtree(d)


# A list of 1,000 cosets swept whole, 10,000 nodes, its last chunk at time 960; and a list of 100,000 swept whole in two
# chunks, a million nodes.
F = [chunk('ff', 1000, 1000, 0, 249, 4000, 900.0, cpu=5.0), chunk('ff', 1000, 1000, 250, 499, 3000, 920.0),
     chunk('ff', 1000, 1000, 500, 749, 2000, 940.0), chunk('ff', 1000, 1000, 750, 999, 1000, 960.0)]
CF = dict(digest='ff', K=1000, W=190, floor=4, curve=[[500, 0.02], [1000, 0.03]], cost=[])
G = [chunk('gg', 100000, 100000, 0, 49999, 600000, 900.0, cpu=50.0), chunk('gg', 100000, 100000, 50000, 99999, 400000, 950.0)]
CG = dict(digest='gg', K=100000, W=190, floor=4, curve=[[50000, 0.2], [100000, 0.3]], cost=[])
# credit (2026-11-28, morning): what the list's pass would add, in a curve's units.  nodes (that afternoon): what the planner
# expects the list to take, its price; 0 where it states none, and the list then counts by its kind.
LIST = dict(W=190, floor=4, count=1000, credit=0.05, nodes=0)
PRICED = dict(lo=0.9, median=1.05, hi=1.2)   # what a price is multiplied by: of 132 lists priced so, a tenth took under 0.91 of it and a tenth over 1.18


def blend(price, swept, done, key):
    """The nodes to come of a list priced at price, the cosets swept priced at swept and done in done nodes, at the level key
    (2026-11-28, night): the price of the cosets left, times the list's ratio of nodes to price, taken from a prior worth
    KAPPA of the list at PRICED and from the cosets swept at SHAPED.  KAPPA and SHAPED are read from the estimator: this
    suite holds the forecast's form, and the recorded stage's quals what its constants come to."""
    k, shaped = sweep_eta.KAPPA, dict(zip(('lo', 'median', 'hi'), sweep_eta.SHAPED))
    return (price - swept) * (k * price * PRICED[key] + done * shaped[key]) / (k * price + swept)


def q_planned_lists_count_before_they_start():
    # Replicata: a sweep directory with the finished list F, the second log above (500 of its 1,000 cosets swept) and a
    # plan that names those two and two more lists of their kind (width 190, floor 4, 1,000 cosets) with no curve yet.
    # Expectata (dreeves, 2026-11-28, of the sweep's ETA chart, whose time to go had jumped at every list a launcher
    # started: "these ETAs sure don't look calibrated"): the sweep is its plan.  A planned list not yet begun takes
    # what the finished lists of its kind took, 10,000 nodes: total is the nodes done, the running list's to come and
    # 20,000; pending the running list's 500 cosets and the two lists' 2,000.  The time to go is the nodes to come over
    # the nodes a second of the lists running (one, 2,000 nodes in 40 s), since the planned lists wait for them, or
    # the running list's own time where that is longer; times SPEED.  rate is the running list's, 50: a finished list
    # adds none.
    # Resultata before: the estimator read the lists begun alone, so the two planned lists added nothing until each
    # began, and rate summed every list's last, the finished one's too.
    d = sandbox()
    try:
        plan = [dict(LIST, name='p0'), dict(LIST, name='p1'), dict(LIST, name='q0'), dict(LIST, name='q1')]
        args, rec = lay(d, [F, B], [CF, CB], plan=plan)
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        e = ests[0]
        assert (e['done'], e['finished'], e['pending'], e['rate']) == (15000, 1500, 2500, 50), e
        for key, b in (('lo', 0.4), ('median', 0.3), ('hi', 0.2)):
            mine = to_come(8.0, 375.0, 500, 1000, b)
            assert close(e['total'][key], 15000 + mine + 20000), (key, e['total'], mine)
            assert close(e['to_go'][key], SPEED[key] * max(mine * 40 / 2000, (mine + 20000) / 50)), (key, e['to_go'], mine)
        sys.path.insert(0, os.path.join(d, 'searchwatch'))
        import track
        track.checked(track.lines(rec))
    finally:
        shutil.rmtree(d)


def q_a_planned_list_s_credit_counts_in_finds():
    # Replicata: the directory of the qual above (the finished list F, the list B with 500 of its 1,000 cosets swept,
    # and a plan naming those two and two more lists with no curve yet), each planned list stating its credit, 0.05:
    # the expected witnesses its pass would add, in a curve's units.
    # Expectata (dreeves, 2026-11-27: "if the chance that the current search, the thing we're showing the ETA for,
    # finds a witness is very different from that then that should also be shown on the page"; Fable 5.2, 2026-11-28:
    # a stage of 96 lists whose launcher starts them a few at a time read 2% on the page where the stage held 13%):
    # finds is the chance in everything the sweep is yet to take, 1 - exp(-0.9 (0.01 + 0.05 + 0.05)): B's cosets left
    # and the two planned lists.  exists is of what is swept, as before: 1 - exp(-(2.5 - 0.9 0.06)).
    # Resultata before: 1 - exp(-0.9 0.01), the lists begun alone; a planned list's chance joined as it began.
    d = sandbox()
    try:
        plan = [dict(LIST, name='p0'), dict(LIST, name='p1'), dict(LIST, name='q0'), dict(LIST, name='q1')]
        args, rec = lay(d, [F, B], [CF, CB], plan=plan)
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        e = ests[0]
        assert close(e['finds'], 1 - math.exp(-0.9 * (0.01 + 0.05 + 0.05))), e
        assert close(e['exists'], 1 - math.exp(-(2.5 - 0.9 * 0.06))), e
        args, rec = lay(d, [F, B], [CF, CB], plan=[dict(x, credit=0.0) for x in plan])       # control: lists that add nothing
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and close(ests[0]['finds'], 1 - math.exp(-0.9 * 0.01)), (p.stderr[-2000:], ests)
    finally:
        shutil.rmtree(d)


def q_a_plan_that_asks_more_of_a_list_begun_counts_before_the_sweep_takes_it_up():
    # Replicata: the estimator on a list of 4,000 cosets whose log says the sweep takes the first 1,000 and has swept
    # them all (the list of q_a_list_swept_in_part_counts_its_part, done), with a plan whose line for that list asks
    # for 2,000: the next stage extends the list (sweep.py: "a larger COUNT extends it"), and no chunk of the
    # extension is written yet.
    # Expectata (Fable 5.2, 2026-11-28, for stages that take lists further: a list extended as its launcher got to it
    # would move the time to go at each start, the fault dreeves named in the ETA chart of 2026-11-28): a list's count
    # is its plan's where the plan asks for more than its log.  pending the 1,000 cosets asked for and not swept;
    # finds 1 - exp(-0.9 (0.2067 - 0.16)), the curve read at 2,000 less what is swept (0.16 at 1,000; the curve runs
    # straight from 0.16 at 1,000 to 0.30 at 4,000); exists of what is swept, 1 - exp(-(2.5 - 0.9 0.16)); and nodes to
    # come, where a finished list has none.
    # Resultata before: the plan's line was read only of lists not begun: pending 0, finds 0, nothing to go.
    d = sandbox()
    try:
        part = [chunk('aa', 4000, 1000, 0, 249, 8000, 1010.0, cpu=9.0), chunk('aa', 4000, 1000, 250, 499, 6000, 1030.0),
                chunk('aa', 4000, 1000, 500, 749, 5000, 1050.0), chunk('aa', 4000, 1000, 750, 999, 4000, 1070.0)]
        args, rec = lay(d, [part], [CA], plan=[dict(name='p0', W=190, floor=4, count=2000, credit=0.2, nodes=0)])
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        e = ests[0]
        assert (e['finished'], e['pending']) == (1000, 1000), e
        assert close(e['finds'], 1 - math.exp(-0.9 * (0.16 + 0.14 / 3 - 0.16))), e
        assert close(e['exists'], 1 - math.exp(-(2.5 - 0.9 * 0.16))), e
        assert e['total']['lo'] > e['done'] and e['to_go']['lo'] > 0, e
        args, rec = lay(d, [part], [CA], plan=[dict(name='p0', W=190, floor=4, count=500, credit=0.1, nodes=0)])     # control: a plan that asks for less than the log's count changes nothing
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and (ests[0]['pending'], ests[0]['finds']) == (0, 0), (p.stderr[-2000:], ests)
    finally:
        shutil.rmtree(d)


def q_a_list_just_begun_is_forecast_by_its_kind():
    # Replicata: the finished list G (100,000 cosets, a million nodes) and a list of its kind with 500 cosets swept,
    # 80,000 nodes, its top cosets the dearest; then that list alone.
    # Expectata (2026-11-28): a list under a fiftieth swept says little of its own cost (a width-220 list's forecast
    # from its first 4,500 cosets was 2.3 times what its positions measured before gave), so beside a finished list of
    # its kind it is forecast by that one: a million nodes in all, 920,000 to come at all three levels.  Alone, it is
    # forecast by its own cost as any list, the three levels apart.
    # Resultata before: its own cost alone, which puts 2.1 to 4.9 million nodes on it here.
    d = sandbox()
    try:
        J = [chunk('jj', 100000, 100000, 0, 249, 50000, 1100.0, cpu=5.0), chunk('jj', 100000, 100000, 250, 499, 30000, 1120.0)]
        CJ = dict(digest='jj', K=100000, W=190, floor=4, curve=[[50000, 0.2], [100000, 0.3]], cost=[])
        args, rec = lay(d, [G, J], [CG, CJ])
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        e = ests[0]
        assert all(close(e['total'][key], 1000000 + 1000000) for key in ('lo', 'median', 'hi')) and e['pending'] == 99500, e
        assert all(close(e['to_go'][key], SPEED[key] * 920000 * 20 / 30000) for key in ('lo', 'median', 'hi')), e
        args, rec = lay(d, [J], [CJ])
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        alone = ests[0]
        assert 2e6 < alone['total']['lo'] < alone['total']['median'] < alone['total']['hi'], alone
    finally:
        shutil.rmtree(d)


def q_a_kind_is_measured_by_its_latest_lists():
    # Replicata: seven finished lists of one kind, two that took 10,000 nodes and ended first, then five that took 2,000
    # each; the running second log above; and a plan with one more list of the kind.
    # Expectata (2026-11-28): lists run in the order of their profiles' ranks and a later rank's list is cheaper (at
    # 528:12, 3.5e11 nodes at rank 0 and 3e10 at rank 30), so the planned list takes what the five latest to end took,
    # 2,000 nodes, not the 10,000 of the first two.
    d = sandbox()
    try:
        ended = lambda i, nodes, t: [chunk(f'e{i}', 1000, 1000, 0, 999, nodes, t, cpu=5.0)]
        logs = [ended(i, 10000, 100.0 + i) for i in range(2)] + [ended(i, 2000, 200.0 + i) for i in range(2, 7)] + [B]
        curves = [dict(CF, digest=f'e{i}') for i in range(7)] + [CB]
        args, rec = lay(d, logs, curves, plan=[dict(LIST, name=f'p{i}') for i in range(8)] + [dict(LIST, name='q0')])
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        e = ests[0]
        done = 2 * 10000 + 5 * 2000 + 5000
        assert e['done'] == done and close(e['total']['median'], done + to_come(8.0, 375.0, 500, 1000, 0.3) + 2000), e
    finally:
        shutil.rmtree(d)


def q_a_cut_list_is_no_measure_of_its_kind():
    # Replicata: the list F cut after 500 of its 1,000 cosets (its last line's count 500, was 1,000), the running
    # second log above, and a plan with one more list of 1,000 cosets.
    # Expectata (2026-11-28): the cut list is done (nothing pending for it) but is no whole list of the planned one's
    # kind, so the planned list takes what the running list of its kind is forecast to take in all, by its own cost
    # at the median: 5,000 and its nodes to come.
    # Resultata before: no planned list counted at all.
    d = sandbox()
    try:
        cut = F[:1] + [dict(F[1], count=500, was=1000)]
        args, rec = lay(d, [cut, B], [CF, CB], plan=[dict(LIST, name='p0'), dict(LIST, name='p1'), dict(LIST, name='q0')])
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        e = ests[0]
        whole = 5000 + to_come(8.0, 375.0, 500, 1000, 0.3)
        assert (e['done'], e['pending'], e['rate']) == (12000, 1500, 50), e
        for key, b in (('lo', 0.4), ('median', 0.3), ('hi', 0.2)):
            assert close(e['total'][key], 12000 + to_come(8.0, 375.0, 500, 1000, b) + whole), (key, e['total'], whole)
    finally:
        shutil.rmtree(d)


def q_the_wait_between_two_runs_of_a_list_is_no_chunk_s_time():
    # Replicata: a list of 100,000 cosets of which a first run swept 5,000, a chunk of 250 cosets and 2,000 nodes
    # every 20 seconds; three hours after that run's last chunk a second run, asked for 10,000, has written its first
    # chunk (250 cosets, 2,000 nodes).  Then the same log with that chunk 20 seconds after the one before it.
    # Expectata (Fable 5.2, 2026-11-28, as a stage that takes 119 lists further began and the page's time to go read
    # 588 hours): a chunk's wall seconds run from the chunk before it, so that one chunk holds the wait between the
    # two runs; the list's speed is its chunks', 100 nodes a second, and the estimate is the one of the log without
    # the wait: rate 100, and a time to go of the nodes to come (the latest tenth of the swept cosets is three chunks:
    # 8 nodes a coset at position 4,875) at 0.01 seconds a node, times SPEED.
    # Resultata before: the wait was summed into the latest chunks' seconds (20, 20 and 10,820 over 6,000 nodes), so
    # rate read 0.55 and the time to go 181 times the list's own.
    d = sandbox()
    try:
        first = [chunk('hh', 100000, 5000, 250 * i, 250 * i + 249, 2000, 1000.0 + 20 * i) for i in range(20)]
        again = lambda wait: first + [chunk('hh', 100000, 10000, 5000, 5249, 2000, first[-1]['time'] + wait)]
        CH = dict(digest='hh', K=100000, W=190, floor=4, curve=[[50000, 0.2], [100000, 0.3]], cost=[])
        seen = []
        for wait in (3 * 3600 + 20, 20):
            args, rec = lay(d, [again(wait)], [CH])
            p, ests = estimates(d, args, rec)
            assert p.returncode == 0 and len(ests) == 1, (wait, p.returncode, p.stderr[-2000:], ests)
            seen.append({k: v for k, v in ests[0].items() if k != 'time'})
        e = seen[0]
        assert close(e['rate'], 100) and (e['finished'], e['pending']) == (5250, 4750), e
        for key, b in (('lo', 0.4), ('median', 0.3), ('hi', 0.2)):
            assert close(e['to_go'][key], SPEED[key] * to_come(8.0, 4875.0, 5250, 10000, b) * 0.01), (key, e['to_go'])
        assert seen[0] == seen[1], seen
    finally:
        shutil.rmtree(d)


def q_a_plan_s_price_counts_where_no_list_measures_the_kind():
    # Replicata: the finished list F (width 190, floor 4; 10,000 nodes), the running list B, and a plan naming those
    # two and a list of a kind the directory has none of (width 220, floor 4, 4,000 cosets), not begun, whose line
    # states its price, 50,000 nodes; then the same with the price 0; then with a list of such a kind begun, 500 of
    # its 100,000 cosets swept in 80,000 nodes, priced at 600,000.
    # Expectata (Fable 5.2, 2026-11-28, before a stage of four width-220 lists at floor 4, each 5e12 to 9e12 nodes by
    # floor 3's nodes on the same cosets times the measured ratio of the floors): the plan states what its planner
    # expects a list to take (nodes, as it states credit), and a list not begun, or begun with under a fiftieth of
    # its cosets swept, counts at that price, at PRICED's band: the nodes to come are B's and 0.9, 1.05 and 1.2 times
    # 50,000; begun, the same of 600,000 less the 80,000 done.  With the price 0 the list counts by its kind, as
    # before: here by the finished list of another kind, 10,000 at all three levels.
    # (2026-11-28, night; a spec change with the estimator's, at dreeves's "that sounds like a can-opener question" of
    # the cost by position: a list begun is forecast by its curve's cost, the plan's price drawn towards the list's own
    # ratio of nodes to cost, from its first chunk: q_a_priced_list_is_forecast_by_its_price_and_its_ratio_so_far.  The
    # list begun here states the cost 600,000 with 60,000 for its first 500 cosets, which took 80,000.)
    # Resultata before: the kind alone: 10,000 nodes for the list not begun, and nothing to come for the one begun
    # (10,000 less its 80,000 done) until a fiftieth of it was swept, when its own cost took over and the time to go
    # jumped: the fault dreeves named in the ETA chart of 2026-11-28.
    d = sandbox()
    try:
        new = dict(name='q0', W=220, floor=4, count=4000, credit=0.05, nodes=50000)
        mine = lambda b: to_come(8.0, 375.0, 500, 1000, b)
        args, rec = lay(d, [F, B], [CF, CB], plan=[dict(LIST, name='p0'), dict(LIST, name='p1'), new])
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        e = ests[0]
        assert (e['done'], e['pending']) == (15000, 4500), e
        for key, b in (('lo', 0.4), ('median', 0.3), ('hi', 0.2)):
            assert close(e['total'][key], 15000 + mine(b) + PRICED[key] * 50000), (key, e['total'], mine(b))
        args, rec = lay(d, [F, B], [CF, CB], plan=[dict(LIST, name='p0'), dict(LIST, name='p1'), dict(new, nodes=0)])    # control: no price
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and all(close(ests[0]['total'][key], 15000 + mine(b) + 10000) for key, b in (('lo', 0.4), ('median', 0.3), ('hi', 0.2))), (p.stderr[-2000:], ests)
        J = [chunk('jj', 100000, 100000, 0, 249, 50000, 1100.0, cpu=5.0), chunk('jj', 100000, 100000, 250, 499, 30000, 1120.0)]
        CJ = dict(digest='jj', K=100000, W=220, floor=4, curve=[[50000, 0.2], [100000, 0.3]], cost=[[500, 60000], [100000, 600000]])
        args, rec = lay(d, [F, B, J], [CF, CB, CJ], plan=[dict(LIST, name='p0'), dict(LIST, name='p1'), dict(name='p2', W=220, floor=4, count=100000, credit=0.3, nodes=600000)])
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        e = ests[0]
        assert (e['done'], e['pending']) == (95000, 100000), e
        for key, b in (('lo', 0.4), ('median', 0.3), ('hi', 0.2)):
            assert close(e['total'][key], 95000 + mine(b) + blend(600000, 60000, 80000, key)), (key, e['total'], mine(b))
    finally:
        shutil.rmtree(d)


# 2026-11-28, evening (dreeves: "always add as many new quals as possible (except stupid wolf-crying ones that, eg, pin
# specific wording)").  The quals from here to the recorded stage's hold what the estimator did already, but for the two
# with a Resultata before; each was seen red on a copy of the estimator with that behavior changed
# (scratch/quals-20261128/NOTES.md).


def q_a_priced_list_is_forecast_by_its_price_and_its_ratio_so_far():
    # Replicata: the finished list F, the running list B and a plan naming them and a third list (width 220, floor 4,
    # 100,000 cosets, credit 0.3) priced at 600,000 nodes; then the same once that list has begun, 500 of its cosets
    # swept in 80,000 nodes, its curve stating its cost: 60,000 nodes for its first 500 cosets, 420,000 for its first
    # 50,000, 600,000 for all; then with 50,000 of its cosets swept, in 400,000 nodes.
    # Expectata (2026-11-28, night; dreeves, of the cost by position: "that sounds like a can-opener question"): a
    # priced list's nodes to come are the price of its cosets left, times its ratio of nodes to price; the ratio is
    # the plan's (PRICED: 0.9, 1.05, 1.2) for a prior worth a tenth of the list (KAPPA) and the list's own so far (at
    # SHAPED, what the rest took over that forecast: 0.9, 0.97, 1.05) for the cosets swept:
    #     (P - p) (KAPPA P PRICED + d SHAPED) / (KAPPA P + p),   P the price, p the swept cosets' price, d their nodes.
    # Not begun that is PRICED times its price.  Begun, it holds from the first chunk, with no wait for a fiftieth of
    # the list: 540,000 of price left at (60,000 PRICED + 80,000 SHAPED) / 120,000.  Half swept the list's own ratio
    # has nearly all the weight: 180,000 left at (60,000 PRICED + 400,000 SHAPED) / 480,000.  The cosets pending and
    # finished add up to the same 102,000 before and after the list's start, and finds falls by the witnesses expected
    # in its 500 cosets alone, 0.002.
    # Resultata before: past a fiftieth swept a list was forecast by its latest chunks' cost falling as position^-b,
    # which on 132 lists read 0.87 to 2.07 of what the rest took at a twentieth swept (the blend: 0.93 to 1.04) and
    # put the page's time to go a third high on 2026-11-28; under a fiftieth, by its price less its nodes done.
    d = sandbox()
    try:
        J = [chunk('jj', 100000, 100000, 0, 249, 50000, 1100.0, cpu=5.0), chunk('jj', 100000, 100000, 250, 499, 30000, 1120.0)]
        J2 = [chunk('jj', 100000, 100000, 0, 24999, 250000, 1100.0, cpu=5.0), chunk('jj', 100000, 100000, 25000, 49999, 150000, 1120.0)]
        CJ = dict(digest='jj', K=100000, W=220, floor=4, curve=[[50000, 0.2], [100000, 0.3]], cost=[[500, 60000], [50000, 420000], [100000, 600000]])
        plan = [dict(LIST, name='p0'), dict(LIST, name='p1'), dict(name='p2', W=220, floor=4, count=100000, credit=0.3, nodes=600000)]
        mine = lambda b: to_come(8.0, 375.0, 500, 1000, b)
        seen = []
        for logs, curves in (([F, B], [CF, CB]), ([F, B, J], [CF, CB, CJ]), ([F, B, J2], [CF, CB, CJ])):
            args, rec = lay(d, logs, curves, plan=plan)
            p, ests = estimates(d, args, rec)
            assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
            seen.append(ests[0])
        before, after, half = seen
        for key, b in (('lo', 0.4), ('median', 0.3), ('hi', 0.2)):
            assert close(before['total'][key], 15000 + mine(b) + PRICED[key] * 600000), (key, before['total'])
            assert close(after['total'][key], 95000 + mine(b) + blend(600000, 60000, 80000, key)), (key, after['total'])
            assert close(half['total'][key], 415000 + mine(b) + blend(600000, 420000, 400000, key)), (key, half['total'])
        assert before['pending'] + before['finished'] == after['pending'] + after['finished'] == 102000, (before, after)
        assert close(before['finds'], 1 - math.exp(-0.9 * (0.01 + 0.3))) and close(after['finds'], 1 - math.exp(-0.9 * (0.01 + 0.3 - 0.002))), (before, after)
    finally:
        shutil.rmtree(d)


def q_a_cost_that_is_not_the_list_s_stops_it():
    # Replicata: the directory of the qual above with the third list begun, its curve's cost ending before the list
    # does; then falling from one position to a later one; then the curve stating no cost at all (the field left out).
    # Expectata: each time the estimator fails and appends nothing: a cost that does not run to the list's last coset,
    # or that falls, is not a list's, and a curve says where it has none (cost: []).
    d = sandbox()
    try:
        J = [chunk('jj', 100000, 100000, 0, 249, 50000, 1100.0, cpu=5.0), chunk('jj', 100000, 100000, 250, 499, 30000, 1120.0)]
        CJ = dict(digest='jj', K=100000, W=220, floor=4, curve=[[50000, 0.2], [100000, 0.3]], cost=[[500, 60000], [100000, 600000]])
        plan = [dict(LIST, name='p0'), dict(LIST, name='p1'), dict(name='p2', W=220, floor=4, count=100000, credit=0.3, nodes=600000)]
        args, rec = lay(d, [F, B, J], [CF, CB, CJ], plan=plan)
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        for curve in (dict(CJ, cost=[[500, 60000], [50000, 420000]]), dict(CJ, cost=[[500, 60000], [100000, 50000]]), {k: v for k, v in CJ.items() if k != 'cost'}):
            args, rec = lay(d, [F, B, J], [CF, CB, curve], plan=plan)
            p, ests = estimates(d, args, rec)
            assert p.returncode != 0 and not ests, (curve, p.returncode, ests)
    finally:
        shutil.rmtree(d)


def q_the_count_is_as_sure_as_its_controls():
    # Replicata: the two logs of the first qual (the curves hold 0.19 expected witnesses in the cosets swept and 0.34
    # in those the lists take), the count 2.5, recovery 0.9, and a model whose one control found 3 cosets with a
    # witness where the count model predicted 4; then with a second control, 9 found where 2 were predicted.
    # Expectata (dreeves, 2026-11-28, of the box's probabilities, which had fallen to 0.53 and been put back to 0.82 by
    # a revised model: "it's the epitome of 'fool me once, shame on you, fool me twice, shame on me'"): the count is
    # the model's, and the model is as good as its record.  The true count is the model's times q, and a control that
    # found x where p were predicted says of q what x + 1 draws at rate p say (a flat prior): then no witness among s
    # of the count's expected ones has chance keep(s) = (p / (p + s))^(x + 1), and over several controls, each as
    # likely to be the cell's case as another, the mean of that.  With M the count, S what the sweep would have found
    # by now (0.9 x 0.19) and T what it will have at its plan's end (0.9 x 0.34):
    #     prior 1 - keep(M),   exists 1 - keep(M) / keep(S),   finds 1 - keep(T) / keep(S).
    # One control: keep(s) = (4 / (4 + s))^4.  Two: the mean of that and (2 / (2 + s))^10.
    # Resultata before: the count times one calibration, taken as exact: 1 - exp(-0.75 (2.5 - 0.171)) and so on,
    # whatever the control's size.
    d = sandbox()
    try:
        S, T, M = 0.9 * 0.19, 0.9 * 0.34, 2.5
        for controls, keep in (([[3, 4]], lambda s: (4 / (4 + s)) ** 4), ([[3, 4], [9, 2]], lambda s: ((4 / (4 + s)) ** 4 + (2 / (2 + s)) ** 10) / 2)):
            args, rec = lay(d, [A, B], [CA, CB], model=dict(MODEL, controls=controls))
            p, ests = estimates(d, args, rec)
            assert p.returncode == 0 and len(ests) == 1, (controls, p.returncode, p.stderr[-2000:], ests)
            e = ests[0]
            assert close(e['prior'], 1 - keep(M)) and close(e['exists'], 1 - keep(M) / keep(S)) and close(e['finds'], 1 - keep(T) / keep(S)), (controls, e)
            assert e['finds'] < e['exists'] < e['prior'], (controls, e)
    finally:
        shutil.rmtree(d)


def q_a_sweep_that_finds_nothing_believes_its_count_less():
    # Replicata: a list with 500 of its 4,000 cosets swept, twice: once with a curve that holds 0.10 expected
    # witnesses in the cosets swept and 0.30 in all, once with one that holds 0.50 and 0.70, so that the cosets left
    # hold the same 0.20 either way.  Each under a model whose control found 3 where 4 were predicted, and under the
    # model that leaves no doubt of its count.
    # Expectata: where the count is in doubt, what a sweep has failed to find lowers what it expects of the cosets
    # left: finds is 1 - ((4 + S) / (4 + S + 0.18))^4 with S 0.09 and 0.45, so less after the larger failure, and the
    # chance that a witness exists is less by more than the cosets swept alone would take from it.  With no doubt of
    # the count, finds is 1 - exp(-0.18) both times: the sweep learns nothing of its model, which is what the page
    # showed until 2026-11-28 (a chance that fell and was then put back by a revision).
    d = sandbox()
    try:
        rows = A[:2]
        little, much = dict(CA, curve=[[500, 0.10], [4000, 0.30]]), dict(CA, curve=[[500, 0.50], [4000, 0.70]])
        seen = {}
        for name, model in (('doubt', dict(MODEL, controls=[[3, 4]])), ('sure', MODEL)):
            for curve in (little, much):
                args, rec = lay(d, [rows], [curve], model=model)
                p, ests = estimates(d, args, rec)
                assert p.returncode == 0 and len(ests) == 1, (name, p.returncode, p.stderr[-2000:], ests)
                seen.setdefault(name, []).append(ests[0])
        for e, S in zip(seen['doubt'], (0.09, 0.45)):
            assert close(e['finds'], 1 - ((4 + S) / (4 + S + 0.18)) ** 4) and close(e['exists'], 1 - ((4 + S) / (4 + 2.5)) ** 4), (S, e)
        assert seen['doubt'][1]['finds'] < seen['doubt'][0]['finds'], seen['doubt']
        assert all(close(e['finds'], 1 - math.exp(-0.18)) for e in seen['sure']), seen['sure']
        assert seen['doubt'][0]['exists'] - seen['doubt'][1]['exists'] > seen['sure'][0]['exists'] - seen['sure'][1]['exists'] > 0, seen
    finally:
        shutil.rmtree(d)


def q_a_list_past_its_kind_s_measure_leaves_nothing_to_come():
    # Replicata: the finished list F (width 190, floor 4, 1,000 cosets: 10,000 nodes) and an unpriced list of its kind
    # just begun, 10 cosets swept in 15,000 nodes.
    # Expectata: under a fiftieth swept, the list is forecast by its kind, 10,000 nodes in all, less its nodes done:
    # it has taken more than that already, so it leaves nothing to come, never less than nothing: total is the nodes
    # done, 25,000, at all three levels (a total under the nodes done is no estimate: track.checked).
    d = sandbox()
    try:
        N = [chunk('nn', 1000, 1000, 0, 9, 15000, 1100.0, cpu=5.0)]
        args, rec = lay(d, [F, N], [CF, dict(CF, digest='nn')])
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        e = ests[0]
        assert (e['done'], e['pending']) == (25000, 990) and e['total'] == dict(lo=25000, median=25000, hi=25000), e
    finally:
        shutil.rmtree(d)


def q_a_list_no_run_is_sweeping_adds_work_and_no_rate():
    # Replicata: the two logs of the first qual, neither swept to its count, with the first list's chunks two hours
    # later, so that the second list's newest chunk is two hours behind the directory's newest (a list whose sweep has
    # stopped, or that waits to be taken up); then the two logs as they are, 90 seconds apart.
    # Expectata: a list is running if its newest chunk is within a quarter of an hour of the directory's newest.  The
    # stopped list's nodes to come are the sweep's work all the same (total: the nodes done and both lists' to come),
    # but it adds no nodes a second: rate is the first list's, 50, and the time to go all the nodes to come at that
    # rate, times SPEED.  Ninety seconds apart both run: rate 100.
    d = sandbox()
    try:
        come = {b: (to_come(16.0, 875.0, 1000, 4000, b), to_come(8.0, 375.0, 500, 1000, b)) for b in (0.2, 0.3, 0.4)}
        for later, rate in ((7200.0, 50), (0.0, 100)):
            args, rec = lay(d, [[dict(r, time=r['time'] + later) for r in A], B], [CA, CB])
            p, ests = estimates(d, args, rec)
            assert p.returncode == 0 and len(ests) == 1, (later, p.returncode, p.stderr[-2000:], ests)
            e = ests[0]
            assert close(e['rate'], rate), (later, e)
            for key, b in (('lo', 0.4), ('median', 0.3), ('hi', 0.2)):
                assert close(e['total'][key], 28000 + sum(come[b])), (later, key, e['total'], come[b])
                assert close(e['to_go'][key], SPEED[key] * max(come[b][0] * 0.02, come[b][1] * 0.02, sum(come[b]) / rate)), (later, key, e['to_go'], come[b])
    finally:
        shutil.rmtree(d)


# A list of 500 cosets with its first chunk alone: 250 cosets, 900 nodes, 30 CPU seconds.
D1 = [chunk('dd', 500, 500, 0, 249, 900, 1015.0, cpu=30.0)]
CD = dict(digest='dd', K=500, W=190, floor=4, curve=[[250, 0.01], [500, 0.015]], cost=[])


def q_the_clock_and_the_units_are_no_input():
    # Replicata: a directory with the finished list F, three lists under way (the first qual's two and one with its
    # first chunk alone) and a plan naming them and two lists not begun, one priced at 50,000 nodes and one without a
    # price; then the same with every chunk's time a million seconds later; with every count of nodes tripled (the
    # chunks' and the plan's price); and with every time and every CPU second doubled.
    # Expectata: the estimator reads no clock, and holds no constant in nodes and none in seconds but the quarter of an
    # hour within which a list is running (the three lists under way are within it either way).  The later sweep's
    # estimate is the same.  With the nodes tripled, done, total and rate are tripled and nothing else moves.  With
    # the seconds doubled, the time to go is doubled and rate halved, and nothing else moves.
    d = sandbox()
    try:
        def made(shift=0.0, nodes=1, seconds=1):
            logs = [[dict(r, time=seconds * r['time'] + shift, cpu_s=seconds * r['cpu_s'], nodes=nodes * r['nodes']) for r in rows] for rows in (F, A, B, D1)]
            plan = [dict(LIST, name='p0'), dict(LIST, name='p1', count=4000), dict(LIST, name='p2'), dict(LIST, name='p3', count=500),
                    dict(name='q0', W=220, floor=4, count=4000, credit=0.05, nodes=nodes * 50000), dict(LIST, name='q1')]
            args, rec = lay(d, logs, [CF, CA, CB, CD], plan=plan)
            p, ests = estimates(d, args, rec)
            assert p.returncode == 0 and len(ests) == 1, (shift, nodes, seconds, p.returncode, p.stderr[-2000:], ests)
            e = ests[0]
            return {k: e[k] for k in ('done', 'rate', 'prior', 'exists', 'finds', 'pending', 'finished')} | {(k, j): e[k][j] for k in ('total', 'to_go') for j in ('lo', 'median', 'hi')}
        base, later, triple, slow = made(), made(shift=1e6), made(nodes=3), made(seconds=2)
        times = lambda e, by: {k: v * by.get((k, k[0])[type(k) is tuple], 1) for k, v in e.items()}        # e, the numbers named in by multiplied (a band's by its name)
        agree = lambda x, y: all(close(x[k], y[k]) for k in x)
        assert base['done'] == 10000 + 23000 + 5000 + 900 and base['pending'] == 3000 + 500 + 250 + 4000 + 1000, base
        assert agree(later, base), (later, base)
        assert agree(triple, times(base, dict(done=3, total=3, rate=3))), (triple, base)
        assert agree(slow, times(base, dict(to_go=2, rate=0.5))), (slow, base)
    finally:
        shutil.rmtree(d)


def q_the_lists_names_are_no_input():
    # Replicata: three lists (the first qual's first with its chunks two hours later, its second, so two hours behind
    # and not running, and the finished list F) and a plan with one more, not begun; written under the names p0, p1,
    # p2 in that order, then in the reverse order, the plan's lines named to match.
    # Expectata: the same estimate.  The estimator takes its lists in their names' order, and no number of the estimate
    # is of that order: which list is running is by the directory's newest chunk, whichever list's that is.
    d = sandbox()
    try:
        lists = [([dict(r, time=r['time'] + 7200.0) for r in A], CA, 4000), (B, CB, 1000), (F, CF, 1000)]
        seen = []
        for order in (lists, lists[::-1]):
            logs, curves, counts = zip(*order)
            args, rec = lay(d, logs, curves, plan=[dict(LIST, name=f'p{i}', count=c) for i, c in enumerate(counts)] + [dict(LIST, name='q0')])
            p, ests = estimates(d, args, rec)
            assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
            seen.append(ests[0])
        a, b = seen
        assert close(a['rate'], 50) and a['pending'] == 3000 + 500 + 1000, a
        assert all(close(a[k], b[k]) for k in ('done', 'rate', 'prior', 'exists', 'finds', 'pending', 'finished')), (a, b)
        assert all(close(a[k][j], b[k][j]) for k in ('total', 'to_go') for j in ('lo', 'median', 'hi')), (a, b)
    finally:
        shutil.rmtree(d)


def q_a_plan_line_without_a_field_stops_it():
    # Replicata: the directory of q_planned_lists_count_before_they_start (the finished list F, the running list B, a
    # plan naming them and two lists not begun); then twelve times over with one of a line's six fields (name, W,
    # floor, count, credit, nodes) left out: of the line of a list begun (p1), and of one not begun (q0).
    # Expectata: with the whole plan, one estimate.  Each other time the estimator fails and appends nothing: a plan
    # line states all six, of a list begun as of one not begun, and the estimator fills none in (a credit or a price
    # read as 0 would be an estimate of another plan).
    # Resultata before: a line of a list begun was read for its name, its count and its price alone; without its W,
    # its floor or its credit the estimate came out as with the line whole.
    d = sandbox()
    try:
        plan = [dict(LIST, name='p0'), dict(LIST, name='p1'), dict(LIST, name='q0'), dict(LIST, name='q1')]
        args, rec = lay(d, [F, B], [CF, CB], plan=plan)
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        for i in (1, 2):
            for field in ('name', 'W', 'floor', 'count', 'credit', 'nodes'):
                args, rec = lay(d, [F, B], [CF, CB], plan=plan[:i] + [{k: v for k, v in plan[i].items() if k != field}] + plan[i + 1:])
                p, ests = estimates(d, args, rec)
                assert p.returncode != 0 and not ests, (plan[i]['name'], field, p.returncode, ests)
    finally:
        shutil.rmtree(d)


def q_a_plan_that_holds_more_than_the_count_stops_it():
    # Replicata: the finished list F, the running list B and a plan naming them and a list not begun whose credit is
    # 3.0, where the model counts 2.5 witnesses in all and the enumeration recovers 0.9 of those in a coset it sweeps;
    # then with the credit 2.6.
    # Expectata: 0.9 (0.07 + 3.0), what the lists and the plan would find, is more than the 2.5 the model says exist:
    # a credit or a curve is wrong, and the estimator fails and appends nothing.  At 2.6 (0.9 times 2.67 is 2.403) it
    # gives its estimate, and finds, the chance that the sweep finds a witness, is no more than exists, the chance
    # that there is one.
    # Resultata before: an estimate with finds 0.933 over exists 0.913: on the page, a search likelier to find a
    # witness than one is to exist.
    d = sandbox()
    try:
        plan = lambda credit: [dict(LIST, name='p0'), dict(LIST, name='p1'), dict(LIST, name='q0', credit=credit)]
        args, rec = lay(d, [F, B], [CF, CB], plan=plan(3.0))
        p, ests = estimates(d, args, rec)
        assert p.returncode != 0 and not ests, (p.returncode, ests)
        args, rec = lay(d, [F, B], [CF, CB], plan=plan(2.6))
        p, ests = estimates(d, args, rec)
        assert p.returncode == 0 and len(ests) == 1, (p.returncode, p.stderr[-2000:], ests)
        e = ests[0]
        assert close(e['finds'], 1 - math.exp(-0.9 * (0.01 + 2.6))) and close(e['exists'], 1 - math.exp(-(2.5 - 0.9 * 0.06))) and e['finds'] <= e['exists'], e
    finally:
        shutil.rmtree(d)


RECORDED = os.path.join(HERE, 'quals', 'quals_sweep_eta_recorded.json')


@functools.lru_cache(maxsize=None)
def replayed(hidden):
    """A stage of the 528:12 sweep as recorded on 2026-11-28 (quals_sweep_eta_recorded.json: 100 lists, each chunk with
    its nodes and the time it ended), through the estimator: (the estimates, each with `at`, the time it is of: every
    fifth minute from the stage's first chunk to its end, and its end; the nodes the lists took; the time the last
    chunk ended; the cosets the stage was to sweep).  The directory at a time: each list's chunks ended by then, a
    curve for a list with a chunk, the model, no witness, and the plan.  hidden leaves out of the plan the lists not
    yet begun: the sweep as the estimator read it before it read a plan.  Made once a run of the suite."""
    rec = json.load(open(RECORDED))
    logs = {}
    for name, x in rec['lists'].items():
        firsts = [0] + [c[0] + 1 for c in x['chunks'][:-1]]
        rows = [chunk(x['digest'], x['K'], c[1], first, c[0], c[2], c[3], cpu=c[4]) for first, c in zip(firsts, x['chunks'])]
        logs[name] = rows[:-1] + [dict(rows[-1], **x['cut'])]
    curves = {name: dict(digest=x['digest'], K=x['K'], W=x['W'], floor=x['floor'], curve=x['curve'], cost=x['cost']) for name, x in rec['lists'].items()}
    stage = [name for name, x in rec['lists'].items() if not x['cut']]
    first, end = min(logs[n][0]['time'] for n in stage), max(logs[n][-1]['time'] for n in stage)
    nodes, cosets = sum(r['nodes'] for rows in logs.values() for r in rows), sum(rows[-1]['count'] for rows in logs.values())
    d, out = sandbox(), []
    try:
        sys.path.insert(0, os.path.join(d, 'searchwatch'))
        import track
        for t in [300.0 * i for i in range(int(first // 300) + 1, int(end // 300) + 1)] + [end]:
            then = {name: [r for r in rows if r['time'] <= t] for name, rows in logs.items()}
            begun = [name for name in logs if then[name]]
            args, record = lay(d, [then[n] for n in begun], [curves[n] for n in begun], model=rec['model'],
                               plan=[x for x in rec['plan'] if x['name'] in begun or not hidden], name=begun.__getitem__)
            p, ests = estimates(d, args, record)
            assert p.returncode == 0 and len(ests) == 1, (t, p.returncode, p.stderr[-2000:])
            track.checked(track.lines(record))
            out.append(dict(ests[0], at=t))
    finally:
        shutil.rmtree(d)
    return out, nodes, end, cosets


def q_through_a_recorded_stage_the_bands_hold_what_it_took():
    # Replicata: a stage of the 528:12 sweep as recorded (2026-11-28, 06:29 to 10:12: floor 4 over the first 10,000
    # cosets of 96 width-210 lists, begun a few at a time as slots came free, beside four lists cut the night before),
    # replayed: the estimator run on the directory as it stood at every fifth minute, 44 times, with the plan as the
    # planner writes one since that afternoon (each list's count, credit and price).  Then the same with the lists not
    # yet begun left out of the plan.
    # Expectata (dreeves, 2026-11-28, of this sweep's ETA chart: "these ETAs sure don't look calibrated"): a band runs
    # from the tenth to the ninetieth hundredth of what is to come, so it is meant to hold the truth four times in
    # five; here it holds it in three quarters of the estimates at least, of the nodes in all (what the 100 lists
    # took) and of the time to go (to the stage's last chunk).  The median of the nodes in all is within a tenth of
    # what they took at every estimate.  With the lists not begun left out, which is the sweep as the estimator read
    # it until that morning, neither band holds the truth that often, and the median of the nodes in all is under nine
    # tenths of what they took at more than half the estimates.
    # Resultata on 2026-11-28: the bands held the truth at 41 and 36 of the 44; with the plan's unbegun lists left out,
    # at 6 and 20.  (That morning, with the kind's measure in place of prices, the median ran from 0.9 to 4.6 times
    # the truth.)  Since that night's forecast by cost (a priced list by its price and its ratio so far): at 44 and 36,
    # and at 8 and 19.
    ests, nodes, end, cosets = replayed(False)
    es, hs = ests[:-1], replayed(True)[0][:-1]        # the estimate at the stage's end is the next qual's
    held = lambda xs: (sum(e['total']['lo'] <= nodes <= e['total']['hi'] for e in xs), sum(e['to_go']['lo'] <= end - e['at'] <= e['to_go']['hi'] for e in xs))
    need = 3 * len(es) / 4
    assert len(es) == len(hs) >= 40 and min(held(es)) >= need, (held(es), len(es))
    assert all(abs(e['total']['median'] / nodes - 1) <= 0.1 for e in es), [round(e['total']['median'] / nodes, 3) for e in es]
    assert max(held(hs)) < need and sum(e['total']['median'] < 0.9 * nodes for e in hs) > len(hs) / 2, (held(hs), len(hs))


def q_through_a_recorded_stage_the_cosets_add_up_and_no_chance_rises():
    # Replicata: the replay of the qual above, with one more estimate at the stage's end.
    # Expectata: at every estimate the cosets pending and finished add up to the stage's (the 96 lists' 10,000 each
    # and what the cut lists had swept), whichever lists have begun.  While nothing is found neither exists nor finds
    # rises from one estimate to the next (a list's start adds no chance: its credit was the plan's), and finds, the
    # sweep's chance of a find, is never over exists, the chance that there is a witness.  At the end nothing is
    # pending or to come: total is done at all three levels, the nodes the lists took; the time to go 0; finds 0.
    # With the lists not begun left out of the plan, finds rises as lists begin: the fault of before the plan.
    ests, nodes, end, cosets = replayed(False)
    assert all(e['pending'] + e['finished'] == cosets for e in ests), [(e['at'], e['pending'], e['finished']) for e in ests if e['pending'] + e['finished'] != cosets]
    for a, b in zip(ests, ests[1:]):
        assert b['exists'] <= a['exists'] and b['finds'] <= a['finds'], (a, b)
    assert all(e['finds'] <= e['exists'] for e in ests), ests
    last = ests[-1]
    assert (last['pending'], last['finished'], last['done'], last['finds']) == (0, cosets, nodes, 0), last
    assert last['total'] == dict(lo=nodes, median=nodes, hi=nodes) and last['to_go'] == dict(lo=0, median=0, hi=0), last
    hid = replayed(True)[0]
    assert any(b['finds'] > a['finds'] for a, b in zip(hid, hid[1:])), 'the control shows no rise'


def q_a_curve_of_another_list_stops_it():
    # Replicata: the first log above with a curve whose digest is another list's; then with a curve that ends before
    # the list does.
    # Expectata: each time the estimator fails and appends nothing: an estimate from a curve that is not the list's
    # would be a wrong P(exists).
    d = sandbox()
    try:
        for curve in (dict(CA, digest='zz'), dict(CA, curve=CA['curve'][:2])):
            args, rec = lay(d, [A], [curve])
            p, ests = estimates(d, args, rec)
            assert p.returncode != 0 and not ests, (curve, p.returncode, ests)
    finally:
        shutil.rmtree(d)


if __name__ == '__main__':
    # TODO: error copy; says the script refuses to run under python -O, which would strip its assertions
    if not __debug__: raise SystemExit('Fable 5.2: "nolo sine assertionibus currere (python -O)"')
    names = sys.argv[1:] or [k for k in list(globals()) if k.startswith('q_')]
    failed = 0
    for name in names:
        try:
            globals()[name]()
            print(f'PASSED {name}', flush=True)
        except Exception:
            failed += 1
            print(f'FAILED {name}:\n{traceback.format_exc()[-1500:]}', flush=True)
    raise SystemExit(1 if failed else 0)
