error-of 0.1.0__tar.gz
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-0.1.0/PKG-INFO +94 -0
- error_of-0.1.0/README.md +76 -0
- error_of-0.1.0/error_of/__init__.py +0 -0
- error_of-0.1.0/error_of/__main__.py +3 -0
- error_of-0.1.0/error_of/cli.py +122 -0
- error_of-0.1.0/error_of/core.py +251 -0
- error_of-0.1.0/error_of/heal.py +66 -0
- error_of-0.1.0/error_of/walk.py +99 -0
- error_of-0.1.0/error_of.egg-info/PKG-INFO +94 -0
- error_of-0.1.0/error_of.egg-info/SOURCES.txt +17 -0
- error_of-0.1.0/error_of.egg-info/dependency_links.txt +1 -0
- error_of-0.1.0/error_of.egg-info/entry_points.txt +2 -0
- error_of-0.1.0/error_of.egg-info/requires.txt +11 -0
- error_of-0.1.0/error_of.egg-info/top_level.txt +1 -0
- error_of-0.1.0/pyproject.toml +25 -0
- error_of-0.1.0/setup.cfg +4 -0
- error_of-0.1.0/tests/test_core.py +39 -0
- error_of-0.1.0/tests/test_organism.py +79 -0
- error_of-0.1.0/tests/test_walk.py +90 -0
error_of-0.1.0/PKG-INFO
ADDED
|
@@ -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.
|
error_of-0.1.0/README.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# error-of
|
|
2
|
+
|
|
3
|
+
Errors as observations. See `PRD.md` and `docs/architecture.md`.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
./error-of run <command ...> run, capture, classify, report (output/<id>.md, .json)
|
|
7
|
+
./error-of report <id> show a stored case
|
|
8
|
+
./error-of search <text> search stored cases
|
|
9
|
+
./error-of patterns recurring classes and signatures
|
|
10
|
+
./error-of walk <e1> <e2> ... diagnose a walk from its signed errors
|
|
11
|
+
python3 -m unittest discover tests
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
How error-of fits a larger loop (reconstruct, run, read the error, keep two edges,
|
|
15
|
+
gate): `docs/construct.md`.
|
|
16
|
+
|
|
17
|
+
## Side and walk
|
|
18
|
+
|
|
19
|
+
Every case now carries a **side** when the error has a direction: `too big`
|
|
20
|
+
(Memory, Storage: trade time for space), `too slow` (Time: trade space for time),
|
|
21
|
+
`too coarse` (Precision). Programs can report their own with `"side"` and a signed
|
|
22
|
+
`"error"` in the protocol line.
|
|
23
|
+
|
|
24
|
+
`error_of/walk.py` keeps only the last two errors of a walk toward a target and
|
|
25
|
+
reads one number from them, `k = (e_now + e_prev) / e_last`:
|
|
26
|
+
|k| < 2 cycling, k = +2 drifting, k < -2 converging while bracketing, and so on.
|
|
27
|
+
Cycles are called from three numbers, without a list of visited states.
|
|
28
|
+
|
|
29
|
+
## Organisms: programs generated, not written
|
|
30
|
+
|
|
31
|
+
Four small, runnable cases, each with a one-page description in `docs/organisms/`:
|
|
32
|
+
|
|
33
|
+
| | goal | starts with | learns | code |
|
|
34
|
+
|---|---|---|---|---|
|
|
35
|
+
| [X](docs/organisms/X.md) | answer a question | a frozen proposer | nothing; carries two sides | `examples/reconstruct/fib.py` |
|
|
36
|
+
| [A](docs/organisms/A.md) | find a program from examples | four seed moves | words from successes, refutations from failures | `examples/organism/organism.py` |
|
|
37
|
+
| [B](docs/organisms/B.md) | same as A | seed moves, in A's world | from A's refutations | same |
|
|
38
|
+
| [C](docs/organisms/C.md) | same as A, plus an unseen goal | A's words | from A's successes | same |
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
python3 examples/reconstruct/fib.py # X, ~3 s
|
|
42
|
+
./error-of run python3 examples/organism/organism.py # A, B, C, recorded as observations
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Knowledge base: `~/.error-of/cases.jsonl` (append-only; override with `ERROR_OF_HOME`).
|
|
46
|
+
|
|
47
|
+
## Observation protocol
|
|
48
|
+
|
|
49
|
+
Any program, in any language, can report its own boundary by printing one line to stderr:
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
ERROR-OF {"class": "Representation", "boundary": "...", "observation": "...",
|
|
53
|
+
"assumption": "...", "transformation": "...", "outcome": "..."}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
These are first-hand observations and are listed above pattern-based inferences.
|
|
57
|
+
A run that exits 0 after reporting observations has status `continued`.
|
|
58
|
+
|
|
59
|
+
## Example: `examples/pdf2html`
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
pip install pdfminer.six
|
|
63
|
+
./error-of run python3 examples/pdf2html/pdf2html.py input.pdf out.html
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Tries layout representations in turn, checks invariants after each one, and reports
|
|
67
|
+
every violation as an observation. Case study: `docs/case-studies/pdf2html.md`.
|
|
68
|
+
|
|
69
|
+
## Self-healing: `error_of/heal.py`
|
|
70
|
+
|
|
71
|
+
A heal transforms the input, never the code (the PRD lists "automatic code fixer"
|
|
72
|
+
as a non-goal). A heal is accepted only if its invariant confirms it preserved what
|
|
73
|
+
must be preserved; otherwise the original error is raised unchanged. Every attempt
|
|
74
|
+
is reported as an observation. Example: `examples/self_heal_phinary.py`, where the
|
|
75
|
+
`str.replace` heal is rejected because it changes the number and the carry heal is
|
|
76
|
+
accepted.
|
|
File without changes
|
|
@@ -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())
|
|
@@ -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)
|
|
@@ -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
|
|
@@ -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,17 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
error_of/__init__.py
|
|
4
|
+
error_of/__main__.py
|
|
5
|
+
error_of/cli.py
|
|
6
|
+
error_of/core.py
|
|
7
|
+
error_of/heal.py
|
|
8
|
+
error_of/walk.py
|
|
9
|
+
error_of.egg-info/PKG-INFO
|
|
10
|
+
error_of.egg-info/SOURCES.txt
|
|
11
|
+
error_of.egg-info/dependency_links.txt
|
|
12
|
+
error_of.egg-info/entry_points.txt
|
|
13
|
+
error_of.egg-info/requires.txt
|
|
14
|
+
error_of.egg-info/top_level.txt
|
|
15
|
+
tests/test_core.py
|
|
16
|
+
tests/test_organism.py
|
|
17
|
+
tests/test_walk.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
error_of
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "error-of"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Errors as observations: side, three-error walk diagnostics, and invariant-witnessed self-healing."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [
|
|
13
|
+
{name = "space"}
|
|
14
|
+
]
|
|
15
|
+
dependencies = []
|
|
16
|
+
|
|
17
|
+
[project.optional-dependencies]
|
|
18
|
+
pdf = ["pdfminer.six", "numpy", "pillow"]
|
|
19
|
+
all = ["pdfminer.six", "numpy", "pillow", "playwright"]
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
error-of = "error_of.cli:main"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.packages.find]
|
|
25
|
+
include = ["error_of*"]
|
error_of-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Run: python3 -m unittest discover tests"""
|
|
2
|
+
import json, os, sys, tempfile, unittest
|
|
3
|
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
4
|
+
os.environ["ERROR_OF_HOME"] = tempfile.mkdtemp()
|
|
5
|
+
from error_of import core
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Core(unittest.TestCase):
|
|
9
|
+
def test_bash_running_python_is_syntax_and_context(self):
|
|
10
|
+
err = ("f.py: line 1: import: command not found\n"
|
|
11
|
+
"f.py: line 6: syntax error near unexpected token `('")
|
|
12
|
+
self.assertEqual({h["class"] for h in core.classify(err)}, {"Syntax", "Context"})
|
|
13
|
+
|
|
14
|
+
def test_self_report_is_parsed_and_ranked_first(self):
|
|
15
|
+
err = 'ERROR-OF {"class": "Representation", "boundary": "b"}\nValueError: x'
|
|
16
|
+
cap = dict(command=["x"], stdout="", stderr=err, exit_code=0, runtime_s=0,
|
|
17
|
+
environment={}, time="t")
|
|
18
|
+
case = core.build_case(cap)
|
|
19
|
+
self.assertEqual(case["status"], "continued")
|
|
20
|
+
self.assertEqual(case["observations"][0]["class"], "Representation")
|
|
21
|
+
|
|
22
|
+
def test_signature_ignores_paths_and_numbers(self):
|
|
23
|
+
a = core.signature("File /a/b.py, line 12\nKeyError: 3")
|
|
24
|
+
b = core.signature("File /c/d.py, line 99\nKeyError: 7")
|
|
25
|
+
self.assertEqual(a, b)
|
|
26
|
+
|
|
27
|
+
def test_unknown_is_explicit(self):
|
|
28
|
+
cap = dict(command=["x"], stdout="", stderr="zzz", exit_code=1, runtime_s=0,
|
|
29
|
+
environment={}, time="t")
|
|
30
|
+
self.assertEqual(core.build_case(cap)["inferences"][0]["class"], "Unknown")
|
|
31
|
+
|
|
32
|
+
def test_store_is_append_only(self):
|
|
33
|
+
core.store({"id": "a", "signature": None})
|
|
34
|
+
core.store({"id": "b", "signature": None})
|
|
35
|
+
self.assertEqual([c["id"] for c in core.load_cases()][-2:], ["a", "b"])
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
if __name__ == "__main__":
|
|
39
|
+
unittest.main()
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Run: python3 -m unittest discover tests"""
|
|
2
|
+
import os, subprocess, sys, tempfile, unittest
|
|
3
|
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
4
|
+
sys.path.insert(0, ROOT)
|
|
5
|
+
sys.path.insert(0, os.path.join(ROOT, "examples", "organism"))
|
|
6
|
+
os.environ.setdefault("ERROR_OF_HOME", tempfile.mkdtemp())
|
|
7
|
+
from error_of import core
|
|
8
|
+
import organism as O
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def correct(o, goal, f, xs=range(-6, 7)):
|
|
12
|
+
w = o.words[goal][0]
|
|
13
|
+
return all(w(x) == f(x) for x in xs)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Learning(unittest.TestCase):
|
|
17
|
+
def setUp(self):
|
|
18
|
+
self.world = O.World()
|
|
19
|
+
self.a = O.Organism("A", self.world)
|
|
20
|
+
self.results = O.live(self.a, O.CURRICULUM)
|
|
21
|
+
|
|
22
|
+
def test_seed_only_cannot_reach_the_deep_goal(self):
|
|
23
|
+
r = O.Organism("s", O.World()).solve(*O.CURRICULUM[-1])
|
|
24
|
+
self.assertIsNone(r["program"])
|
|
25
|
+
|
|
26
|
+
def test_a_reaches_every_goal_with_its_own_words(self):
|
|
27
|
+
self.assertTrue(all(r["program"] for r in self.results))
|
|
28
|
+
self.assertEqual(self.results[-1]["program"], "4plus1sq . 4plus1sq")
|
|
29
|
+
self.assertTrue(correct(self.a, "deep", lambda x: (4 * (x + 1) ** 2 + 1) ** 2 * 4))
|
|
30
|
+
|
|
31
|
+
def test_b_needs_one_check_per_goal_but_still_generates(self):
|
|
32
|
+
b = O.Organism("B", self.world)
|
|
33
|
+
rb = O.live(b, O.CURRICULUM)
|
|
34
|
+
self.assertEqual([r["checks"] for r in rb], [1] * len(O.CURRICULUM))
|
|
35
|
+
self.assertGreater(sum(r["built"] for r in rb), len(O.CURRICULUM))
|
|
36
|
+
|
|
37
|
+
def test_refutations_carry_over_to_a_renamed_goal(self):
|
|
38
|
+
newborn = O.Organism("D", self.world) # no words learned yet
|
|
39
|
+
r = newborn.solve("square_of_next", O.CURRICULUM[1][1])
|
|
40
|
+
self.assertEqual((r["checks"], r["program"]), (1, "inc . sq"))
|
|
41
|
+
|
|
42
|
+
def test_refutations_carry_over_to_an_overlapping_goal(self):
|
|
43
|
+
ex = O.examples_of(lambda x: (x + 1) ** 2, xs=(0, 1, 3, 4)) # shares 0 and 1
|
|
44
|
+
fresh = O.Organism("F", O.World()).solve("g", ex)["checks"]
|
|
45
|
+
shared = O.Organism("G", self.world).solve("g", ex)["checks"]
|
|
46
|
+
self.assertLess(shared, fresh)
|
|
47
|
+
|
|
48
|
+
def test_a_refutation_never_blocks_a_right_answer(self):
|
|
49
|
+
# inc was refuted for times4 by (1 -> 4); for "next" (1 -> 2) it is right
|
|
50
|
+
r = O.Organism("H", self.world).solve("next", O.examples_of(lambda x: x + 1))
|
|
51
|
+
self.assertEqual((r["checks"], r["program"]), (1, "inc"))
|
|
52
|
+
|
|
53
|
+
def test_c_solves_an_unseen_goal_a_newborn_cannot(self):
|
|
54
|
+
c = O.Organism("C", O.World(), library=self.a.library)
|
|
55
|
+
newborn = O.Organism("n", O.World()).solve(*O.UNSEEN)
|
|
56
|
+
child = c.solve(*O.UNSEEN)
|
|
57
|
+
self.assertIsNone(newborn["program"])
|
|
58
|
+
self.assertIsNotNone(child["program"])
|
|
59
|
+
self.assertTrue(correct(c, "unseen", lambda x: 16 * ((x + 1) ** 2 + 1) ** 2))
|
|
60
|
+
|
|
61
|
+
def test_forgetting_keeps_seeds_and_respects_capacity(self):
|
|
62
|
+
small = O.Organism("S", O.World(), capacity=6)
|
|
63
|
+
O.live(small, O.CURRICULUM)
|
|
64
|
+
self.assertLessEqual(len(small.words), 6)
|
|
65
|
+
self.assertTrue(all(k in small.words for k in O.SEED))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Observed(unittest.TestCase):
|
|
69
|
+
def test_a_life_is_recorded_by_error_of(self):
|
|
70
|
+
cap = core.capture([sys.executable, os.path.join(ROOT, "examples", "organism", "organism.py")])
|
|
71
|
+
case = core.build_case(cap)
|
|
72
|
+
self.assertEqual(case["exit_code"], 0)
|
|
73
|
+
self.assertEqual(case["status"], "continued")
|
|
74
|
+
stopped = [o for o in case["observations"] if o.get("outcome") == "stopped"]
|
|
75
|
+
self.assertTrue(stopped and all(o["side"] == "too slow" for o in stopped))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
if __name__ == "__main__":
|
|
79
|
+
unittest.main()
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Run: python3 -m unittest discover tests"""
|
|
2
|
+
import math, os, sys, tempfile, unittest
|
|
3
|
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
4
|
+
os.environ.setdefault("ERROR_OF_HOME", tempfile.mkdtemp())
|
|
5
|
+
from error_of import core
|
|
6
|
+
from error_of.walk import Walk, diagnose
|
|
7
|
+
|
|
8
|
+
PHI = (1 + 5 ** 0.5) / 2
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def run(errors):
|
|
12
|
+
w = Walk()
|
|
13
|
+
return [w.step(e) for e in errors][-1]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Side(unittest.TestCase):
|
|
17
|
+
def test_memory_error_is_too_big(self):
|
|
18
|
+
h = core.classify("MemoryError")[0]
|
|
19
|
+
self.assertEqual((h["class"], h["side"]), ("Memory", "too big"))
|
|
20
|
+
self.assertIn("trade time for space", h["trade"])
|
|
21
|
+
|
|
22
|
+
def test_timeout_is_too_slow(self):
|
|
23
|
+
h = core.classify("[error-of] timeout after 3s")[0]
|
|
24
|
+
self.assertEqual(h["side"], "too slow")
|
|
25
|
+
|
|
26
|
+
def test_syntax_has_no_side(self):
|
|
27
|
+
self.assertIsNone(core.classify("SyntaxError: invalid syntax")[0]["side"])
|
|
28
|
+
|
|
29
|
+
def test_self_reported_side_wins(self):
|
|
30
|
+
err = 'ERROR-OF {"class": "Representation", "boundary": "gate", "side": "too low", "error": -3}\nMemoryError'
|
|
31
|
+
cap = dict(command=["x"], stdout="", stderr=err, exit_code=1, runtime_s=0,
|
|
32
|
+
environment={}, time="t")
|
|
33
|
+
self.assertEqual(core.build_case(cap)["side"], "too low")
|
|
34
|
+
|
|
35
|
+
def test_pattern_side_when_no_report(self):
|
|
36
|
+
cap = dict(command=["x"], stdout="", stderr="MemoryError", exit_code=1, runtime_s=0,
|
|
37
|
+
environment={}, time="t")
|
|
38
|
+
self.assertEqual(core.build_case(cap)["side"], "too big")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class WalkDiagnosis(unittest.TestCase):
|
|
42
|
+
def test_alternating_phi_errors_bracket_and_converge_at_one_over_phi(self):
|
|
43
|
+
d = run([(-1 / PHI) ** n for n in range(6)])
|
|
44
|
+
self.assertEqual(d["state"], "converging")
|
|
45
|
+
self.assertTrue(d["bracketing"])
|
|
46
|
+
self.assertAlmostEqual(d["k"], -(PHI + 1 / PHI), places=9) # -sqrt(5)
|
|
47
|
+
self.assertAlmostEqual(d["rate"], 1 / PHI, places=9)
|
|
48
|
+
|
|
49
|
+
def test_one_sided_shrinking_converges(self):
|
|
50
|
+
d = run([8, 4, 2, 1])
|
|
51
|
+
self.assertEqual((d["state"], d["bracketing"]), ("converging", False))
|
|
52
|
+
self.assertAlmostEqual(d["rate"], 0.5)
|
|
53
|
+
|
|
54
|
+
def test_rotation_is_cycling(self):
|
|
55
|
+
# e_n = cos(0.7 n) obeys e_{n+1} + e_{n-1} = 2cos(0.7) e_n, |k| < 2
|
|
56
|
+
d = run([math.cos(0.7 * n) for n in range(1, 5)])
|
|
57
|
+
self.assertEqual(d["state"], "cycling")
|
|
58
|
+
self.assertAlmostEqual(d["k"], 2 * math.cos(0.7), places=9)
|
|
59
|
+
|
|
60
|
+
def test_two_value_loop_is_cycling(self):
|
|
61
|
+
# the "1 - S forever" loop: the error flips between the same two values
|
|
62
|
+
self.assertEqual(run([1, -1, 1, -1])["state"], "cycling") # k = -2, r = -1
|
|
63
|
+
self.assertEqual(run([2, -1, 2, -1])["state"], "cycling") # |k| < 2
|
|
64
|
+
|
|
65
|
+
def test_constant_step_is_drifting(self):
|
|
66
|
+
self.assertEqual(run([10, 9, 8, 7])["state"], "drifting")
|
|
67
|
+
|
|
68
|
+
def test_no_change_is_stuck(self):
|
|
69
|
+
self.assertEqual(run([5, 5, 5])["state"], "stuck")
|
|
70
|
+
|
|
71
|
+
def test_growing_is_diverging(self):
|
|
72
|
+
d = run([1, 3, 9, 27])
|
|
73
|
+
self.assertEqual(d["state"], "diverging")
|
|
74
|
+
self.assertAlmostEqual(d["rate"], 3.0)
|
|
75
|
+
|
|
76
|
+
def test_zero_is_arrived(self):
|
|
77
|
+
self.assertEqual(run([4, -2, 0])["state"], "arrived")
|
|
78
|
+
|
|
79
|
+
def test_memory_is_two_errors(self):
|
|
80
|
+
w = Walk()
|
|
81
|
+
for e in [9, 7, 5, 3]:
|
|
82
|
+
w.step(e)
|
|
83
|
+
self.assertEqual(w.edges, (5, 3))
|
|
84
|
+
|
|
85
|
+
def test_warming_up(self):
|
|
86
|
+
self.assertEqual(diagnose(None, 3, 2)["state"], "warming up")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
if __name__ == "__main__":
|
|
90
|
+
unittest.main()
|