File size: 17,243 Bytes
2419253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
"""code_store - Oracle7's store of the functions it has composed, on the Tree of Life spine (12.0, CODE_SPEC C7).

KEPT       a function composed for a project is kept only after the project's own check passed with it (the law decides, not
           the composer). Kept with its evidence: the examples it was made from, its read-back, the project and test files,
           the shapes it takes and gives, the words of its name and of the request, the moves it is built from, sha256.
           Pure functions only (no file, process or network call): what is kept is what any later goal may call.
ON THE SPINE   every kept function is an item spelled as a walk over the 22 paths (o7spine_v1's codebook and walks, as
           flash_tol102 spells its store). Its facts are bound to it: bind(walk(key), walk(value)) for each shape it takes
           (by place and in any place), the shape it gives, its arity, each word, each move. One matrix, one row per
           function.
LIT        a goal's own facts (the shapes of its examples, the shape of its answers, its arity, the words of its name and of
           the request) are the cue: one matrix product over the whole store gives every function's resonance, adding where
           facts meet. Only the lit functions become moves in that goal's search, so the search is one size however large
           the store grows; cleanup is the 22-way choice per position, never against the store's size.
THE LAW    lit is a proposal. A lit function is used only where its shapes fit, its source passes the check below, and the
           composed program reads back and passes the project's check.
CHECK      a kept source is called only if it is one function, with no import, no dunder attribute, and names drawn only
           from its parameters, its own comprehension names, the composer's modules and builtins, and other kept functions.
No language model; numpy and the standard library."""
from __future__ import annotations

import ast
import builtins
import hashlib
import json
import os
import re
import sys
import time
from pathlib import Path

WB = Path(__file__).resolve().parent
for _d in (WB / "swarm",):
    if str(_d) not in sys.path:
        sys.path.insert(0, str(_d))

MODULES = {"math", "statistics", "collections", "functools", "itertools", "re", "hashlib", "base64", "hmac", "json"}
IMPURE = {"open", "print", "input", "exec", "eval", "compile", "__import__", "exit", "quit", "breakpoint", "setattr",
          "delattr", "globals", "locals", "vars", "getattr"}
TOP = 24


def store_path():
    if os.environ.get("ORACLE7_CODE_STORE"):
        return Path(os.environ["ORACLE7_CODE_STORE"])
    if os.environ.get("ORACLE7_STATE"):
        return Path(os.environ["ORACLE7_STATE"]) / "code_parts.jsonl"
    return WB / "local" / "code_parts.jsonl"


def _beside(name):
    """a file kept beside the store: its retirements, its holes, its dreams"""
    return store_path().with_name(name)


def retired_ids():
    p = _beside("code_retired.jsonl")
    out = set()
    if p.is_file():
        for ln in p.read_text(encoding="utf-8").splitlines():
            try:
                out.add(json.loads(ln)["id"])
            except Exception:  # noqa: BLE001
                continue
    return out


def load(with_retired=False):
    p = store_path()
    out, seen = [], set() if with_retired else retired_ids()   # a retired function stays in the file (replay reaches it)
    if p.is_file():
        for ln in p.read_text(encoding="utf-8").splitlines():
            try:
                e = json.loads(ln)
            except Exception:  # noqa: BLE001
                continue
            if e.get("id") and e["id"] not in seen:
                seen.add(e["id"])
                out.append(e)
    return out


def checked_source(src, name, known):
    """None when the source is one function built only from the composer's names; else the reason it is not called"""
    try:
        tree = ast.parse(src)
    except SyntaxError as e:
        return "does not parse: %s" % e
    fns = [n for n in tree.body if isinstance(n, ast.FunctionDef)]
    if len(tree.body) != 1 or len(fns) != 1 or fns[0].name != name:
        return "is not one function called %s" % name
    fn = fns[0]
    allowed = set(MODULES) | set(dir(builtins)) | set(known) | {a.arg for a in fn.args.args}
    for n in ast.walk(fn):
        if isinstance(n, (ast.Import, ast.ImportFrom, ast.Global, ast.Nonlocal, ast.While, ast.Try)) and \
                not isinstance(n, (ast.While, ast.Try)):
            return "imports or reaches outside itself"
        if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store):
            allowed.add(n.id)
        if isinstance(n, ast.arg):
            allowed.add(n.arg)
    for n in ast.walk(fn):
        if isinstance(n, ast.Attribute) and n.attr.startswith("__"):
            return "reaches a dunder attribute"
        if isinstance(n, ast.Name) and n.id not in allowed:
            return "names %s, which is not one of the composer's" % n.id
        if isinstance(n, ast.Name) and n.id in IMPURE:
            return "calls %s" % n.id
    return None


