diff --git a/infra/bin/fly-loop-recover b/infra/bin/fly-loop-recover index edbfb46..28d10d7 100755 --- a/infra/bin/fly-loop-recover +++ b/infra/bin/fly-loop-recover @@ -3,8 +3,12 @@ Ladder (infra/docs/loop-recovery.md): restart flysim, then reset to the current rung's milestone, then to the rung below. It climbs one step per confirmed trap that outlives -the previous step, and starts over once the fly reaches a new best rung or has been -quiet for QUIET seconds. A router model can delay a step, never deny it. +the previous step, and starts over once the fly reaches a new best rung, makes lasting +progress after the last step that it had not made before (a reset's replay re-earns its +archive's rewards, which is not progress), or has been quiet for QUIET seconds. A milestone reset +never erases a species first owned within PROTECT seconds, and never repeats the last +reset's archive (a restore replays it exactly); either is a restart instead. A router model can +delay a step, never deny it. """ import json import os @@ -29,6 +33,9 @@ QUIET = 6 * 3600 # this long without a suspected report starts the ladder ov HOLD = 3 * 3600 # restart-only spacing while the reset budget is spent DAY = 24 * 3600 MAX_RESETS = 2 # milestone resets per DAY +AGAIN = 12 * 3600 # after this long the last reset's archive may be restored again (row 70) +PROTECT = 2 * 3600 # a species owned this recently is not reset away (row 70) +SEEN = 2000 # lasting-progress names remembered, oldest dropped first (row 70 r3) VETO_LIMIT = 3 # model vetoes of one step before it goes ahead anyway MODEL_BUDGET = 90 # seconds across all models in one decision VERIFY_TIMEOUT = 240 @@ -142,16 +149,19 @@ def rungs(): return sorted(found) -def plan(level, rank, best, resets_left): +def plan(level, rank, best, resets_left, last_reset=None): """(action, target rung) for a ladder level; a spent budget or no restorable archive is a restart. Level 1 resets to the current rung's archive; level 2 and beyond to the rung below the best, - and never lower, so repeated days of a trap cannot walk the run down the ladder. + and never lower, so repeated days of a trap cannot walk the run down the ladder. The archive + the last reset restored is not restored again (`last_reset`, cleared by a new best rung): a + restore is deterministic, so the same archive replays the same run into the same trap (row 70: + the second reset to rung 11 matched the first event for event). """ if level == 0 or not resets_left or rank is None: return "restart", None target = rank if level == 1 else max(best, rank) - 1 - if target > rank or target not in restorable_rungs(): + if target > rank or target == last_reset or target not in restorable_rungs(): return "restart", None return "reset", target @@ -226,7 +236,10 @@ def run(now=None, sleep=time.sleep, clock=None): if level: log({"at": now, "event": "ladder-reset", "why": "new best rung", "rank": rank}) state.update(bestRank=rank, level=0) + state.pop("lastReset", None) level = 0 + if "lastReset" in state and now - state.get("lastResetAt", 0) >= AGAIN: + state.pop("lastReset", None) last = state.get("lastSuspectedAt") if level and last and now - last > QUIET: log({"at": now, "event": "ladder-reset", "why": "quiet", "rank": rank}) @@ -234,6 +247,46 @@ def run(now=None, sleep=time.sleep, clock=None): state["resets"] = [at for at in state.get("resets", []) if now - at < DAY] at = report.get("at") + # Row 70: lasting progress in the probe's window (a new rung, a species owned, a map entered, + # a trainer or badge beaten; the watchdog's window.progress). The ladder climbs for a trap that + # OUTLIVES its last step; one that follows real progress after that step is a new trap and + # starts again from a restart. A species owned is also kept from a milestone reset for PROTECT. + # A new trap means the old one let go: a clear probe more than SETTLE after the step, so a catch + # made while the fly stays flagged does not start the ladder over. + # + # Progress is measured against everything the ladder has seen before, not against the + # restored archive (row 70 review r3): a milestone reset restores the reward ledger, so the + # replay pays the archive's areas, trainers, species and rungs again, and counting those + # started the ladder over after every reset (a rung-12 replay re-earning an area and a + # species cost two extra steps and a three-hour hold before the rung below). The watchdog + # names each lasting reward (`window.progress.keys`, `kind:label`); only a name not in + # `progressSeen` is progress, and only a species not in it is protected (the replayed catch + # was the fly's before the reset too, and was protected then). A watchdog without names falls + # back to the counts. + progress = (report.get("window") or {}).get("progress") or {} + fresh = type(at) is int and 0 <= now - at <= 600 + if fresh and report.get("suspected") == 0: + state["clearAt"] = max(at, state.get("clearAt", 0)) + if fresh and type(progress) is dict: + keys = progress.get("keys") + if type(keys) is list: + seen = state.get("progressSeen") + seen = [key for key in seen if type(key) is str] if type(seen) is list else [] + known = set(seen) + new = [key for key in dict.fromkeys(key for key in keys if type(key) is str) if key not in known] + state["progressSeen"] = (seen + new)[-SEEN:] + lasting, species = len(new), sum(key.startswith("pokedex:") for key in new) + else: + lasting, species = (progress.get(name) if type(progress.get(name)) is int else 0 + for name in ("lasting", "species")) + if lasting > 0: + state["progressAt"] = max(at, state.get("progressAt", 0)) + if species > 0: + state["speciesAt"] = max(at, state.get("speciesAt", 0)) + since = state.get("actedAt", 0) + SETTLE + if level and state.get("progressAt", 0) > since and state.get("clearAt", 0) > since: + log({"at": now, "event": "ladder-reset", "why": "progress since the last step", "rank": rank}) + state["level"] = level = 0 # The last probe that saw progress (new places, or a higher rung than the last probe), kept across # restarts and reboots so the stream's STUCK time counts the whole trap, not the last streak. delta = (report.get("places") or {}).get("delta") @@ -265,10 +318,25 @@ def run(now=None, sleep=time.sleep, clock=None): return "waiting for next probe" resets_left = MAX_RESETS - len(state["resets"]) - action, target = plan(level, rank, state.get("bestRank", 0), resets_left) - if action == "restart" and level and now - acted < HOLD: + action, target = plan(level, rank, state.get("bestRank", 0), resets_left, state.get("lastReset")) + protected = action == "reset" and now - state.get("speciesAt", -PROTECT) < PROTECT + # Only a catch-protected reset is held (the level keeps its slot, so it never drops a rung deeper + # while the window lasts, row 70). A step skipped because it would restore the archive just used + # does climb, so the ladder reaches the rung below promptly. + held_reset = protected + if protected: + action, target = "restart", None + # Restarts are at least HOLD apart, also when the ladder has started over since the last one. + if action == "restart" and (level or state.get("lastAction") == "restart") and now - acted < HOLD: write_json(STATE, state) - return "holding: reset budget spent, next restart after the hold" + if protected: + return "holding: a species owned within the protection window, next restart after the hold" + if not level: + return "holding: the last restart was under three hours ago" + return "holding: no reset to take, next restart after the hold" + if protected: + log({"at": now, "event": "protect", "why": "a species owned within the protection window", + "speciesAt": state["speciesAt"], "rank": rank}) stuck, model = verdict(report) if stuck is False and state.get("vetoes", 0) < VETO_LIMIT: @@ -289,15 +357,18 @@ def run(now=None, sleep=time.sleep, clock=None): notice(base, "countdown", now) sleep(COUNTDOWN) started = int(clock()) - # Recorded before acting, so a helper killed mid-step has still climbed and spent the reset. - state.update(level=level + 1, actedAt=started, lastAction=action, vetoes=0) + # Recorded before acting, so a helper killed mid-step has still climbed (unless held) and spent the reset. + state.update(level=level if held_reset else level + 1, actedAt=started, lastAction=action, vetoes=0) state.pop("observedAt", None) if action == "reset": state["resets"].append(started) + state.update(lastReset=target, lastResetAt=started) write_json(STATE, state) notice(base, "acting", started) ok = act(action, target) finished = int(clock()) + if action == "reset" and not ok: + state.pop("lastReset", None) # not known to have been restored, so it may be tried again notice(base, "done" if ok else "failed", finished) state["actedAt"] = finished write_json(STATE, state) diff --git a/infra/bin/fly-watchdog b/infra/bin/fly-watchdog index 944c012..6d11c8c 100755 --- a/infra/bin/fly-watchdog +++ b/infra/bin/fly-watchdog @@ -880,7 +880,7 @@ loop_status_fields() { loop_macro_stream() { [ -f "$FLY_EVENT_LOG" ] || return 0 tail -n "$WD_LOOP_TAIL_LINES" "$FLY_EVENT_LOG" 2>/dev/null \ - | jq -r 'fromjson? // empty | select(.kind == "macro" or .kind == "reward") | "\(.brainMs)\t\(.label)\t\(.kind)\t\(.rewardKind // "")"' -R 2>/dev/null \ + | jq -r 'fromjson? // empty | select(.kind == "macro" or .kind == "reward" or .kind == "milestone") | "\(.brainMs)\t\(.label)\t\(.kind)\t\(.rewardKind // "")"' -R 2>/dev/null \ || true } @@ -888,13 +888,22 @@ loop_macro_stream() { # # total US distinct US topCount US period US repeats US windowFrom US # windowTo US topName US block US tail US decisions US refused US blocked US -# timeout US done US rewards US fights US wins +# timeout US done US rewards US fights US wins US progress US species US keys # # `total` counts start events inside the window, `decisions` starts plus # refusals (the sequence, `distinct` and `topCount` are over decisions), and # the next four count each outcome in the window, and `rewards` the reward # events in it (row 58), `fights` the `MOVE n` decisions and `wins` the -# rewards of kind wildwin/trainer/badge (row 67). `period`/`repeats` describe +# rewards of kind wildwin/trainer/badge (row 67). `progress` counts the lasting +# progress in the window (row 70): a `milestone` event (a new rung), or a reward of kind +# pokedex (a species owned for the first time), area (a map entered for the first time), +# trainer or badge -- each paid once per run, so a ring cannot earn them twice -- and +# `species` the pokedex ones alone. `keys` names each of them once as `kind:label` +# (`pokedex:OWNED #8`, `milestone:Reached MT. MOON`), RS-joined, at most 64: a milestone +# reset restores the reward ledger, so its replay pays the same rewards again, and only +# the names tell a replayed reward from a new one. They are reported, never read by a +# rule here: the recovery ladder uses them to tell a trap that follows real progress from +# one that outlived its last step. `period`/`repeats` describe # the shortest repeating block at the END of the sequence (0/0 when nothing # repeats), `block` is that block comma-joined, and `tail` is the last 12 # names for context. The window ends at the newest macro event's own brain @@ -903,17 +912,28 @@ loop_analyze() { awk -F'\t' -v win="$WD_LOOP_WINDOW_MS" -v maxp="$WD_LOOP_MAX_PERIOD" ' # Reward lines are counted and nothing else: the window still ends at the # newest macro event, as it always has. - $3 == "reward" { rms[++nr] = $1 + 0; rkind[nr] = $4; next } + $3 == "reward" { rms[++nr] = $1 + 0; rkind[nr] = $4; rlbl[nr] = $2; next } + $3 == "milestone" { rms[++nr] = $1 + 0; rkind[nr] = "milestone"; rlbl[nr] = $2; next } { ms[++n] = $1 + 0; lbl[n] = $2 } END { - if (n == 0) { printf "0\0370\0370\0370\0370\0370\0370\037\037\037\0370\0370\0370\0370\0370\0370\0370\0370\n"; exit } + if (n == 0) { printf "0\0370\0370\0370\0370\0370\0370\037\037\037\0370\0370\0370\0370\0370\0370\0370\0370\0370\0370\037\n"; exit } to = ms[n]; from = to - win k = 0; distinct = 0; topn = 0; top = "" starts = 0; refused = 0; blocked = 0; timeout = 0; done = 0; rewards = 0 - fights = 0; wins = 0 + fights = 0; wins = 0; progress = 0; species = 0; keys = ""; nkeys = 0 for (q = 1; q <= nr; q++) if (rms[q] >= from) { + lasting = rkind[q] == "milestone" || rkind[q] == "pokedex" || rkind[q] == "area" \ + || rkind[q] == "trainer" || rkind[q] == "badge" + if (lasting) { + progress++ + key = rkind[q] ":" rlbl[q] + gsub(/[\036\037]/, " ", key) + if (!(key in seenkey) && nkeys < 64) { seenkey[key] = 1; keys = keys (nkeys++ ? "\036" : "") key } + } + if (rkind[q] == "milestone") continue rewards++ if (rkind[q] == "wildwin" || rkind[q] == "trainer" || rkind[q] == "badge") wins++ + if (rkind[q] == "pokedex") species++ } for (i = 1; i <= n; i++) { if (ms[i] < from) continue @@ -948,9 +968,9 @@ loop_analyze() { tailstr = "" start = k - 11; if (start < 1) start = 1 for (j = start; j <= k; j++) tailstr = tailstr (tailstr == "" ? "" : ", ") seq[j] - printf "%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\037%s\037%s\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\n", \ + printf "%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\037%s\037%s\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\n", \ starts, distinct, topn, period, repeats, from, to, top, block, tailstr, \ - k, refused, blocked, timeout, done, rewards, fights, wins + k, refused, blocked, timeout, done, rewards, fights, wins, progress, species, keys }' } @@ -1008,15 +1028,15 @@ check_loop() { echo "$delta" > "${WD_RUN_DIR}/loop.places_delta" local analysis total distinct topn period repeats win_from win_to top block tailstr - local decisions refused blocked timeouts completed rewards fights wins + local decisions refused blocked timeouts completed rewards fights wins progress species keys analysis="$(loop_macro_stream | loop_analyze)" IFS=$'\037' read -r total distinct topn period repeats win_from win_to top block tailstr \ - decisions refused blocked timeouts completed rewards fights wins <<< "$analysis" + decisions refused blocked timeouts completed rewards fights wins progress species keys <<< "$analysis" total="${total:-0}"; distinct="${distinct:-0}"; topn="${topn:-0}" period="${period:-0}"; repeats="${repeats:-0}" decisions="${decisions:-0}"; refused="${refused:-0}"; blocked="${blocked:-0}" timeouts="${timeouts:-0}"; completed="${completed:-0}"; rewards="${rewards:-0}" - fights="${fights:-0}"; wins="${wins:-0}" + fights="${fights:-0}"; wins="${wins:-0}"; progress="${progress:-0}"; species="${species:-0}" echo "$distinct" > "${WD_RUN_DIR}/loop.distinct" echo "$period" > "${WD_RUN_DIR}/loop.period" echo "$repeats" > "${WD_RUN_DIR}/loop.repeats" @@ -1130,6 +1150,9 @@ check_loop() { --argjson rewards "$rewards" \ --argjson fights "$fights" \ --argjson wins "$wins" \ + --argjson progress "$progress" \ + --argjson species "$species" \ + --arg keys "${keys:-}" \ --argjson windowFrom "${win_from:-0}" \ --argjson windowTo "${win_to:-0}" \ --argjson windowMs "$WD_LOOP_WINDOW_MS" \ @@ -1161,6 +1184,8 @@ check_loop() { rewards: $rewards, fights: $fights, wins: $wins, + progress: { lasting: $progress, species: $species, + keys: (if $keys == "" then [] else ($keys | split("\u001e")) end) }, tail: (if $tail == "" then [] else ($tail | split(", ")) end) }, dominant: { name: (if $dominant == "" then null else $dominant end), diff --git a/infra/docs/loop-recovery.md b/infra/docs/loop-recovery.md index 3f6bb8e..b0e7d45 100644 --- a/infra/docs/loop-recovery.md +++ b/infra/docs/loop-recovery.md @@ -16,9 +16,35 @@ a ladder one step per trap that outlives the previous step: their 10-brain-minute window lies after it. The helper waits that long after every step. - **Budget:** at most two milestone resets per 24 hours. With the budget spent the step is a restart, at most every three hours, until a reset is free again. The same three-hour spacing applies - when a reset level finds no restorable rung and restarts instead. -- **Starting over:** the ladder returns to level 0 when the fly reaches a new best rung, or after - six hours with no suspected report. + when a reset level finds no restorable rung and restarts instead, and between any two restarts in a + row, also when the ladder has started over in between. +- **Starting over:** the ladder returns to level 0 when the fly reaches a new best rung, after + six hours with no suspected report, or when the fly makes new lasting progress more than + 20 minutes after the last step and a clear probe shows the old trap let go (row 70). Lasting + progress is the watchdog's `window.progress`: a rung reached, a species owned, a map entered, or + a trainer or badge beaten, each named in `window.progress.keys` as `kind:label` (`pokedex:OWNED + #41`). A ring cannot earn them twice, but a milestone reset restores the reward ledger, so its + replay pays the archive's rewards again. Progress is therefore measured against every name the + ladder has seen (`progressSeen` in the state file, the last 2,000), not against the restored + archive: a replay re-earning what the run had before the reset is not progress, and the ladder + climbs on to the rung below as it did before row 70. A trap that follows new progress is a new + trap, and it starts again from a restart. A catch made while the fly stays flagged is not a new + trap. With a watchdog that reports no names, the counts are used as before. + Names the ladder never saw (before this version was deployed, or while an older one ran) count + as new once. +- **Protected catches:** a milestone reset never erases a species first owned in the last two hours + (`PROTECT`, a `pokedex:` name not seen before). A species a reset's replay owns again was the fly's + before the reset and was protected then, so it does not open a second window. Within that window the step is a restart, spaced by + the hold like a spent budget, and `history.jsonl` records a `protect` event. A reset turned into a + restart this way does not climb the ladder: the level keeps its slot and the reset comes, at the + same rung, once the window ends. Evolution also counts as a species owned. +- **No archive twice in a row:** a reset never restores the same archive as the last reset, + until a new best rung is reached or twelve hours have passed (`AGAIN`; a trap no restart clears + is reset again in bounded time, no later than before this rule). Such a step does climb, so the rung below is reached promptly. A restore is deterministic, so the same archive replays the + same run into the same trap. Row 70's second reset to rung 11 matched the first one event for + event: the same Zubat caught, the same trap an hour later, and the catch erased. That step is + a restart instead. A reset that fails does not mark its archive: it is not known to have been + restored, so the next reset may try it again. A milestone step only uses an archive the running build can restore. `fly-loop-reset --list` compares each archive's compatibility string with `flysim --print-compatibility` and accepts an diff --git a/infra/docs/macros-traps.md b/infra/docs/macros-traps.md index 15fa6a7..9f252b3 100644 --- a/infra/docs/macros-traps.md +++ b/infra/docs/macros-traps.md @@ -3629,3 +3629,61 @@ ROM tests on the build box (rom-env sourced): The stub reaches row 70 by itself. From the live rung-12 archive (Mt. Moon's mouth, one ball), three uniform-stub seeds each catch a Zubat within 4,000 frames and meet the same Lass. There Wartortle faints at f27,361, f34,656 and f35,284. + +### The watchdog and the ladder: every act was on a real trap + +The day's six acts, replayed probe by probe through check 10 and the ladder from the live logs +(open loop; uniqueLocations proxied from the tile rewards). The base replay reproduces the live +history: restarts at 05:55, 08:55 and 11:55, and resets to rung 11 at 16:50 and 18:49 (live: +16:54 and 18:50). + +| live act | window | what the fly was doing | +| --- | --- | --- | +| restarts 05:57, 08:58, 11:59 (map 59) | `unwon-battles`, 05:50 to 13:50 | Row 67 again, against a Lass on Mt. Moon 1F. `MOVE 2` (TAIL WHIP) on six turns in seven, BUBBLE doing 5 to 8 to her Oddish, 34 to 48 moves per window, no battle won, whiteout and back. Beaten after the 11:59 restart (13:54, then the other 1F trainers, B2F's and the Super Nerd) | +| reset to 11, 16:54 (map 61, B2F) | `unrewarded`, 15:05 to 16:50 | A wild encounter every ~20 s, `RUN` every time (220), `GO FRONTIER`/`GO WARP` between them, and no new tile or reward for 1 h 50 min. The battles were ending and the fly was moving between them, but on ground it had already covered. Mechanism not established: no checkpoint from before 16:54 survives (row 64/65 territory, B2F's far side) | +| reset to 11, 18:50 (map 59) | `dominant`/`sequence`, 17:59 on | Row 70's list: `NEXT` alone for 58 brain minutes | + +So check 10 read no cave as a trap. Healthy cave windows (17:04 to 17:54: Route 3 and Mt. Moon +battles won, a catch, new areas) peaked at 94% `NEXT`, and the tile gate kept them clear. Two +suggested relaxations are **not** supported by the evidence: + +- "Battles ending and the fly moving between them": the 16:54 window was exactly that for + 1 h 50 min, with nothing new. +- Counting the damage reward's KO as a win: the Lass ring had 45 KOs of her first Pokémon in + eight hours and never won. + +The watchdog's flags are unchanged. Every replayed log (rows 58, 60 to 64, 67, 70) flags on the +same probes with the same reasons, base and branch. + +What went wrong was the ladder. It stayed at level 3 to 4 from the morning's ring through a +rung-11 reset and a full, rewarded climb back to Mt. Moon. The 18:50 reset then restored the +same rung-11 archive as the 16:54 one. A restore is deterministic: the replay after it matched +the one before event for event (1,138 of 1,138, same `brainMs`). So the reset erased the catch +and walked back into the same list about an hour later. It also could not have helped: row 70's +trap is in the game state, not the ledgers, so neither a restart nor a replay clears it. + +| # | trap | trigger | test | fix, or why it is left | +| --- | --- | --- | --- | --- | +| 70b | the ladder never started over after real progress. A trap after a reset and a rewarded climb back was treated as the old trap outliving its step | a reset, then progress, then any trap | `test_progress_after_the_last_step_starts_the_ladder_over`, `test_progress_while_a_step_settles_does_not_start_the_ladder_over` | **fixed**: `window.progress` in loop.json (report only; `lint.sh` check 10 case 9). New lasting progress more than `SETTLE` after the step, once a clear probe shows the trap let go, returns the ladder to level 0 (see 70f) | +| 70c | a reset restored the same archive as the last reset, which replays deterministically into the same trap | level 2 and above, where every step targets the rung below the best | `test_the_last_resets_archive_is_not_restored_again`, `test_a_reset_records_its_archive_and_a_new_best_rung_forgets_it` | **fixed**: that step is a restart | +| 70d | a reset erased a catch made an hour earlier | any reset after a catch | `test_a_species_owned_recently_is_never_reset_away`, `test_a_probe_that_owns_a_species_starts_the_protection` | **fixed**: within two hours of a species first owned, a reset is a restart (held three hours apart) | +| 70f | (review r3) a reset's replay counted as progress. The restored reward ledger pays the archive's areas, trainers, species and rung again, so 70b started the ladder over after every reset, and a replayed catch opened a second protection window. A trap only the rung below escapes took 5.6 h (6.8 h after a catch) to reach it, against 2.1 h in v0.7.0 | a reset whose replay re-earns rewards, then traps | `test_a_replay_that_re_earns_seen_rewards_does_not_start_the_ladder_over`, `test_a_reward_not_seen_before_starts_the_ladder_over_and_a_new_species_is_protected`, `test_a_catch_while_the_fly_stays_flagged_does_not_start_the_ladder_over`, `test_a_trap_only_the_rung_below_escapes_is_reached_promptly`, `test_restarts_are_a_hold_apart_in_every_closed_loop` | **fixed**: `window.progress.keys` names each lasting reward (`lint.sh` check 10 case 9); progress and protection count only names the ladder has not seen (`progressSeen`). 2.1 h (3.3 h after a catch). Restarts stay three hours apart, and a failed reset does not mark its archive | +| 70e | the B2F wander: `RUN` from every encounter, walks on covered ground, nothing new for 1 h 50 min | Mt. Moon B2F after the Super Nerd | -- | **left, named**: no checkpoint survived. The next occurrence should be pulled before any reset | + +Ladder replay of the day (the same logs and the same start state, base against branch): + +- **Base**: restarts at 01:30, 05:55, 08:55, 11:55 and 15:10; resets to 11 at 16:50 and 18:49. +- **Branch**: restarts at 01:30, 05:55, 07:15, 10:30, 13:30 and 15:10; a reset to 12 (the + current rung, not 11) at 16:50; a restart at 18:04. + - 07:15: AREA 60 at 06:48 started the ladder over. + - 18:04: the climb after 16:50 started the ladder over. + - After 18:04, no reset. The Zubat was owned at 17:46 and rung 12 was the last reset's + archive, so the branch holds to restarts three hours apart. + +- **Review r3** (names, from a live-like 00:00 state, then the post-16:54 log with the state carried + over): restarts at 01:30, 05:55, 08:55, 11:55 and 15:10, as live; a reset to 12 at 16:50 (the + 13:54 to 14:20 trainers were new, so the ladder had started over). After 16:54 the Route 3 + trainers, AREA 59, OWNED #8 and the rung are the replay's and do not count; OWNED #41 (the + Zubat, 17:46) is new, so a restart at 18:04 and then the protection hold through 18:54, no reset. + +The replay is open loop: the log after 16:50 is what the base's reset produced. diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh index 7b2240a..4b1f94c 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -2015,6 +2015,38 @@ LPCAT fail "check 10: a won battle gave suspected=$(lp_metric fly_loop_suspected) wins=$(lp_metric fly_loop_wins)" fi + # (9) Row 70: the report carries the window's lasting progress for the recovery ladder -- + # a milestone event, and rewards of kind pokedex/area/trainer/badge -- and the species + # alone. The flag itself does not read them: the same battles still flag with a species + # owned in the window, as long as nothing was won. + lp_reset + lp_cycle 25 "GO OBJECTIVE" "TALK" "NO" "NEXT" "NEXT" "NEXT" "MOVE 2" "NEXT" \ + "MOVE 2" "NEXT" "MOVE 3" "NEXT" | lp_outcomes "$lp_fixture/events.jsonl" "done" + printf '%s\n' \ + '{"id":999991,"wallMs":1758000999991,"brainMs":100000,"kind":"reward","label":"OWNED #41","value":0.5,"rewardKind":"pokedex"}' \ + '{"id":999992,"wallMs":1758000999992,"brainMs":100001,"kind":"reward","label":"AREA 59","value":0.2,"rewardKind":"area"}' \ + '{"id":999993,"wallMs":1758000999993,"brainMs":100002,"kind":"milestone","label":"Reached MT. MOON","value":12}' \ + >> "$lp_fixture/events.jsonl" + lp_status "$lp_fixture/status.json" 2311 + lp_pass + lp_pass + lp_pass + if lp_report="$(jq -e -r '[.reason, (.window.rewards|tostring), (.window.progress.lasting|tostring), (.window.progress.species|tostring)] | join(" ")' "$lp_fixture/run/loop.json" 2>/dev/null)" \ + && [ "$lp_report" = "unwon-battles 2 3 1" ]; then + pass "check 10: loop.json carries the window's lasting progress (a rung, a species, a map) for the ladder, and the flag does not read it" + else + fail "check 10: loop.json read back as '${lp_report:-UNREADABLE}' — expected 'unwon-battles 2 3 1'" + fi + # ... and names each once (review r3): a reset's replay pays the same rewards again, and only + # the names let the ladder tell them from new ones. + lp_expected='pokedex:OWNED #41|area:AREA 59|milestone:Reached MT. MOON' + if lp_report="$(jq -e -r '.window.progress.keys | join("|")' "$lp_fixture/run/loop.json" 2>/dev/null)" \ + && [ "$lp_report" = "$lp_expected" ]; then + pass "check 10: loop.json names the window's lasting progress (kind:label) so the ladder can tell a replayed reward from a new one" + else + fail "check 10: window.progress.keys read back as '${lp_report:-UNREADABLE}' — expected '${lp_expected}'" + fi + # The ethos, asserted rather than reviewed: over every case above, check 10 # restarted nothing. It reports; a human or a review agent decides. if [ ! -s "$lp_fixture/systemctl.log" ]; then diff --git a/infra/tests/test_loop_recover.py b/infra/tests/test_loop_recover.py index 0231bf5..fc7c1a1 100644 --- a/infra/tests/test_loop_recover.py +++ b/infra/tests/test_loop_recover.py @@ -117,6 +117,143 @@ class RecoveryTests(unittest.TestCase): self.confirm(T0, rank=13) self.assertEqual(self.acts, [("restart", None)]) + # Row 70: the rung-11 reset replayed the run exactly (1,138 of 1,138 events), caught the Zubat + # again and walked into the same trap; the next step reset to rung 11 again and erased the catch. + def test_progress_after_the_last_step_starts_the_ladder_over(self): + recover.write_json(recover.STATE, {"level": 4, "bestRank": 12, "resets": [], "actedAt": T0 - 7200}) + # an area and a species inside the windows of probes well after the step + self.tick(T0 - 3000, suspected=0, window={"progress": {"lasting": 2, "species": 0}}) + self.assertIn("flysim restarted", self.confirm(T0)) + self.assertEqual(self.acts, [("restart", None)]) + history = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()] + self.assertIn("progress since the last step", [event.get("why") for event in history]) + + def test_progress_while_a_step_settles_does_not_start_the_ladder_over(self): + recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 1500}) + self.tick(T0 - 1400, suspected=0, window={"progress": {"lasting": 3, "species": 0}}) + self.confirm(T0) + self.assertEqual(self.acts, [("reset", 11)]) + + def test_a_species_owned_recently_is_never_reset_away(self): + owned = T0 - 1200 + recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], + "actedAt": T0 - recover.HOLD - 300, "speciesAt": owned}) + self.assertIn("flysim restarted", self.confirm(T0)) + self.assertEqual(self.acts, [("restart", None)]) + history = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()] + self.assertIn("protect", [event.get("event") for event in history]) + # the hold still spaces the restarts, and says why + self.assertIn("protection window", self.confirm(T0 + 300 + recover.SETTLE + 10)) + # the protection lasts PROTECT from the species; then the ladder resets as before + self.assertIn("reset to rung 11", self.tick(owned + recover.PROTECT + 60)) + + def test_a_probe_that_owns_a_species_starts_the_protection(self): + self.tick(T0, suspected=0, window={"progress": {"lasting": 1, "species": 1}}) + self.assertEqual(recover.load(recover.STATE, {}).get("speciesAt"), T0) + self.assertEqual(recover.load(recover.STATE, {}).get("progressAt"), T0) + + def test_the_last_resets_archive_is_not_restored_again(self): + acted = T0 - recover.HOLD - 100 + recover.write_json(recover.STATE, {"level": 3, "bestRank": 12, "resets": [acted], + "actedAt": acted, "lastReset": 11, "lastResetAt": acted}) + self.confirm(T0) + self.assertEqual(self.acts, [("restart", None)]) + + def test_a_protected_reset_does_not_climb_but_the_archive_just_used_does(self): + # protected: the restart keeps the level's slot, so the reset comes at the same rung later + owned = T0 - 600 + recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [], "actedAt": 0, + "speciesAt": owned}) + self.confirm(T0) + self.assertEqual(self.acts, [("restart", None)]) + self.assertEqual(recover.load(recover.STATE, {}).get("level"), 1) + # the archive just restored: a restart that climbs, and the marker is forgotten after AGAIN + self.acts.clear() + reset_at = T0 - recover.HOLD - 100 + recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [reset_at], "actedAt": reset_at, + "lastReset": 12, "lastResetAt": reset_at}) + self.confirm(T0 + 1000) + self.assertEqual(self.acts, [("restart", None)]) + self.assertEqual(recover.load(recover.STATE, {}).get("level"), 2) + self.acts.clear() + self.tick(reset_at + recover.AGAIN + 60) + self.assertNotIn("lastReset", recover.load(recover.STATE, {})) + + def test_a_reset_records_its_archive_and_a_new_best_rung_forgets_it(self): + recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0}) + self.confirm(T0) + self.assertEqual(recover.load(recover.STATE, {}).get("lastReset"), 11) + self.tick(T0 + 300 + recover.SETTLE + 10, suspected=0, rank=13) + self.assertNotIn("lastReset", recover.load(recover.STATE, {})) + + # Row 70 review r3: a reset restores the reward ledger, so its replay pays the archive's rewards + # again. Progress is a reward name the ladder has not seen before, not a count. + def test_a_replay_that_re_earns_seen_rewards_does_not_start_the_ladder_over(self): + seen = ["area:AREA 59", "pokedex:OWNED #8", "trainer:BEAT ROUTE 3 TRAINER 0", "milestone:Reached MT. MOON"] + recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 7200, + "progressSeen": seen}) + replay = {"progress": {"lasting": 4, "species": 1, "keys": seen}} + self.tick(T0 - 3000, suspected=0, window=replay) + state = recover.load(recover.STATE, {}) + self.assertNotIn("progressAt", state) + self.assertNotIn("speciesAt", state) # the replayed catch was protected before the reset + self.assertEqual(state["progressSeen"], seen) + self.confirm(T0) + self.assertEqual(self.acts, [("reset", 11)]) + + def test_a_reward_not_seen_before_starts_the_ladder_over_and_a_new_species_is_protected(self): + recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 7200, + "progressSeen": ["area:AREA 59"]}) + self.tick(T0 - 3000, suspected=0, + window={"progress": {"lasting": 2, "species": 1, "keys": ["area:AREA 59", "pokedex:OWNED #41"]}}) + state = recover.load(recover.STATE, {}) + self.assertEqual((state["progressAt"], state["speciesAt"]), (T0 - 3000, T0 - 3000)) + self.assertEqual(state["progressSeen"], ["area:AREA 59", "pokedex:OWNED #41"]) + self.assertIn("flysim restarted", self.confirm(T0)) + history = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()] + self.assertIn("progress since the last step", [event.get("why") for event in history]) + + def test_a_catch_while_the_fly_stays_flagged_does_not_start_the_ladder_over(self): + acted = T0 - recover.HOLD - 600 + recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": acted, + "clearAt": acted + 60}) + catch = {"progress": {"lasting": 1, "species": 1, "keys": ["pokedex:OWNED #41"]}} + self.assertIn("flysim restarted", self.confirm(T0, window=catch)) + self.assertEqual(self.acts, [("restart", None)]) # the rung-11 reset, held for the new species + self.assertEqual(recover.load(recover.STATE, {}).get("level"), 2) + + def test_without_reward_names_the_counts_still_count(self): + recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 7200, + "progressSeen": ["pokedex:OWNED #8"]}) + self.tick(T0 - 3000, suspected=0, window={"progress": {"lasting": 1, "species": 1}}) + state = recover.load(recover.STATE, {}) + self.assertEqual((state["progressAt"], state["speciesAt"]), (T0 - 3000, T0 - 3000)) + + def test_the_names_remembered_are_bounded(self): + recover.write_json(recover.STATE, {"progressSeen": [f"area:AREA {n}" for n in range(recover.SEEN)]}) + self.tick(T0, suspected=0, window={"progress": {"lasting": 1, "species": 0, "keys": ["area:AREA X"]}}) + seen = recover.load(recover.STATE, {})["progressSeen"] + self.assertEqual((len(seen), seen[0], seen[-1]), (recover.SEEN, "area:AREA 1", "area:AREA X")) + # a malformed list is ignored item by item + self.tick(T0 + 300, suspected=0, window={"progress": {"lasting": 1, "species": 0, "keys": [{}, ["x"], 3]}}) + self.assertEqual(recover.load(recover.STATE, {})["progressSeen"][-1], "area:AREA X") + + def test_restarts_stay_a_hold_apart_after_the_ladder_starts_over(self): + recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [], "actedAt": T0 - 3600, + "lastAction": "restart"}) + self.tick(T0 - 2000, suspected=0, window={"progress": {"lasting": 1, "species": 0, "keys": ["area:AREA 60"]}}) + self.assertIn("last restart was under three hours ago", self.confirm(T0)) + self.assertEqual(self.acts, []) + self.assertIn("flysim restarted", self.tick(T0 - 3600 + recover.HOLD)) + + def test_a_failed_reset_does_not_block_its_archive(self): + recover.act.side_effect = lambda action, target: self.acts.append((action, target)) or False + recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0}) + self.assertIn("reset FAILED", self.confirm(T0)) + state = recover.load(recover.STATE, {}) + self.assertNotIn("lastReset", state) + self.assertEqual((state["level"], len(state["resets"])), (3, 1)) # it still climbed and spent the reset + def test_quiet_hours_start_the_ladder_over(self): recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "actedAt": 0, "lastSuspectedAt": T0 - recover.QUIET - 1}) @@ -268,6 +405,139 @@ BUILD = "lif-1ms-f64-v2/pokered-unique8-v7/abc/fly-kc-mbon-rstdp-v2" @unittest.skipIf(recover.os.geteuid() == 0, "the wrapper ignores test overrides as root") +class ClosedLoopTests(unittest.TestCase): + """Row 70 review L1: a trap no restart clears, every reset replaying it exactly (closed loop).""" + M = 60 + R11 = dict(events=[(20, "pokedex"), (21, "trainer"), (35, "trainer"), (44, "area"), (46, "milestone"), + (52, "pokedex")], trap=58, rank_after=[(46, 12)], start_rank=11) + R12 = dict(events=[(7, "pokedex")], trap=12, rank_after=[], start_rank=12) + R10 = dict(events=[(30, "area"), (60, "milestone"), (90, "milestone"), (100, "pokedex")], trap=110, + rank_after=[(60, 11), (90, 12)], start_rank=10) + + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + root = Path(self.temp.name) + for name, value in (("REPORT", "loop.json"), ("STATE", "s.json"), ("HISTORY", "h.jsonl"), + ("NOTICE", "n.json")): + patcher = patch.object(recover, name, root / value) + patcher.start() + self.addCleanup(patcher.stop) + for name, value in (("restorable_rungs", lambda: {9, 10, 11, 12}), ("verdict", lambda report: (None, None))): + patcher = patch.object(recover, name, value) + patcher.start() + self.addCleanup(patcher.stop) + self.env = patch.dict("os.environ", {}, clear=False) + self.env.start() + self.addCleanup(self.env.stop) + for key in ("FLY_LOOP_ROUTER_URL", "FLY_LOOP_MODELS", "FLY_LOOP_MODEL", "FLY_LOOP_ROUTER_KEY"): + recover.os.environ.pop(key, None) + + def simulate(self, archives, hours, species_before=None, names=True): + """The fly is trapped from T0; returns [(hours, action, target)]. A reset replays its archive. + + Every lasting reward has a name (window.progress.keys): the fly earned each archive's rewards + once before the trap, in clear probes the ladder saw, and a replay pays the same names again. + """ + M = self.M + sim = dict(events=[(T0 - species_before * M, "pokedex", "pokedex:pre")] if species_before else [], + rank=12, rank_changes=[], trap_from=T0, now=T0, acts=[]) + history = [f"{k}:{rung}/{o}" for rung, a in sorted(archives.items()) for o, k in a["events"]] + for i in range(0, len(history), 3) if names else (): + recover.REPORT.write_text(json.dumps({ + "at": T0 - 86400 + i * 300, "suspected": 0, "action": "none", "milestone": {"rank": 12}, + "window": {"progress": {"lasting": 3, "species": 0, "keys": history[i:i + 3]}}})) + recover.run(now=T0 - 86400 + i * 300 + 5, sleep=lambda s: None) + seen = recover.load(recover.STATE, {}).get("progressSeen") + + def act(action, target): + sim["acts"].append((sim["now"], action, target)) + if action == "reset": + a = archives[target] + sim["rank"] = a["start_rank"] + sim["events"] = [(sim["now"] + o * M, k, f"{k}:{target}/{o}") for o, k in a["events"]] + sim["rank_changes"] = [(sim["now"] + o * M, r) for o, r in a["rank_after"]] + sim["trap_from"] = None if a["trap"] is None else sim["now"] + a["trap"] * M + return True + + recover.write_json(recover.STATE, dict({"bestRank": 12, "rank": 12, "level": 0}, + **({"progressSeen": seen} if seen else {}))) + recover.HISTORY.write_text("") + with patch.object(recover, "act", side_effect=act): + t = T0 + while t < T0 + hours * 3600: + for change in list(sim["rank_changes"]): + if change[0] <= t: + sim["rank"] = change[1] + sim["rank_changes"].remove(change) + win = [(k, name) for at, k, name in sim["events"] if t - 600 <= at <= t] + trapped = sim["trap_from"] is not None and t - sim["trap_from"] >= 600 + recover.REPORT.write_text(json.dumps({ + "at": t, "suspected": 1 if trapped else 0, "action": "none", "reason": "dominant", + "sequence": ["NEXT"], "milestone": {"rank": sim["rank"], "label": "X"}, "map": 59, + "window": {"progress": dict({ + "lasting": sum(k in ("pokedex", "area", "trainer", "badge", "milestone") for k, _ in win), + "species": sum(k == "pokedex" for k, _ in win)}, + **({"keys": [name for _, name in win]} if names else {}))}})) + sim["now"] = t + 5 + recover.run(now=t + 5, sleep=lambda s: None) + t += 300 + return [((at - T0) / 3600, action, target) for at, action, target in sim["acts"]] + + def test_a_restart_proof_trap_is_reset_in_bounded_time_and_again(self): + acts = self.simulate({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, 72, species_before=6) + resets = [a for a in acts if a[1] == "reset"] + # v0.7.0 resets again at 24.75 h; the ladder is no worse, and keeps resetting + self.assertTrue(resets and resets[0][0] <= 25, acts) + self.assertTrue(len([a for a in resets if a[0] <= 25]) >= 1, acts) + self.assertTrue(len(resets) >= 3, acts) + gaps = [b[0] - a[0] for a, b in zip(resets, resets[1:])] + self.assertTrue(all(g <= 25 for g in gaps), acts) + # the first step is a restart; the catch stays protected for 2 h + self.assertEqual(acts[0][1], "restart") + self.assertTrue(all(a[0] >= 2 - 0.2 for a in resets[:1]), acts) + + def test_the_held_reset_is_the_rung_12_one_not_a_deeper_rung(self): + acts = self.simulate({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, 24, species_before=6) + self.assertEqual([a[2] for a in acts if a[1] == "reset"][:1], [12], acts) + + def test_a_trap_the_rung_12_archive_escapes_ends_there(self): + clean = dict(self.R12, trap=None) + acts = self.simulate({11: self.R11, 12: clean, 10: self.R10, 9: self.R10}, 24, species_before=6) + self.assertEqual([a[1:] for a in acts if a[1] == "reset"], [("reset", 12)], acts) + self.assertEqual(len(acts), 2, acts) + + def test_without_a_catch_the_ladder_resets_early(self): + acts = self.simulate({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, 24) + self.assertLessEqual(next(a[0] for a in acts if a[1] == "reset"), 1, acts) + + def test_a_trap_only_the_rung_below_escapes_is_reached_promptly(self): + # review r2 N1: the rung-12 replay re-earns progress, then traps; only rung 11 escapes. + # v0.7.0 reset to 11 at 2.08 h; holding the level on the archive just used took 24.75 h, and + # counting the replay's area and species as progress took 5.58 h (6.83 h after a catch). + late12 = dict(events=[(30, "area"), (40, "pokedex")], trap=60, rank_after=[], start_rank=12) + archives = {11: dict(self.R11, trap=None), 12: late12, 10: self.R10, 9: self.R10} + for species_before, bound in ((None, 2.1), (6, 2.1 + 2)): # a catch 6 min before the trap: +2 h at most + with self.subTest(species_before=species_before): + self.setUp() + acts = self.simulate(archives, 96, species_before=species_before) + resets = [a for a in acts if a[1] == "reset"] + self.assertEqual([a[2] for a in resets], [12, 11], acts) + self.assertLessEqual(resets[-1][0], bound, acts) + + def test_restarts_are_a_hold_apart_in_every_closed_loop(self): + late12 = dict(events=[(30, "area"), (40, "pokedex")], trap=60, rank_after=[], start_rank=12) + for archives in ({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, + {11: self.R11, 12: late12, 10: self.R10, 9: self.R10}): + for species_before in (None, 6): + self.setUp() + acts = self.simulate(archives, 72, species_before=species_before) + restarts = [a[0] for a in acts if a[1] == "restart"] + self.assertTrue(all(b - a >= 3 - 1e-6 for a, b in zip(restarts, restarts[1:])), acts) + resets = [a[0] for a in acts if a[1] == "reset"] + self.assertTrue(all(sum(1 for y in resets if x <= y < x + 24) <= 2 for x in resets), acts) + + class WrapperTests(unittest.TestCase): """infra/bin/fly-loop-reset against a fake flysim, systemctl, reset tool and archives."""