File size: 6,375 Bytes
adf68aa
 
 
 
 
 
 
 
5bac4c2
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
5bac4c2
 
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bac4c2
adf68aa
 
 
5bac4c2
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
adf68aa
 
 
 
 
 
 
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Container-free smoke of the world: python world/scripts/smoke-local.py [--sidecar]

Starts PybotWorld from world/ with plain Python on a free port, backed by a FAKE
in-process hub (a local bare git repo + LocalHub, injected as `repository`; the shipped code still
defaults to the real Hub). Checks /healthz, the token (and a per-agent one), /manifest's tools and
one run_bot call.
With --sidecar, the bot sandbox runs as a 2nd local process (`sandbox.py serve`, given only its
token) and run_bot must succeed through it. Writes nothing outside a temp dir and makes no network
calls beyond localhost. Needs the deps in requirements.txt, legion (README) and git.
"""
import json
import os
import socket
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.request
from pathlib import Path

SRC = Path(__file__).resolve().parent.parent  # world/
sys.path.insert(0, str(SRC))
TOOLS = {"open_pr", "review_pr", "merge_pr", "close_pr", "list_prs", "get_pr", "record_verdict",
         "verdicts", "run_bot", "world_status"}
TOKEN = "smoke-token"


def git(path, *args):
    return subprocess.run(["git", "-C", str(path), *args], check=True, capture_output=True,
                          text=True).stdout.strip()


class LocalHub:  # tests/test_pybot.py's fake: PRs are refs/pr/N in the bare remote
    def __init__(self, remote):
        self.remote, self.n = remote, 0

    def open(self, title, description):
        self.n += 1
        git(self.remote, "update-ref", f"refs/pr/{self.n}", "main")
        return self.n

    def ready(self, pr): pass
    def comment(self, pr, text): pass
    def close(self, pr, comment): pass
    def merge(self, pr, comment): raise NotImplementedError("not used by this smoke")


def call(port, method, path, body=None, token=TOKEN, agent="smoke"):
    req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", method=method,
                                 data=None if body is None else json.dumps(body).encode(),
                                 headers={"Content-Type": "application/json", "X-Legion-Agent": agent,
                                          **({"X-World-Token": token} if token else {})})
    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            return r.status, json.loads(r.read())
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read() or b"null")


def free_port():
    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


def start_sidecar(tmp):
    """sandbox.py serve with nothing but its token and PORT; returns (proc, log)."""
    port, log = free_port(), tmp / "sidecar.log"
    proc = subprocess.Popen([sys.executable, str(SRC / "sandbox.py"), "serve"], cwd=SRC,
                            stderr=log.open("wb"), env={"PYBOT_SANDBOX_TOKEN": "sidecar-token",
                                                     "PORT": str(port)})
    for _ in range(100):
        try:
            socket.create_connection(("127.0.0.1", port), timeout=1).close()
            break
        except OSError:
            assert proc.poll() is None, log.read_text()
            time.sleep(0.1)
    os.environ.update(PYBOT_SANDBOX_URL=f"http://127.0.0.1:{port}", PYBOT_SANDBOX_TOKEN="sidecar-token")
    print(f"ok  sidecar: sandbox.py serve on 127.0.0.1:{port}")
    return proc, log


def main(sidecar=False):
    import uvicorn
    from pybot import PybotWorld
    from repository import Repository

    from legion.world.server import create_app

    tmp = Path(tempfile.mkdtemp(prefix="pybot-smoke-"))
    os.environ.update(PYBOT_REPO="smoke/never-used", HF_TOKEN="")  # the fake hub ignores both
    seed = tmp / "seed"
    subprocess.run(["cp", "-r", str(SRC / os.environ.get("PYBOT_SEED_DIR", "seed")), str(seed)], check=True)
    git(seed, "init", "-q", "-b", "main")
    git(seed, "add", ".")
    git(seed, "-c", "user.name=seed", "-c", "user.email=seed@legion.invalid", "commit", "-qm", "seed")
    remote = tmp / "remote.git"
    git(tmp, "clone", "-q", "--bare", str(seed), str(remote))
    repo = Repository(tmp / "ws" / "repo.git", str(remote))
    repo.hub = LocalHub(remote)
    world = PybotWorld(tmp / "ws", repo)

    port = free_port()
    if sidecar:
        sidecar_proc, sidecar_log = start_sidecar(tmp)
    server = uvicorn.Server(uvicorn.Config(create_app(world, TOKEN), host="127.0.0.1", port=port,
                                           log_level="warning"))
    threading.Thread(target=server.run, daemon=True).start()
    for _ in range(100):
        try:
            if call(port, "GET", "/healthz", token=None) == (200, {"status": "ready"}):
                break
        except OSError:
            pass
        time.sleep(0.1)
    else:
        sys.exit("FAIL: /healthz never said ready")
    print(f"ok  GET /healthz on 127.0.0.1:{port}: ready")

    assert call(port, "GET", "/manifest", token="wrong")[0] == 401
    print("ok  GET /manifest with a wrong X-World-Token: 401")
    from legion.world.protocol import agent_token
    own = agent_token(TOKEN, "smoke")
    assert call(port, "GET", "/manifest", token=own)[0] == 200
    assert call(port, "GET", "/manifest", token=own, agent="other")[0] == 401
    print("ok  GET /manifest with the agent's own token: 200; as another agent: 401")
    status, m = call(port, "GET", "/manifest")
    names = {t["name"] for t in m["tools"]}
    assert status == 200 and names == TOOLS, (status, names)
    print(f"ok  GET /manifest: {m['name']} {m['version']}, {len(names)} tools: {', '.join(sorted(names))}")

    status, r = call(port, "POST", "/tools/run_bot",
                     {"args": {"ref_or_path": "main", "lines": ["Hello"]}})
    ran = status == 200 and r["result"]["ok"]  # False where unshare is not permitted (README)
    print(f"{'ok ' if ran else 'note'} POST /tools/run_bot main ['Hello']: {status} "
          f"{json.dumps(r)[:300]}")
    server.should_exit = True
    if sidecar:
        sidecar_proc.terminate()
        sidecar_proc.wait(10)
        served = '"POST /run HTTP/1.1" 200' in sidecar_log.read_text()
        assert ran and served, f"run_bot did not succeed through the sidecar: {sidecar_log.read_text()[-600:]}"
        print("ok  run_bot went through the sidecar (its log: POST /run 200)")


if __name__ == "__main__":
    main("--sidecar" in sys.argv[1:])