def entry_for(r, g, project, test_files):
    """the record kept for a composed function, or None when it is not kept (impure, or not confirmed)"""
    src = r.get("source") or ""
    if not src or not r.get("confirmed"):
        return None
    if checked_source(src, g["name"], set(r.get("uses") or [])) is not None:
        return None
    deps = dict(r.get("deps") or {})
    if any(u not in deps for u in (r.get("uses") or [])):
        return None                                   # it calls something whose exact source is not kept with it
    sha = hashlib.sha256((g["name"] + "\n" + src).encode()).hexdigest()
    return {"id": sha[:16], "sha256": sha, "name": g["name"], "source": src, "params": list(g["params"]), "deps": deps,
            "imports": list(r.get("imports") or []), "uses": list(r.get("uses") or []),
            "in_shapes": r.get("in_shapes") or [], "out_shape": r.get("out_shape"), "words": r.get("words") or [],
            "moves": [str(m) for m in (r.get("moves") or [])][:40], "examples": r.get("evidence") or [],
            "read_back": r.get("read_back"), "project": project, "test_files": list(test_files or []), "t": time.time()}


def keep(entries, deps_from=()):
    """append the confirmed functions not already kept; -> the ones added. A function composed in the same job and called by
    another is kept too (its record carries its own evidence), so every dependency is in the store by its sha"""
    have = {e["id"] for e in load()}
    add = [e for e in entries if e and e["id"] not in have]
    if add:
        p = store_path()
        p.parent.mkdir(parents=True, exist_ok=True)
        with open(p, "a", encoding="utf-8") as f:
            for e in add:
                f.write(json.dumps(e) + "\n")
    return add


def retire(ids, why):
    """kept functions taken out of reuse, each with the receipt why (12.5 C32): a kept function is trusted on the evidence it
    was kept with, and a later check that failed with it inside is evidence too. It stays in the file (replay reaches it);
    -> the ids newly retired"""
    have = retired_ids()
    new = [i for i in dict.fromkeys(ids) if i and i not in have]
    if new:
        p = _beside("code_retired.jsonl")
        p.parent.mkdir(parents=True, exist_ok=True)
        with open(p, "a", encoding="utf-8") as f:
            for i in new:
                f.write(json.dumps({"id": i, "receipt": str(why)[:400], "t": time.time()}) + "\n")
    return new


# ---------------------------------------------------------------- holes and the night
def note_hole(goal, gap, project=None, cause=None, spent=None, work=None):
    """a code goal the composer declined, kept as a hole for the night: its name, its examples, why, what stopped it
    (cause: time, memory, stopped, searched = every program within the bound tried, evidence = the examples do not
    decide) and the seconds it was given (12.5 C33)"""
    ev = []
    for a, o, _t in goal.get("examples") or []:
        try:
            json.dumps([list(a), o])
            ev.append([list(a), o])
        except Exception:  # noqa: BLE001
            pass
    if not ev:
        return
    p = _beside("code_holes.jsonl")
    p.parent.mkdir(parents=True, exist_ok=True)
    key = hashlib.sha256(json.dumps([goal["name"], ev], sort_keys=True).encode()).hexdigest()[:16]
    try:                                              # 12.5 step 5: the code hole is one kind of the one hole record too
        import holes as _holes
        _holes.record("code", "composing %s: %s" % (goal["name"], str(gap)[:300]), cause=cause or "evidence",
                      takes=["one more example of %s, or a narrower description" % goal["name"]], spent=spent,
                      route="compose", extra={"name": goal["name"], "code_hole": key, "work": work})
    except Exception:  # noqa: BLE001
        pass
    with open(p, "a", encoding="utf-8") as f:
        f.write(json.dumps({"id": key, "name": goal["name"], "params": list(goal.get("params") or []), "examples": ev,
                            "gap": str(gap)[:400], "project": project, "cause": cause or "evidence", "spent": spent, "work": work,
                            "t": time.time()}) + "\n")


