diff --git a/infra/bin/fly-loop-recover b/infra/bin/fly-loop-recover index a528cad..28d10d7 100755 --- a/infra/bin/fly-loop-recover +++ b/infra/bin/fly-loop-recover @@ -4,9 +4,10 @@ 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, makes lasting -progress after the last step, or has been quiet for QUIET seconds. A milestone reset -never erases a species 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 +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 @@ -34,6 +35,7 @@ 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 @@ -249,13 +251,40 @@ def run(now=None, sleep=time.sleep, clock=None): # 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 {} - if type(at) is int and 0 <= now - at <= 600 and type(progress) is dict: - if type(progress.get("lasting")) is int and progress["lasting"] > 0: + 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 type(progress.get("species")) is int and progress["species"] > 0: + if species > 0: state["speciesAt"] = max(at, state.get("speciesAt", 0)) - if level and state.get("progressAt", 0) > state.get("actedAt", 0) + SETTLE: + 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 @@ -297,10 +326,13 @@ def run(now=None, sleep=time.sleep, clock=None): held_reset = protected if protected: action, target = "restart", None - if action == "restart" and level and now - acted < HOLD: + # 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) 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", @@ -335,6 +367,8 @@ def run(now=None, sleep=time.sleep, clock=None): 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 010ffa4..6d11c8c 100755 --- a/infra/bin/fly-watchdog +++ b/infra/bin/fly-watchdog @@ -888,7 +888,7 @@ 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 US progress US species +# 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 @@ -898,9 +898,12 @@ loop_macro_stream() { # 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. 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 +# `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 @@ -909,20 +912,27 @@ 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 == "milestone" { rms[++nr] = $1 + 0; rkind[nr] = "milestone"; 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\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; progress = 0; species = 0 + fights = 0; wins = 0; progress = 0; species = 0; keys = ""; nkeys = 0 for (q = 1; q <= nr; q++) if (rms[q] >= from) { - if (rkind[q] == "milestone") { progress++; continue } + 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" || rkind[q] == "area" || rkind[q] == "trainer" || rkind[q] == "badge") progress++ if (rkind[q] == "pokedex") species++ } for (i = 1; i <= n; i++) { @@ -958,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\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, progress, species + k, refused, blocked, timeout, done, rewards, fights, wins, progress, species, keys }' } @@ -1018,10 +1028,10 @@ 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 progress species + 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 progress species <<< "$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}" @@ -1142,6 +1152,7 @@ check_loop() { --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" \ @@ -1173,7 +1184,8 @@ check_loop() { rewards: $rewards, fights: $fights, wins: $wins, - progress: { lasting: $progress, species: $species }, + 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 64788bf..b0e7d45 100644 --- a/infra/docs/loop-recovery.md +++ b/infra/docs/loop-recovery.md @@ -16,15 +16,25 @@ 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. + 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 a probe's window shows lasting progress more than - 20 minutes after the last step (row 70). Lasting progress is the watchdog's `window.progress`: - a new rung, a species owned for the first time, a map entered for the first time, or a trainer - or badge beaten. The run pays each of these once, so a ring cannot earn them twice. A trap that - follows real progress is a new trap, and it starts again from a restart. -- **Protected catches:** a milestone reset never erases a species owned in the last two hours - (`PROTECT`, from `window.progress.species`). Within that window the step is a restart, spaced by + 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. @@ -33,7 +43,8 @@ a ladder one step per trap that outlives the previous step: 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 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 f57e1c6..9f252b3 100644 --- a/infra/docs/macros-traps.md +++ b/infra/docs/macros-traps.md @@ -3664,9 +3664,10 @@ trap is in the game state, not the ledgers, so neither a restart nor a replay cl | # | 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). Lasting progress more than `SETTLE` after the step returns the ladder to level 0 | +| 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 six hours of a species owned, a reset is a restart (held three hours apart) | +| 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): @@ -3679,4 +3680,10 @@ Ladder replay of the day (the same logs and the same start state, base against b - 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 389e4c2..4b1f94c 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -2037,6 +2037,15 @@ LPCAT 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. diff --git a/infra/tests/test_loop_recover.py b/infra/tests/test_loop_recover.py index cd072f0..fc7c1a1 100644 --- a/infra/tests/test_loop_recover.py +++ b/infra/tests/test_loop_recover.py @@ -186,6 +186,74 @@ class RecoveryTests(unittest.TestCase): 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}) @@ -365,23 +433,36 @@ class ClosedLoopTests(unittest.TestCase): 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): - """The fly is trapped from T0; returns [(hours, action, target)]. A reset replays its archive.""" + 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")] if species_before else [], + 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) for o, k in a["events"]] + 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, {"bestRank": 12, "rank": 12, "level": 0}) + 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: @@ -389,14 +470,15 @@ class ClosedLoopTests(unittest.TestCase): if change[0] <= t: sim["rank"] = change[1] sim["rank_changes"].remove(change) - win = [k for at, k in sim["events"] if t - 600 <= at <= t] + 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": { - "lasting": sum(k in ("pokedex", "area", "trainer", "badge", "milestone") for k in win), - "species": sum(k == "pokedex" for k in win)}}})) + "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 @@ -431,14 +513,29 @@ class ClosedLoopTests(unittest.TestCase): 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. + # 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) - clean11 = dict(self.R11, trap=None) - acts = self.simulate({11: clean11, 12: late12, 10: self.R10, 9: self.R10}, 96) - 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], 7, acts) # 6.83 h with the 2 h protection (was 2.08 h in v0.7.0) - self.assertLess([a[2] for a in resets].count(12), 2, acts) + 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):