error-of 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- error_of/__init__.py +0 -0
- error_of/__main__.py +3 -0
- error_of/cli.py +122 -0
- error_of/core.py +251 -0
- error_of/heal.py +66 -0
- error_of/walk.py +99 -0
- error_of-0.1.0.dist-info/METADATA +94 -0
- error_of-0.1.0.dist-info/RECORD +11 -0
- error_of-0.1.0.dist-info/WHEEL +5 -0
- error_of-0.1.0.dist-info/entry_points.txt +2 -0
- error_of-0.1.0.dist-info/top_level.txt +1 -0
error_of/__init__.py
ADDED
|
File without changes
|
error_of/__main__.py
ADDED
error_of/cli.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""error-of command line.
|
|
2
|
+
|
|
3
|
+
error-of run <command ...> run, capture, classify, report, store
|
|
4
|
+
error-of report <case-id> print a stored case as Markdown
|
|
5
|
+
error-of search <text> find stored cases by class, boundary or text
|
|
6
|
+
error-of patterns recurring signatures and classes
|
|
7
|
+
error-of walk <e1> <e2> ... diagnose a walk from its signed errors
|
|
8
|
+
(two remembered errors per step, no history)
|
|
9
|
+
"""
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
from collections import Counter
|
|
14
|
+
|
|
15
|
+
from . import core
|
|
16
|
+
from . import walk
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def cmd_run(argv, out_dir):
|
|
20
|
+
if not argv:
|
|
21
|
+
print("usage: error-of run <command ...>", file=sys.stderr)
|
|
22
|
+
return 2
|
|
23
|
+
cap = core.capture(argv)
|
|
24
|
+
case = core.build_case(cap)
|
|
25
|
+
core.store(case)
|
|
26
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
27
|
+
md, js = (os.path.join(out_dir, f"{case['id']}.{e}") for e in ("md", "json"))
|
|
28
|
+
with open(md, "w") as f:
|
|
29
|
+
f.write(core.to_markdown(case))
|
|
30
|
+
with open(js, "w") as f:
|
|
31
|
+
json.dump(case, f, indent=2)
|
|
32
|
+
|
|
33
|
+
# the original output first, untouched
|
|
34
|
+
sys.stdout.write(cap["stdout"])
|
|
35
|
+
sys.stderr.write(cap["stderr"])
|
|
36
|
+
print(f"\n[error-of] {case['status']} exit={case['exit_code']} "
|
|
37
|
+
f"{len(case['observations'])} observation(s), {len(case['inferences'])} inference(s)"
|
|
38
|
+
+ (f", signature seen {case['seen_before']}x before" if case["seen_before"] else ""),
|
|
39
|
+
file=sys.stderr)
|
|
40
|
+
for o in case["observations"]:
|
|
41
|
+
print(f"[error-of] {o.get('class')}: {o.get('boundary')} -> {o.get('outcome', '')}",
|
|
42
|
+
file=sys.stderr)
|
|
43
|
+
for h in case["inferences"]:
|
|
44
|
+
print(f"[error-of] {h['class']}: assumed '{h['assumption']}'", file=sys.stderr)
|
|
45
|
+
if case.get("side"):
|
|
46
|
+
print(f"[error-of] side: {case['side']}", file=sys.stderr)
|
|
47
|
+
print(f"[error-of] report: {md}", file=sys.stderr)
|
|
48
|
+
return case["exit_code"]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def cmd_report(case_id):
|
|
52
|
+
for c in core.load_cases():
|
|
53
|
+
if c["id"].startswith(case_id):
|
|
54
|
+
print(core.to_markdown(c))
|
|
55
|
+
return 0
|
|
56
|
+
print(f"no case {case_id}", file=sys.stderr)
|
|
57
|
+
return 1
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def cmd_search(term):
|
|
61
|
+
t = term.lower()
|
|
62
|
+
n = 0
|
|
63
|
+
for c in core.load_cases():
|
|
64
|
+
blob = json.dumps(c["observations"] + c["inferences"]).lower() + c["stderr"].lower()
|
|
65
|
+
if t in blob:
|
|
66
|
+
classes = sorted({x.get("class") for x in c["observations"] + c["inferences"]})
|
|
67
|
+
print(f"{c['id']} {c['time']} {c['status']:<9} {','.join(classes):<30} {' '.join(c['command'])}")
|
|
68
|
+
n += 1
|
|
69
|
+
return 0 if n else 1
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def cmd_patterns():
|
|
73
|
+
cases = core.load_cases()
|
|
74
|
+
cls = Counter(x.get("class") for c in cases for x in c["observations"] + c["inferences"])
|
|
75
|
+
sig = Counter(c["signature"] for c in cases if c["signature"])
|
|
76
|
+
print(f"{len(cases)} cases\n\nclasses:")
|
|
77
|
+
for k, v in cls.most_common():
|
|
78
|
+
print(f" {v:4} {k}")
|
|
79
|
+
print("\nrecurring signatures:")
|
|
80
|
+
for k, v in sig.most_common():
|
|
81
|
+
if v > 1:
|
|
82
|
+
ex = next(c for c in cases if c["signature"] == k)
|
|
83
|
+
print(f" {v:4} {k} e.g. {' '.join(ex['command'])}")
|
|
84
|
+
return 0
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def cmd_walk(values):
|
|
88
|
+
try:
|
|
89
|
+
errors = [float(v) for v in values]
|
|
90
|
+
except ValueError:
|
|
91
|
+
print("usage: error-of walk <signed error> <signed error> ...", file=sys.stderr)
|
|
92
|
+
return 2
|
|
93
|
+
w = walk.Walk()
|
|
94
|
+
last = None
|
|
95
|
+
for e in errors:
|
|
96
|
+
last = w.step(e)
|
|
97
|
+
print(walk.describe(last))
|
|
98
|
+
return 0 if last and last["state"] in ("arrived", "converging") else 1
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def main():
|
|
102
|
+
a = sys.argv[1:]
|
|
103
|
+
out_dir = os.environ.get("ERROR_OF_OUT", "output")
|
|
104
|
+
if not a or a[0] in ("-h", "--help"):
|
|
105
|
+
print(__doc__)
|
|
106
|
+
return 0
|
|
107
|
+
if a[0] == "run":
|
|
108
|
+
return cmd_run(a[1:], out_dir)
|
|
109
|
+
if a[0] == "report" and len(a) > 1:
|
|
110
|
+
return cmd_report(a[1])
|
|
111
|
+
if a[0] == "search" and len(a) > 1:
|
|
112
|
+
return cmd_search(" ".join(a[1:]))
|
|
113
|
+
if a[0] == "patterns":
|
|
114
|
+
return cmd_patterns()
|
|
115
|
+
if a[0] == "walk" and len(a) > 1:
|
|
116
|
+
return cmd_walk(a[1:])
|
|
117
|
+
print(__doc__)
|
|
118
|
+
return 2
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
if __name__ == "__main__":
|
|
122
|
+
sys.exit(main())
|
error_of/core.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""error-of core: capture -> normalize -> classify -> infer -> report -> store.
|
|
2
|
+
|
|
3
|
+
Every inference carries the rule that produced it (design principle:
|
|
4
|
+
"explain every inference"). The original stdout/stderr are kept verbatim
|
|
5
|
+
("preserve original errors"). The knowledge base is append-only JSONL
|
|
6
|
+
("learn without rewriting history").
|
|
7
|
+
"""
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import platform
|
|
12
|
+
import re
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
from datetime import datetime, timezone
|
|
17
|
+
|
|
18
|
+
# --------------------------------------------------------------------- capture
|
|
19
|
+
|
|
20
|
+
def capture(argv, timeout=None):
|
|
21
|
+
t0 = time.monotonic()
|
|
22
|
+
try:
|
|
23
|
+
p = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
|
|
24
|
+
out, err, code = p.stdout, p.stderr, p.returncode
|
|
25
|
+
except FileNotFoundError as e:
|
|
26
|
+
out, err, code = "", f"{e}", 127
|
|
27
|
+
except subprocess.TimeoutExpired as e:
|
|
28
|
+
out = e.stdout or ""
|
|
29
|
+
err = (e.stderr or "") + f"\n[error-of] timeout after {timeout}s"
|
|
30
|
+
code = 124
|
|
31
|
+
out = out.decode() if isinstance(out, bytes) else out
|
|
32
|
+
err = err.decode() if isinstance(err, bytes) else err
|
|
33
|
+
return {
|
|
34
|
+
"command": argv,
|
|
35
|
+
"stdout": out,
|
|
36
|
+
"stderr": err,
|
|
37
|
+
"exit_code": code,
|
|
38
|
+
"runtime_s": round(time.monotonic() - t0, 4),
|
|
39
|
+
"environment": {
|
|
40
|
+
"python": platform.python_version(),
|
|
41
|
+
"platform": platform.platform(),
|
|
42
|
+
"cwd": os.getcwd(),
|
|
43
|
+
},
|
|
44
|
+
"time": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# ------------------------------------------------- self-reported observations
|
|
49
|
+
# A program can describe its own boundary by printing one line to stderr:
|
|
50
|
+
# ERROR-OF {"class": ..., "boundary": ..., "assumption": ..., ...}
|
|
51
|
+
# Those are taken as first-hand observations and ranked above pattern guesses.
|
|
52
|
+
|
|
53
|
+
OBS_RE = re.compile(r"^ERROR-OF\s+(\{.*\})\s*$", re.M)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def self_reports(stderr):
|
|
57
|
+
found = []
|
|
58
|
+
for m in OBS_RE.finditer(stderr):
|
|
59
|
+
try:
|
|
60
|
+
d = json.loads(m.group(1))
|
|
61
|
+
d["source"] = "self-report"
|
|
62
|
+
found.append(d)
|
|
63
|
+
except json.JSONDecodeError:
|
|
64
|
+
pass
|
|
65
|
+
return found
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ------------------------------------------------------------------- classify
|
|
69
|
+
# Each rule: class, regex, boundary, assumption, possible invariant, transformations.
|
|
70
|
+
|
|
71
|
+
RULES = [
|
|
72
|
+
("Syntax", r"SyntaxError|syntax error near unexpected token|unexpected EOF|IndentationError",
|
|
73
|
+
"the parser's grammar",
|
|
74
|
+
"the text is written in the language of the program that reads it",
|
|
75
|
+
"an interpreter accepts only its own grammar",
|
|
76
|
+
["check the interpreter matches the file (python vs bash: shebang or `python file.py`)",
|
|
77
|
+
"look for a wrapped or merged line near the reported position"]),
|
|
78
|
+
("Context", r"command not found|No such file or directory|not a git repository|ModuleNotFoundError|ImportError|cannot find module",
|
|
79
|
+
"what exists in this environment",
|
|
80
|
+
"a name the program refers to exists where it is run",
|
|
81
|
+
"a reference is only valid inside the context that defines it",
|
|
82
|
+
["install or activate the missing piece (venv, package, PATH)",
|
|
83
|
+
"make the dependency explicit (requirements file, shebang, absolute path)"]),
|
|
84
|
+
("Memory", r"MemoryError|out of memory|Killed|std::bad_alloc|Cannot allocate memory",
|
|
85
|
+
"available memory",
|
|
86
|
+
"the whole state fits in memory at once",
|
|
87
|
+
"state size grows with input; memory does not",
|
|
88
|
+
["stream or chunk instead of materialising everything",
|
|
89
|
+
"replace enumeration by a closed form or recurrence"]),
|
|
90
|
+
("Precision", r"OverflowError|int too large to convert to float|FloatingPointError|ZeroDivisionError|\b(inf|nan)\b",
|
|
91
|
+
"the number representation",
|
|
92
|
+
"floats can stand in for the exact values",
|
|
93
|
+
"an exact quantity should survive the round trip",
|
|
94
|
+
["use exact types (int, Fraction, Decimal, symbolic)",
|
|
95
|
+
"keep values in a representation where the operation is closed"]),
|
|
96
|
+
("Time", r"timeout|Timed out|TimeoutExpired|deadline exceeded",
|
|
97
|
+
"the time budget",
|
|
98
|
+
"the work finishes within the allowed time",
|
|
99
|
+
"cost grows with input size",
|
|
100
|
+
["reduce complexity, cache, or parallelise",
|
|
101
|
+
"make progress resumable"]),
|
|
102
|
+
("Storage", r"No space left on device|Disk quota exceeded|ENOSPC",
|
|
103
|
+
"disk capacity",
|
|
104
|
+
"there is room to write",
|
|
105
|
+
"writes need free space",
|
|
106
|
+
["clean caches and build outputs", "write elsewhere or compress"]),
|
|
107
|
+
("Permissions", r"Permission denied|Operation not permitted|EACCES|EPERM",
|
|
108
|
+
"the permission boundary",
|
|
109
|
+
"this process may touch this resource",
|
|
110
|
+
"access is granted per identity and path",
|
|
111
|
+
["run with the right identity or path", "request the permission explicitly"]),
|
|
112
|
+
("Authentication", r"\b401\b|403 Forbidden|Unauthorized|invalid token|authentication failed",
|
|
113
|
+
"identity verification",
|
|
114
|
+
"the caller is who the service expects",
|
|
115
|
+
"credentials expire and are scoped",
|
|
116
|
+
["refresh or rescope the credential"]),
|
|
117
|
+
("Network", r"Connection refused|Name or service not known|ECONNRESET|Network is unreachable|\b429\b|Too Many Requests",
|
|
118
|
+
"reachability",
|
|
119
|
+
"the remote side is reachable and willing",
|
|
120
|
+
"a remote resource can refuse or be absent",
|
|
121
|
+
["retry with backoff", "use a local copy or a different route"]),
|
|
122
|
+
("Representation", r"ValueError|TypeError|invalid literal|could not convert|UnicodeDecodeError|KeyError",
|
|
123
|
+
"the shape of the data",
|
|
124
|
+
"the data has the form the code expects",
|
|
125
|
+
"input form and code form must match",
|
|
126
|
+
["validate and normalise at the boundary", "choose a representation where the case is legal"]),
|
|
127
|
+
]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# Which way the wall was hit, and which way to move. A boundary says where the
|
|
131
|
+
# walk stopped; a side says what to do next. Classes without a side (Syntax,
|
|
132
|
+
# Context, ...) are walls with no direction: the fix is to change the input,
|
|
133
|
+
# not to move along an axis. Space and time trade against each other.
|
|
134
|
+
SIDES = {
|
|
135
|
+
"Memory": ("too big", "trade time for space: recompute or keep only what the next step needs"),
|
|
136
|
+
"Storage": ("too big", "trade time for space: write less, compress, or stream"),
|
|
137
|
+
"Time": ("too slow", "trade space for time: store results instead of recomputing"),
|
|
138
|
+
"Precision": ("too coarse", "use a finer representation: the value needs more than the cell holds"),
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def classify(stderr, stdout=""):
|
|
143
|
+
text = stderr + "\n" + stdout
|
|
144
|
+
hits = []
|
|
145
|
+
for cls, pat, boundary, assumption, invariant, transforms in RULES:
|
|
146
|
+
m = re.search(pat, text)
|
|
147
|
+
if m:
|
|
148
|
+
side, trade = SIDES.get(cls, (None, None))
|
|
149
|
+
hits.append({
|
|
150
|
+
"class": cls, "boundary": boundary, "assumption": assumption,
|
|
151
|
+
"invariant": invariant, "transformations": transforms,
|
|
152
|
+
"side": side, "trade": trade,
|
|
153
|
+
"evidence": text[max(0, m.start() - 60):m.end() + 60].strip(),
|
|
154
|
+
"rule": pat, "source": "pattern",
|
|
155
|
+
})
|
|
156
|
+
return hits
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def case_side(observations, inferences):
|
|
160
|
+
"""The case's side: a program's own report first, then the first pattern that has one."""
|
|
161
|
+
for x in list(observations) + list(inferences):
|
|
162
|
+
if x.get("side"):
|
|
163
|
+
return x["side"]
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def signature(stderr):
|
|
168
|
+
"""Stable fingerprint of an error, insensitive to paths, numbers and addresses."""
|
|
169
|
+
s = re.sub(r"0x[0-9a-fA-F]+|\d+", "N", stderr)
|
|
170
|
+
s = re.sub(r"(/[\w.\-]+)+", "PATH", s)
|
|
171
|
+
lines = [l.strip() for l in s.splitlines() if l.strip()][-3:]
|
|
172
|
+
return hashlib.sha1("\n".join(lines).encode()).hexdigest()[:12]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# ----------------------------------------------------------------------- store
|
|
176
|
+
|
|
177
|
+
def kb_path():
|
|
178
|
+
return os.environ.get("ERROR_OF_HOME", os.path.expanduser("~/.error-of")) + "/cases.jsonl"
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def store(case):
|
|
182
|
+
path = kb_path()
|
|
183
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
184
|
+
with open(path, "a") as f:
|
|
185
|
+
f.write(json.dumps(case) + "\n")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def load_cases():
|
|
189
|
+
try:
|
|
190
|
+
with open(kb_path()) as f:
|
|
191
|
+
return [json.loads(l) for l in f if l.strip()]
|
|
192
|
+
except FileNotFoundError:
|
|
193
|
+
return []
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
# ---------------------------------------------------------------------- report
|
|
197
|
+
|
|
198
|
+
def build_case(cap):
|
|
199
|
+
obs = self_reports(cap["stderr"])
|
|
200
|
+
pats = classify(cap["stderr"], cap["stdout"]) if cap["exit_code"] != 0 or not obs else []
|
|
201
|
+
sig = signature(cap["stderr"]) if cap["stderr"].strip() else None
|
|
202
|
+
prior = [c for c in load_cases() if sig and c.get("signature") == sig]
|
|
203
|
+
if cap["exit_code"] == 0 and not obs:
|
|
204
|
+
status = "clean"
|
|
205
|
+
elif cap["exit_code"] == 0:
|
|
206
|
+
status = "continued" # boundaries met and crossed
|
|
207
|
+
else:
|
|
208
|
+
status = "stopped"
|
|
209
|
+
case = dict(cap)
|
|
210
|
+
case.update({
|
|
211
|
+
"id": hashlib.sha1((cap["time"] + " ".join(cap["command"])).encode()).hexdigest()[:10],
|
|
212
|
+
"status": status,
|
|
213
|
+
"observations": obs,
|
|
214
|
+
"inferences": pats if pats else ([] if obs or status == "clean" else [{
|
|
215
|
+
"class": "Unknown", "boundary": "unidentified", "assumption": "unidentified",
|
|
216
|
+
"invariant": None, "transformations": ["add a rule for this signature"],
|
|
217
|
+
"evidence": cap["stderr"][-200:], "rule": None, "source": "fallback"}]),
|
|
218
|
+
"signature": sig,
|
|
219
|
+
"seen_before": len(prior),
|
|
220
|
+
})
|
|
221
|
+
case["side"] = case_side(case["observations"], case["inferences"])
|
|
222
|
+
return case
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def to_markdown(c):
|
|
226
|
+
L = [f"# error-of case {c['id']}", "",
|
|
227
|
+
f"- command: `{' '.join(c['command'])}`",
|
|
228
|
+
f"- exit code: {c['exit_code']} runtime: {c['runtime_s']}s status: **{c['status']}**",
|
|
229
|
+
f"- signature: {c['signature']} seen before: {c['seen_before']}",
|
|
230
|
+
f"- side: {c.get('side') or 'none (a wall with no direction)'}", ""]
|
|
231
|
+
if c["observations"]:
|
|
232
|
+
L += ["## Observations (reported by the program itself)", ""]
|
|
233
|
+
for i, o in enumerate(c["observations"], 1):
|
|
234
|
+
L += [f"### {i}. {o.get('class', '?')}: {o.get('boundary', '')}", ""]
|
|
235
|
+
for k in ("observation", "assumption", "invariant", "transformation", "side", "error", "outcome"):
|
|
236
|
+
if o.get(k) is not None:
|
|
237
|
+
L.append(f"- **{k}:** {o[k]}")
|
|
238
|
+
L.append("")
|
|
239
|
+
if c["inferences"]:
|
|
240
|
+
L += ["## Inferences (from patterns in the output)", ""]
|
|
241
|
+
for i, h in enumerate(c["inferences"], 1):
|
|
242
|
+
L += [f"### {i}. {h['class']}", "",
|
|
243
|
+
f"- **boundary:** {h['boundary']}",
|
|
244
|
+
f"- **assumption:** {h['assumption']}",
|
|
245
|
+
f"- **possible invariant:** {h['invariant']}",
|
|
246
|
+
*([f"- **side:** {h['side']} ({h['trade']})"] if h.get("side") else []),
|
|
247
|
+
"- **suggested transformations:**"] + [f" - {t}" for t in h["transformations"]] + [
|
|
248
|
+
f"- **because:** matched `{h['rule']}` in: `{h['evidence'][:160]}`", ""]
|
|
249
|
+
L += ["## Original stderr", "", "```", c["stderr"].rstrip() or "(empty)", "```", "",
|
|
250
|
+
"## Original stdout", "", "```", c["stdout"].rstrip()[-4000:] or "(empty)", "```"]
|
|
251
|
+
return "\n".join(L)
|
error_of/heal.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Self-healing with a witness.
|
|
2
|
+
|
|
3
|
+
A heal is a transformation of the INPUT (or representation), never of the code.
|
|
4
|
+
A heal is accepted only if an invariant confirms it preserved what must be
|
|
5
|
+
preserved. Every attempt, accepted or rejected, is reported as an ERROR-OF
|
|
6
|
+
observation, so `error-of run` records the history.
|
|
7
|
+
|
|
8
|
+
from error_of.heal import heals, Heal
|
|
9
|
+
|
|
10
|
+
@heals(Heal(ValueError, transform=carry, invariant=same_value, name="carry 011->100"))
|
|
11
|
+
def load(s): ...
|
|
12
|
+
|
|
13
|
+
If no heal applies, or every heal is rejected by its invariant, the original
|
|
14
|
+
error is raised unchanged.
|
|
15
|
+
"""
|
|
16
|
+
import functools
|
|
17
|
+
import json
|
|
18
|
+
import sys
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Heal:
|
|
22
|
+
def __init__(self, error, transform, invariant, name=None, match=None):
|
|
23
|
+
self.error = error # exception type this heal answers
|
|
24
|
+
self.transform = transform # input -> new input
|
|
25
|
+
self.invariant = invariant # (old input, new input) -> bool
|
|
26
|
+
self.name = name or transform.__name__
|
|
27
|
+
self.match = match # optional text that must be in the message
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _observe(**kw):
|
|
31
|
+
print("ERROR-OF " + json.dumps(kw, default=str), file=sys.stderr)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def heals(*heal_list, max_rounds=5):
|
|
35
|
+
def deco(fn):
|
|
36
|
+
@functools.wraps(fn)
|
|
37
|
+
def wrapper(x, *a, **k):
|
|
38
|
+
current, history = x, []
|
|
39
|
+
for _ in range(max_rounds):
|
|
40
|
+
try:
|
|
41
|
+
result = fn(current, *a, **k)
|
|
42
|
+
if history:
|
|
43
|
+
_observe(**{"class": "Representation"}, boundary=fn.__name__,
|
|
44
|
+
observation=f"healed after {len(history)} step(s): {history}",
|
|
45
|
+
assumption=f"input was already in the form {fn.__name__} accepts",
|
|
46
|
+
transformation=" -> ".join(history), outcome="continued")
|
|
47
|
+
return result
|
|
48
|
+
except Exception as e:
|
|
49
|
+
h = next((h for h in heal_list if isinstance(e, h.error)
|
|
50
|
+
and (h.match is None or h.match in str(e))), None)
|
|
51
|
+
if h is None:
|
|
52
|
+
raise
|
|
53
|
+
candidate = h.transform(current)
|
|
54
|
+
ok = h.invariant(current, candidate)
|
|
55
|
+
_observe(**{"class": "Representation"}, boundary=fn.__name__,
|
|
56
|
+
observation=f"{type(e).__name__}: {e}",
|
|
57
|
+
transformation=f"{h.name}: {current!r} -> {candidate!r}",
|
|
58
|
+
invariant=f"{h.invariant.__name__}: {'held' if ok else 'VIOLATED'}",
|
|
59
|
+
outcome="retry" if ok else "rejected, original error raised")
|
|
60
|
+
if not ok:
|
|
61
|
+
raise
|
|
62
|
+
history.append(f"{h.name}({current!r}->{candidate!r})")
|
|
63
|
+
current = candidate
|
|
64
|
+
raise RuntimeError(f"{fn.__name__}: not healed after {max_rounds} rounds: {history}")
|
|
65
|
+
return wrapper
|
|
66
|
+
return deco
|
error_of/walk.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""The walk: two remembered errors, and what they say about where it is going.
|
|
2
|
+
|
|
3
|
+
A walk toward a target produces one signed error per tick
|
|
4
|
+
(error > 0: too high, error < 0: too low, 0: arrived). The walk keeps only
|
|
5
|
+
the last two errors. No history, no list of visited states.
|
|
6
|
+
|
|
7
|
+
From those two and the current one, a single number
|
|
8
|
+
|
|
9
|
+
k = (e_now + e_prev) / e_last
|
|
10
|
+
|
|
11
|
+
says what the walk is doing, because three consecutive values of any
|
|
12
|
+
second-order chain satisfy e_now + e_prev = k * e_last:
|
|
13
|
+
|
|
14
|
+
|k| < 2 rotating: the errors circle and never settle (cycling)
|
|
15
|
+
k = +2 straight line: constant step or no change (drifting / stuck)
|
|
16
|
+
k = -2 flipping between two equal values: a two-step loop (cycling)
|
|
17
|
+
|k| > 2 geometric: errors shrink or grow by a fixed ratio r,
|
|
18
|
+
where r + 1/r = k
|
|
19
|
+
k < -2 the sign flips every step: high, low, high (bracketing)
|
|
20
|
+
k > +2 the sign stays: approaching from one side
|
|
21
|
+
|
|
22
|
+
For a converging walk the rate is the root of r + 1/r = k with |r| < 1.
|
|
23
|
+
Errors of the form t^n and (-1/t)^n give k = t + 1/t and k = -(t + 1/t).
|
|
24
|
+
|
|
25
|
+
This replaces cycle detection by a set of seen states: three numbers the
|
|
26
|
+
walk already holds are enough to call a cycle.
|
|
27
|
+
"""
|
|
28
|
+
import math
|
|
29
|
+
|
|
30
|
+
STRAIGHT_TOL = 0.05 # how close |k| must be to 2 to count as a straight line
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def side(error):
|
|
34
|
+
if error is None:
|
|
35
|
+
return None
|
|
36
|
+
if error > 0:
|
|
37
|
+
return "too high"
|
|
38
|
+
if error < 0:
|
|
39
|
+
return "too low"
|
|
40
|
+
return "arrived"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def diagnose(e_prev, e_last, e_now, tol=STRAIGHT_TOL):
|
|
44
|
+
"""Classify a walk from its last three errors. Pure function."""
|
|
45
|
+
out = {"side": side(e_now), "k": None, "rate": None, "bracketing": None}
|
|
46
|
+
if e_now == 0:
|
|
47
|
+
return {**out, "state": "arrived"}
|
|
48
|
+
if e_prev is None or e_last is None:
|
|
49
|
+
return {**out, "state": "warming up"} # fewer than three points
|
|
50
|
+
if e_last == 0:
|
|
51
|
+
return {**out, "state": "left the target"} # was exact, now is not
|
|
52
|
+
k = (e_now + e_prev) / e_last
|
|
53
|
+
out["k"] = k
|
|
54
|
+
out["bracketing"] = (e_now > 0) != (e_last > 0)
|
|
55
|
+
if abs(abs(k) - 2) <= tol:
|
|
56
|
+
if k > 0: # straight line: same sign, constant step
|
|
57
|
+
state = "stuck" if e_now == e_last else "drifting"
|
|
58
|
+
elif abs(abs(e_now) - abs(e_last)) <= tol * abs(e_last):
|
|
59
|
+
state = "cycling" # r = -1: flips between two values forever
|
|
60
|
+
out["rate"] = 1.0
|
|
61
|
+
else:
|
|
62
|
+
state = "drifting" # flips sign, size changes by a constant step
|
|
63
|
+
return {**out, "state": state}
|
|
64
|
+
if abs(k) < 2:
|
|
65
|
+
out["rate"] = 1.0 # |r| = 1: on the circle
|
|
66
|
+
return {**out, "state": "cycling"}
|
|
67
|
+
small = (k - math.copysign(math.sqrt(k * k - 4), k)) / 2 # root with |r| < 1
|
|
68
|
+
if abs(e_now) < abs(e_last):
|
|
69
|
+
return {**out, "rate": abs(small), "state": "converging"}
|
|
70
|
+
return {**out, "rate": 1 / abs(small), "state": "diverging"}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Walk:
|
|
74
|
+
"""Holds exactly two remembered errors. step() takes the newest one."""
|
|
75
|
+
|
|
76
|
+
def __init__(self, tol=STRAIGHT_TOL):
|
|
77
|
+
self.prev = None
|
|
78
|
+
self.last = None
|
|
79
|
+
self.tol = tol
|
|
80
|
+
self.ticks = 0
|
|
81
|
+
|
|
82
|
+
def step(self, error):
|
|
83
|
+
d = diagnose(self.prev, self.last, error, self.tol)
|
|
84
|
+
self.prev, self.last = self.last, error
|
|
85
|
+
self.ticks += 1
|
|
86
|
+
d["tick"] = self.ticks
|
|
87
|
+
return d
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def edges(self):
|
|
91
|
+
return self.prev, self.last
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def describe(d):
|
|
95
|
+
k = "" if d["k"] is None else f"k={d['k']:+.3f}"
|
|
96
|
+
rate = "" if d["rate"] is None else f"rate={d['rate']:.3f}"
|
|
97
|
+
br = "" if d["bracketing"] is None else ("bracketing" if d["bracketing"] else "one-sided")
|
|
98
|
+
return " ".join(x for x in (f"tick {d['tick']:>3}", f"{d['state']:<15}",
|
|
99
|
+
f"side={d['side']}", k, rate, br) if x)
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: error-of
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Errors as observations: side, three-error walk diagnostics, and invariant-witnessed self-healing.
|
|
5
|
+
Author: space
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Provides-Extra: pdf
|
|
10
|
+
Requires-Dist: pdfminer.six; extra == "pdf"
|
|
11
|
+
Requires-Dist: numpy; extra == "pdf"
|
|
12
|
+
Requires-Dist: pillow; extra == "pdf"
|
|
13
|
+
Provides-Extra: all
|
|
14
|
+
Requires-Dist: pdfminer.six; extra == "all"
|
|
15
|
+
Requires-Dist: numpy; extra == "all"
|
|
16
|
+
Requires-Dist: pillow; extra == "all"
|
|
17
|
+
Requires-Dist: playwright; extra == "all"
|
|
18
|
+
|
|
19
|
+
# error-of
|
|
20
|
+
|
|
21
|
+
Errors as observations. See `PRD.md` and `docs/architecture.md`.
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
./error-of run <command ...> run, capture, classify, report (output/<id>.md, .json)
|
|
25
|
+
./error-of report <id> show a stored case
|
|
26
|
+
./error-of search <text> search stored cases
|
|
27
|
+
./error-of patterns recurring classes and signatures
|
|
28
|
+
./error-of walk <e1> <e2> ... diagnose a walk from its signed errors
|
|
29
|
+
python3 -m unittest discover tests
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
How error-of fits a larger loop (reconstruct, run, read the error, keep two edges,
|
|
33
|
+
gate): `docs/construct.md`.
|
|
34
|
+
|
|
35
|
+
## Side and walk
|
|
36
|
+
|
|
37
|
+
Every case now carries a **side** when the error has a direction: `too big`
|
|
38
|
+
(Memory, Storage: trade time for space), `too slow` (Time: trade space for time),
|
|
39
|
+
`too coarse` (Precision). Programs can report their own with `"side"` and a signed
|
|
40
|
+
`"error"` in the protocol line.
|
|
41
|
+
|
|
42
|
+
`error_of/walk.py` keeps only the last two errors of a walk toward a target and
|
|
43
|
+
reads one number from them, `k = (e_now + e_prev) / e_last`:
|
|
44
|
+
|k| < 2 cycling, k = +2 drifting, k < -2 converging while bracketing, and so on.
|
|
45
|
+
Cycles are called from three numbers, without a list of visited states.
|
|
46
|
+
|
|
47
|
+
## Organisms: programs generated, not written
|
|
48
|
+
|
|
49
|
+
Four small, runnable cases, each with a one-page description in `docs/organisms/`:
|
|
50
|
+
|
|
51
|
+
| | goal | starts with | learns | code |
|
|
52
|
+
|---|---|---|---|---|
|
|
53
|
+
| [X](docs/organisms/X.md) | answer a question | a frozen proposer | nothing; carries two sides | `examples/reconstruct/fib.py` |
|
|
54
|
+
| [A](docs/organisms/A.md) | find a program from examples | four seed moves | words from successes, refutations from failures | `examples/organism/organism.py` |
|
|
55
|
+
| [B](docs/organisms/B.md) | same as A | seed moves, in A's world | from A's refutations | same |
|
|
56
|
+
| [C](docs/organisms/C.md) | same as A, plus an unseen goal | A's words | from A's successes | same |
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
python3 examples/reconstruct/fib.py # X, ~3 s
|
|
60
|
+
./error-of run python3 examples/organism/organism.py # A, B, C, recorded as observations
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Knowledge base: `~/.error-of/cases.jsonl` (append-only; override with `ERROR_OF_HOME`).
|
|
64
|
+
|
|
65
|
+
## Observation protocol
|
|
66
|
+
|
|
67
|
+
Any program, in any language, can report its own boundary by printing one line to stderr:
|
|
68
|
+
|
|
69
|
+
```
|
|
70
|
+
ERROR-OF {"class": "Representation", "boundary": "...", "observation": "...",
|
|
71
|
+
"assumption": "...", "transformation": "...", "outcome": "..."}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
These are first-hand observations and are listed above pattern-based inferences.
|
|
75
|
+
A run that exits 0 after reporting observations has status `continued`.
|
|
76
|
+
|
|
77
|
+
## Example: `examples/pdf2html`
|
|
78
|
+
|
|
79
|
+
```
|
|
80
|
+
pip install pdfminer.six
|
|
81
|
+
./error-of run python3 examples/pdf2html/pdf2html.py input.pdf out.html
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Tries layout representations in turn, checks invariants after each one, and reports
|
|
85
|
+
every violation as an observation. Case study: `docs/case-studies/pdf2html.md`.
|
|
86
|
+
|
|
87
|
+
## Self-healing: `error_of/heal.py`
|
|
88
|
+
|
|
89
|
+
A heal transforms the input, never the code (the PRD lists "automatic code fixer"
|
|
90
|
+
as a non-goal). A heal is accepted only if its invariant confirms it preserved what
|
|
91
|
+
must be preserved; otherwise the original error is raised unchanged. Every attempt
|
|
92
|
+
is reported as an observation. Example: `examples/self_heal_phinary.py`, where the
|
|
93
|
+
`str.replace` heal is rejected because it changes the number and the carry heal is
|
|
94
|
+
accepted.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
error_of/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
error_of/__main__.py,sha256=7Rp7RTr3Wjy-XNx2zU1WCNEKt2oqpvtkRKB5p8uicpw,58
|
|
3
|
+
error_of/cli.py,sha256=RpYsDyBEVv-OR_43gWw1t6_D5zINfUedArQA-EIOJPw,4156
|
|
4
|
+
error_of/core.py,sha256=Wr7SgnOP_wEXYFpj9PYaXPrr3m4POaCuM8LvKNZCYgQ,11082
|
|
5
|
+
error_of/heal.py,sha256=GMDCHNx7BgbPqqAyEeP-fp3JpTx_ETGl2nmn0eEtgMA,2960
|
|
6
|
+
error_of/walk.py,sha256=Ua133sBfbPfprW5QanBoiCR50xFYZvtit3u8aCEcO_s,3922
|
|
7
|
+
error_of-0.1.0.dist-info/METADATA,sha256=03JSzRHWaAb0tO9jeLLof25B3wzLMVlPn6R8Qmb2dkU,3858
|
|
8
|
+
error_of-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
9
|
+
error_of-0.1.0.dist-info/entry_points.txt,sha256=ZgTg8FgS9MgOhy9ZedXZCkErP0b6huUchtlDisZzfEw,47
|
|
10
|
+
error_of-0.1.0.dist-info/top_level.txt,sha256=zr9pedQHMPfFYH7FOs5aHrnofuQ2-EVsqBAtVJ3g4yY,9
|
|
11
|
+
error_of-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
error_of
|