def _holes():
    p = _beside("code_holes.jsonl")
    out = {}
    if p.is_file():
        for ln in p.read_text(encoding="utf-8").splitlines():
            try:
                h = json.loads(ln)
                out[h["id"]] = h
            except Exception:  # noqa: BLE001
                continue
    return list(out.values())


REPLAY = """
import json, sys
job = json.load(open(sys.argv[1]))
ns = {}
for m in job["imports"]:
    ns[m.split(".")[0]] = __import__(m)
for src in job["deps"] + [job["source"]]:
    exec(compile(src, "kept", "exec"), ns)
fn = ns[job["name"]]
out = []
for args, want in job["examples"]:
    try:
        got = fn(*args)
        out.append(json.dumps(got, sort_keys=True) == json.dumps(want, sort_keys=True) or
                   (isinstance(got, float) and isinstance(want, (int, float)) and abs(got - want) < 1e-9))
    except Exception:
        out.append(False)
print(json.dumps(out))
"""


def replay(e, by_sha):
    """a kept function re-run on its own evidence in a separate interpreter (with exactly the dependencies it was kept
    with): -> None when every example still holds, else the receipt why not"""
    import subprocess
    import tempfile
    deps, seen = [], set()

    def add(x):
        for _n, sha in (x.get("deps") or {}).items():
            d = by_sha.get(sha)
            if d is None:
                raise KeyError(_n)
            if sha not in seen:
                seen.add(sha)
                add(d)
                deps.append(d["source"])
    try:
        add(e)
    except KeyError as k:
        return "a function it calls (%s) is no longer kept by the source it was checked with" % k
    if checked_source(e["source"], e["name"], set(e.get("uses") or [])) is not None:
        return "its source no longer passes the store's check"
    if not e.get("examples"):
        return None
    with tempfile.TemporaryDirectory(prefix="o7night_") as d:
        jp = os.path.join(d, "job.json")
        json.dump({"name": e["name"], "source": e["source"], "deps": deps, "imports": e.get("imports") or [],
                   "examples": e["examples"]}, open(jp, "w"))
        sp = os.path.join(d, "replay.py")
        open(sp, "w").write(REPLAY)
        try:
            r = subprocess.run([sys.executable, "-I", sp, jp], capture_output=True, text=True, timeout=60, cwd=d,
                               env=__import__("runjail").env(root=d))   # round-3 R2
            got = json.loads(r.stdout.strip().splitlines()[-1])
        except Exception as x:  # noqa: BLE001
            return "its replay did not finish (%s)" % type(x).__name__
    bad = [i for i, g in enumerate(got) if not g]
    if bad:
        return "%d of its %d examples no longer hold (the first: %r)" % (len(bad), len(got), e["examples"][bad[0]])
    return None


