File size: 7,325 Bytes
5463b45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
"""Run up to three tries of Micro Park inside one session.

A try ends when the engine settles the two-year objective — the park value
target is reached, or month 16 passes below it — or when the park stops running.
After a failed try this process archives that try's evidence, throws the park
away and starts the next try from the shipped seed, so every try begins from the
same empty plot with the same cash and loan. A completed try, or the last try,
is left on screen for the agent and the verifier.

Only this process resets the park. The agent has no shell, and the controller
blocks the in-game actions that could reload or re-date a scenario, so a try can
never be replayed from inside the game.
"""
import json
import os
import shutil
import signal
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path

TRIES = int(os.environ.get("T37_TRIES", "3"))
AUDIT = Path(os.environ["T37_AUDIT_DIR"])
STATE = Path("/logs/artifacts/tries")
HOME = Path(os.environ.get("HOME", "/home/rct2"))
PROFILE = HOME/".config/OpenRCT2"
SEED = Path("/opt/micropark/micropark-seed.park")
LIB = Path("/usr/local/lib/t37")
# The agent's own notes, outside the game profile so a reset cannot erase them.
NOTES = Path(os.environ.get("T37_NOTES_DIR", "/notes"))
# Seconds a settled try stays on screen before the park is taken away, so the
# outcome message and the final figures can be read and saved.
FAILURE_GRACE = 90
# A completed run is not reset at all; this is only time for the agent to read
# the result and report it. The controller has already saved the finished park.
COMPLETION_GRACE = 180
# The controller reports state every five seconds. A much longer silence with a
# live engine means the park is no longer running (quit to the title screen).
HEARTBEAT_TIMEOUT = 180
# A try that never reports at all is a broken engine, not a park. Give up on it
# rather than holding the whole session open with nothing playing.
STARTUP_TIMEOUT = 600
POLL = 2


def now():
    return datetime.now(timezone.utc).isoformat()


def mark(record):
    """Append a supervisor record to the same audit stream as the engine's."""
    AUDIT.mkdir(parents=True, exist_ok=True)
    record["schema"] = 1
    record["observed_at"] = now()
    with (AUDIT/"game.jsonl").open("a") as audit:
        audit.write(json.dumps(record)+"\n")


def publish(number, history):
    """Record which try is live, for collect.py and the verifier."""
    STATE.mkdir(parents=True, exist_ok=True)
    temp = STATE/"current.tmp"
    temp.write_text(json.dumps({"try": number, "tries": TRIES,
                                "history": history, "updated_at": now()}, indent=2)+"\n")
    temp.replace(STATE/"current.json")


def install_plugin(number):
    """Give the controller its try number; it has no way to read a file."""
    target = PROFILE/"plugin/t37-observer.js"
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(f"var T37_TRY={number},T37_TRIES={TRIES};\n"
                      + (LIB/"observer.js").read_text())


def clear_park():
    """Discard the previous try's park so the next one starts from the seed.

    Only paths inside the game profile are touched. The agent's notes live in
    /notes precisely so that carrying learnings into the next try is possible.
    """
    for name in ("save", "screenshot"):
        shutil.rmtree(PROFILE/name, ignore_errors=True)
        (PROFILE/name).mkdir(parents=True, exist_ok=True)


def notes_size():
    """How much is in the notepad now, measured at the start and end of a try."""
    try:
        return sum(path.stat().st_size for path in NOTES.rglob("*") if path.is_file())
    except OSError:
        return None


def notes_seed_size():
    """How much the agent was handed, so the grader can subtract the seed.

    Read from the image's own copy of the seed rather than from /notes, which the
    agent may already have written to by the time a later try starts.
    """
    try:
        return (LIB/"notes-seed.txt").stat().st_size
    except OSError:
        return None


def collect(number):
    subprocess.run([sys.executable, str(LIB/"collect.py"), "--screenshot"],
                   env={**os.environ, "T37_TRY": str(number)}, check=False)


def run_try(number, arguments):
    """Play one try; return the child and why the try ended."""
    outcome = STATE/f"try-{number}-outcome"
    heartbeat = STATE/f"try-{number}-heartbeat"
    for path in (outcome, heartbeat):
        path.unlink(missing_ok=True)
    child = subprocess.Popen(
        [sys.executable, str(LIB/"game-process.py"), str(SEED), *arguments,
         "--rct2-data-path", "/opt/rct2-assets",
         "--openrct2-data-path", "/opt/OpenRCT2/data"],
        env={**os.environ, "T37_TRY": str(number),
             "T37_TRY_OUTCOME": str(outcome), "T37_TRY_HEARTBEAT": str(heartbeat)})
    started = time.time()
    while True:
        # An outcome the engine reported stands even if the engine then died,
        # so a crash on the way out cannot erase a settled two-year try.
        if outcome.exists():
            return child, outcome.read_text().strip() or "objective_failed"
        if child.poll() is not None:
            return child, "engine_exit"
        if heartbeat.exists():
            if time.time()-heartbeat.stat().st_mtime > HEARTBEAT_TIMEOUT:
                return child, "park_closed"
        elif time.time()-started > STARTUP_TIMEOUT:
            return child, "engine_stalled"
        time.sleep(POLL)


def stop(child):
    if child.poll() is not None:
        return
    child.terminate()
    try:
        child.wait(timeout=30)
    except subprocess.TimeoutExpired:
        child.kill()
        child.wait()


def main():
    history = []
    child = None

    def shutdown(*_):
        if child is not None:
            stop(child)
        sys.exit(0)

    signal.signal(signal.SIGTERM, shutdown)
    signal.signal(signal.SIGINT, shutdown)
    for number in range(1, TRIES+1):
        clear_park()
        install_plugin(number)
        publish(number, history)
        mark({"kind": "try_started", "try": number, "tries": TRIES,
              "previous": history, "notes_bytes": notes_size(),
              "notes_seed_bytes": notes_seed_size()})
        child, reason = run_try(number, sys.argv[1:])
        last = number == TRIES
        complete = reason == "objective_complete"
        if complete:
            time.sleep(COMPLETION_GRACE)
        elif reason == "objective_failed" and not last:
            # Leave the failed park up long enough to read the final figures.
            time.sleep(FAILURE_GRACE)
        collect(number)
        history = history+[{"try": number, "reason": reason}]
        mark({"kind": "try_ended", "try": number, "tries": TRIES, "reason": reason,
              "final": bool(complete or last), "notes_bytes": notes_size()})
        publish(number, history)
        if complete or last:
            break
        stop(child)
    mark({"kind": "campaign_finished", "tries_played": len(history),
          "tries": TRIES, "history": history})
    # The last park stays on screen: the agent reports on it and the verifier
    # screenshots it. Exiting here would stop the container.
    if child is not None:
        sys.exit(child.wait())


if __name__ == "__main__":
    main()