def nightly(night=None, dream=True, dream_seconds=120):
    """the code store's night (sleep's steps 4 and 3 for kept code): every kept function replayed on its evidence and
    retired with a receipt when it no longer holds; then each day's code hole tried again with the store as it now is. A
    dream that composes is recorded, never kept: it is kept only after a project's check passes with it (the law)."""
    t0 = time.time()
    entries = load()
    by_sha = {e["sha256"]: e for e in load(with_retired=True)}
    rep = {"night": night, "kept": len(entries), "replayed": 0, "retired": [], "holes": 0, "dreamt": []}
    for e in entries:
        why = replay(e, by_sha)
        rep["replayed"] += 1
        if why:
            rep["retired"].append({"id": e["id"], "name": e["name"], "receipt": why})
    if rep["retired"]:
        with open(_beside("code_retired.jsonl"), "a", encoding="utf-8") as f:
            for r in rep["retired"]:
                f.write(json.dumps(dict(r, night=night, t=time.time())) + "\n")
    if dream:
        import tempfile
        import compose_code as CC
        dreams_p = _beside("code_dreams.jsonl")
        done = set()
        if dreams_p.is_file():
            for ln in dreams_p.read_text(encoding="utf-8").splitlines():
                try:
                    done.add(json.loads(ln)["hole"])
                except Exception:  # noqa: BLE001
                    continue
        holes = [h for h in _holes() if h["id"] not in done]
        rep["holes"] = len(holes)
        for h in holes:
            ex = [(tuple(a), o, None) for a, o in h["examples"]]
            goal = {"name": h["name"], "params": h["params"] or CC.param_names(ex), "module": "dream", "examples": ex,
                    "module_text": ""}
            with tempfile.TemporaryDirectory(prefix="o7dream_") as d:
                res = CC.run_job(d, [goal], timeout=dream_seconds)
            r = (res.get("results") or [{}])[0] if "error" not in res else {}
            if r.get("status") == "composed":
                rec = {"hole": h["id"], "name": h["name"], "source": r["source"], "read_back": r.get("read_back"),
                       "night": night, "t": time.time()}
                rep["dreamt"].append({"name": h["name"], "source": r["source"]})
                with open(dreams_p, "a", encoding="utf-8") as f:
                    f.write(json.dumps(rec) + "\n")
    rep["seconds"] = round(time.time() - t0, 1)
    return rep


# ---------------------------------------------------------------- the spine
class CodeFlash:
    """the kept functions as one matrix of walks; a goal's facts light them in one product"""

    def __init__(self, entries):
        import numpy as np
        import o7spine_v1 as SP
        self.np, self.SP = np, SP
        self.D = SP.D
        self.NE = len(SP.EDGES)
        self.entries = entries
        self._lab = {}
        M = np.zeros((max(1, len(entries)), self.D), np.complex64)
        for n, e in enumerate(entries):
            for k, v in self.facts_of_entry(e):
                M[n] += self.lab("K:" + k) * self.val(v)
        norms = np.sqrt(np.sum(np.abs(M) ** 2, axis=1, keepdims=True))
        self.M = (M / np.maximum(norms, 1e-6)).astype(np.complex64)

    def _walk(self, n, length):
        out = []
        for _ in range(length):
            out.append(n % self.NE)
            n //= self.NE
        return self.SP.walk_vec(out)

    def lab(self, key):
        if key not in self._lab:
            h = int(hashlib.sha256(("o7code:" + key).encode()).hexdigest(), 16)
            self._lab[key] = self._walk(h % (self.NE ** 3), 3)
        return self._lab[key]

    def val(self, v):
        h = int(hashlib.sha256(("o7codeval:" + str(v)).encode()).hexdigest(), 16)
        return self._walk(h % (self.NE ** 4), 4)

    @staticmethod
    def facts_of_entry(e):
        out = [("arity", len(e.get("params") or []))]
        for i, s in enumerate(e.get("in_shapes") or []):
            out += [("in", s), ("in%d" % i, s)]
        if e.get("out_shape"):
            out.append(("out", e["out_shape"]))
        out += [("word", w) for w in (e.get("words") or [])]
        return out

    def light(self, in_shapes, out_shape, words, top=TOP):
        """-> [(resonance, entry)], the kept functions the goal's facts light, strongest first"""
        if not self.entries:
            return []
        np = self.np
        cue = np.zeros(self.D, np.complex64)
        for i, s in enumerate(in_shapes):
            cue += self.lab("K:in") * self.val(s)
        if out_shape:
            cue += self.lab("K:out") * self.val(out_shape)
        for w in words:
            cue += 2.0 * self.lab("K:word") * self.val(w)
        res = np.real(self.M @ np.conj(cue)) / self.D
        order = np.argsort(-res)[:top]
        return [(float(res[i]), self.entries[i]) for i in order if res[i] > 0.02]


if __name__ == "__main__":                            # the night, by a timer or by hand: python3 code_store.py nightly
    if sys.argv[1:2] == ["nightly"]:
        print(json.dumps(nightly(night=time.strftime("%Y-%m-%d")), indent=1))