gdp-wired 0.50.1 → 0.50.3
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.
- package/README.md +4 -2
- package/dist/core/cli.d.ts +12 -1
- package/dist/core/cli.js +64 -26
- package/dist/core/discover.d.ts +6 -1
- package/dist/core/discover.js +54 -7
- package/dist/core/dsl-deadline.d.ts +3 -0
- package/dist/core/dsl-deadline.js +26 -2
- package/dist/core/dsl.d.ts +3 -1
- package/dist/core/dsl.js +97 -32
- package/dist/core/effect.d.ts +12 -0
- package/dist/core/effect.js +26 -9
- package/dist/core/ex/harness.exs +171 -5
- package/dist/core/extract-c.js +64 -7
- package/dist/core/extract-check.d.ts +5 -1
- package/dist/core/extract-check.js +28 -10
- package/dist/core/extract-go-check.js +130 -3
- package/dist/core/extract-go.js +8 -2
- package/dist/core/extract-jvm.js +2 -2
- package/dist/core/extract-rs.js +51 -5
- package/dist/core/extract-step.js +49 -6
- package/dist/core/extract-swift.js +47 -3
- package/dist/core/extract.d.ts +9 -0
- package/dist/core/infer.d.ts +8 -0
- package/dist/core/infer.js +133 -16
- package/dist/core/jvm/Harness.java +135 -3
- package/dist/core/jvm/Rt.java +66 -4
- package/dist/core/laws.d.ts +4 -0
- package/dist/core/laws.js +59 -10
- package/dist/core/native-law.d.ts +3 -1
- package/dist/core/native-law.js +126 -14
- package/dist/core/native-observations.d.ts +20 -0
- package/dist/core/native-observations.js +41 -0
- package/dist/core/native-wire.d.ts +2 -0
- package/dist/core/native-wire.js +99 -0
- package/dist/core/py/harness.py +53 -2
- package/dist/core/rb/harness.rb +178 -9
- package/dist/core/search-termination.d.ts +35 -0
- package/dist/core/search-termination.js +13 -0
- package/dist/core/search-watchdog.d.ts +8 -0
- package/dist/core/search-watchdog.js +34 -0
- package/dist/core/source-check.d.ts +5 -0
- package/dist/core/source-check.js +21 -0
- package/dist/core/swift/Harness.swift +65 -4
- package/dist/core/swift/Main.swift +27 -4
- package/dist/core/wall.d.ts +3 -1
- package/dist/core/wall.js +7 -4
- package/dist/core/work-refusal.d.ts +3 -0
- package/dist/core/work-refusal.js +8 -0
- package/dist/kernel/prove.d.ts +2 -0
- package/dist/kernel/prove.js +13 -5
- package/dist/kernel/reader.js +5 -1
- package/dist/lean-kernel/axiom-audit.js +5 -2
- package/dist/lean-kernel/emit.d.ts +1 -0
- package/dist/lean-kernel/emit.js +22 -4
- package/package.json +1 -1
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) &&
|
|
2
|
+
(Object.getPrototypeOf(value) === null || Object.getPrototypeOf(value) === Object.prototype);
|
|
3
|
+
export function validateNativeObservations(value, allowedCalls) {
|
|
4
|
+
if (!record(value) || !Number.isSafeInteger(value.invocation) || value.invocation <= 0 || !record(value.calls))
|
|
5
|
+
throw new Error('native observation invocation/calls unavailable');
|
|
6
|
+
if (value.error !== undefined && value.error !== null)
|
|
7
|
+
throw new Error(`native observation unavailable: ${typeof value.error === 'string' ? value.error : 'invalid non-string error payload'}`);
|
|
8
|
+
if (value.clock !== undefined && (typeof value.clock !== 'number' || !Number.isSafeInteger(value.clock)))
|
|
9
|
+
throw new Error('native observed clock is outside the exact integer range');
|
|
10
|
+
for (const [key, call] of Object.entries(value.calls)) {
|
|
11
|
+
if (!allowedCalls.has(key))
|
|
12
|
+
throw new Error(`native observation of unbound call ${key}`);
|
|
13
|
+
if (!record(call))
|
|
14
|
+
throw new Error(`native observation of ${key} is not a record`);
|
|
15
|
+
if (call.kind === 'returned') {
|
|
16
|
+
if (!Object.hasOwn(call, 'value') || Object.hasOwn(call, 'raised'))
|
|
17
|
+
throw new Error(`ambiguous native return of ${key}`);
|
|
18
|
+
if (typeof call.value === 'number' && !Number.isSafeInteger(call.value))
|
|
19
|
+
throw new Error(`native return of ${key} is outside the exact integer range`);
|
|
20
|
+
}
|
|
21
|
+
else if (call.kind === 'raised') {
|
|
22
|
+
if (typeof call.raised !== 'string' || !call.raised || Object.hasOwn(call, 'value'))
|
|
23
|
+
throw new Error(`ambiguous native exception of ${key}`);
|
|
24
|
+
}
|
|
25
|
+
else
|
|
26
|
+
throw new Error(`native observation of ${key} has no outcome`);
|
|
27
|
+
}
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
// One reader per native harness. Repeated access to a current response is
|
|
31
|
+
// cached by its adapter; a later response must never reuse an old invocation.
|
|
32
|
+
export function nativeObservationSequence(allowedCalls) {
|
|
33
|
+
let previous = 0;
|
|
34
|
+
return value => {
|
|
35
|
+
const observed = validateNativeObservations(value, allowedCalls);
|
|
36
|
+
if (observed.invocation <= previous)
|
|
37
|
+
throw new Error('native execution observation is stale or repeated');
|
|
38
|
+
previous = observed.invocation;
|
|
39
|
+
return observed;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { nativeSnapshot } from "./source-check.js";
|
|
2
|
+
// Bindings are retained directly by the journal. Snapshot the decoder's mutable
|
|
3
|
+
// canonical objects before any later state/binding frame can update them.
|
|
4
|
+
export const snapshotNativeBindings = (decode, wire) => nativeSnapshot(decode(wire));
|
|
5
|
+
// Decode identity-bearing snapshots returned by the real native harness. This
|
|
6
|
+
// is observation transport only: no model values or proof results are supplied.
|
|
7
|
+
export function nativeWireDecoder(maxObjects = 100000, maxNodes = 10000) {
|
|
8
|
+
if (!Number.isSafeInteger(maxObjects) || maxObjects < 1 || !Number.isSafeInteger(maxNodes) || maxNodes < 1)
|
|
9
|
+
throw Error('invalid native snapshot bounds');
|
|
10
|
+
const objects = new Map();
|
|
11
|
+
return wire => {
|
|
12
|
+
let nodes = 0;
|
|
13
|
+
const seen = new Set();
|
|
14
|
+
const record = (value) => {
|
|
15
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
16
|
+
throw Error('invalid native snapshot node');
|
|
17
|
+
return value;
|
|
18
|
+
};
|
|
19
|
+
const decode = (value) => {
|
|
20
|
+
if (++nodes > maxNodes)
|
|
21
|
+
throw Error('native snapshot exceeds node bound');
|
|
22
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean')
|
|
23
|
+
return value;
|
|
24
|
+
if (typeof value === 'number') {
|
|
25
|
+
if (!Number.isSafeInteger(value))
|
|
26
|
+
throw Error('unsafe native snapshot number');
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
const node = record(value), id = node.id, kind = node.kind;
|
|
30
|
+
if (typeof id !== 'string' || !/^[1-9][0-9]*$/.test(id))
|
|
31
|
+
throw Error('invalid native snapshot identity');
|
|
32
|
+
if (kind === 'ref') {
|
|
33
|
+
if (!seen.has(id))
|
|
34
|
+
throw Error('unbound native snapshot reference');
|
|
35
|
+
return objects.get(id).value;
|
|
36
|
+
}
|
|
37
|
+
if (kind !== 'object' && kind !== 'array' && kind !== 'map' && kind !== 'set')
|
|
38
|
+
throw Error('unsupported native snapshot kind');
|
|
39
|
+
if (seen.has(id))
|
|
40
|
+
throw Error('duplicate native snapshot identity');
|
|
41
|
+
seen.add(id);
|
|
42
|
+
let kept = objects.get(id);
|
|
43
|
+
if (kept && kept.kind !== kind)
|
|
44
|
+
throw Error('native snapshot identity changed kind');
|
|
45
|
+
if (!kept) {
|
|
46
|
+
if (objects.size >= maxObjects)
|
|
47
|
+
throw Error('native snapshot exceeds identity bound');
|
|
48
|
+
const fresh = kind === 'array' ? [] : kind === 'map' ? new Map() : kind === 'set' ? new Set() : Object.create(null);
|
|
49
|
+
kept = { kind, value: fresh };
|
|
50
|
+
objects.set(id, kept);
|
|
51
|
+
}
|
|
52
|
+
if (!Array.isArray(node.items))
|
|
53
|
+
throw Error('invalid native snapshot entries');
|
|
54
|
+
if (kind === 'array') {
|
|
55
|
+
const target = kept.value;
|
|
56
|
+
target.length = 0;
|
|
57
|
+
for (const item of node.items)
|
|
58
|
+
target.push(decode(item));
|
|
59
|
+
}
|
|
60
|
+
else if (kind === 'set') {
|
|
61
|
+
const target = kept.value;
|
|
62
|
+
target.clear();
|
|
63
|
+
for (const item of node.items) {
|
|
64
|
+
const value = decode(item);
|
|
65
|
+
if (target.has(value))
|
|
66
|
+
throw Error('duplicate native snapshot set item');
|
|
67
|
+
target.add(value);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
else if (kind === 'map') {
|
|
71
|
+
const target = kept.value;
|
|
72
|
+
target.clear();
|
|
73
|
+
for (const item of node.items) {
|
|
74
|
+
if (!Array.isArray(item) || item.length !== 2 || (typeof item[0] !== 'string' && typeof item[0] !== 'number'))
|
|
75
|
+
throw Error('invalid native snapshot map entry');
|
|
76
|
+
const key = decode(item[0]);
|
|
77
|
+
if (target.has(key))
|
|
78
|
+
throw Error('duplicate native snapshot map key');
|
|
79
|
+
target.set(key, decode(item[1]));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
const target = kept.value;
|
|
84
|
+
for (const key of Object.keys(target))
|
|
85
|
+
delete target[key];
|
|
86
|
+
for (const item of node.items) {
|
|
87
|
+
if (!Array.isArray(item) || item.length !== 2 || typeof item[0] !== 'string' || Object.hasOwn(target, item[0]))
|
|
88
|
+
throw Error('invalid native snapshot object entry');
|
|
89
|
+
Object.defineProperty(target, item[0], { value: decode(item[1]), writable: true, enumerable: true, configurable: true });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return kept.value;
|
|
93
|
+
};
|
|
94
|
+
const envelope = record(wire);
|
|
95
|
+
if (envelope.version !== 1)
|
|
96
|
+
throw Error('unsupported native snapshot version');
|
|
97
|
+
return decode(envelope.root);
|
|
98
|
+
};
|
|
99
|
+
}
|
package/dist/core/py/harness.py
CHANGED
|
@@ -12,6 +12,7 @@ CUR = {}
|
|
|
12
12
|
EFF = {}
|
|
13
13
|
HIT = set()
|
|
14
14
|
S = {}
|
|
15
|
+
NATIVE_OBJECTS = {}
|
|
15
16
|
|
|
16
17
|
def datetime_in(v, unit):
|
|
17
18
|
epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc if unit == 'datetime-utc' else None)
|
|
@@ -591,7 +592,7 @@ def hello(req):
|
|
|
591
592
|
S['cls'] = getattr(mod, req['cls'].rpartition('.')[2]) if req.get('cls') else None
|
|
592
593
|
S['loop'] = asyncio.new_event_loop()
|
|
593
594
|
asyncio.set_event_loop(S['loop'])
|
|
594
|
-
return {'ok': True}
|
|
595
|
+
return {'ok': True, 'nativeSnapshot': 1, 'nativeBindings': 1, 'nativeEquality': 'scalar'}
|
|
595
596
|
|
|
596
597
|
def make(args):
|
|
597
598
|
global OBJ_STORES
|
|
@@ -639,6 +640,19 @@ def call(req):
|
|
|
639
640
|
try: kwargs = fixed_args(req['a'], {})
|
|
640
641
|
except OverflowError as e:
|
|
641
642
|
return {'outside': f'argument outside the declared runtime domain: {e}'}
|
|
643
|
+
# Bind the actual callable's Python signature, before the method can mutate
|
|
644
|
+
# its arguments. Never reconstruct native law inputs from the symbolic IR.
|
|
645
|
+
try:
|
|
646
|
+
native_fn = fn.__func__ if isinstance(fn, types.MethodType) else fn
|
|
647
|
+
if not isinstance(native_fn, types.FunctionType):
|
|
648
|
+
raise ValueError('unsupported native callable for parameter capture')
|
|
649
|
+
if any(dict.__contains__(native_fn.__dict__, name) for name in ('__signature__', '__wrapped__', '__text_signature__')):
|
|
650
|
+
raise ValueError('customized native signature metadata is unsupported')
|
|
651
|
+
bound = inspect.signature(fn, follow_wrapped=False).bind(**kwargs)
|
|
652
|
+
bound.apply_defaults()
|
|
653
|
+
native_bindings = {'snapshot': native_state(types.SimpleNamespace(**bound.arguments), select=False)}
|
|
654
|
+
except Exception as e:
|
|
655
|
+
native_bindings = {'error': f'{type(e).__name__}: {e}'[:300]}
|
|
642
656
|
before = frames(obj if S['cls'] is not None else None)
|
|
643
657
|
snap = state_of(obj, stores) if S.get('discard') and S['cls'] is not None else None
|
|
644
658
|
sys.settrace(tracer)
|
|
@@ -657,7 +671,43 @@ def call(req):
|
|
|
657
671
|
after = frames(obj if S['cls'] is not None else None)
|
|
658
672
|
for k in before:
|
|
659
673
|
if after.get(k) != before[k]: return {'frame': k}
|
|
660
|
-
return {'out': tag(out), **({'err': err} if err is not None else {}), **({'effects': dict(EFF)} if EFF else {})}
|
|
674
|
+
return {'out': tag(out), 'nativeBindings': native_bindings, **({'err': err} if err is not None else {}), **({'effects': dict(EFF)} if EFF else {})}
|
|
675
|
+
|
|
676
|
+
# Native observation transport for ordered containers. Retain real references
|
|
677
|
+
# so Python cannot recycle an address and manufacture cross-snapshot identity.
|
|
678
|
+
def native_state(obj, select=True):
|
|
679
|
+
seen = set()
|
|
680
|
+
count = [0]
|
|
681
|
+
def encode(value, names=None):
|
|
682
|
+
count[0] += 1
|
|
683
|
+
if count[0] > 10000: raise ValueError('native snapshot exceeds node bound')
|
|
684
|
+
if value is None or isinstance(value, (str, bool)): return value
|
|
685
|
+
if isinstance(value, (int, float)):
|
|
686
|
+
if not (-9007199254740991 <= value <= 9007199254740991) or int(value) != value:
|
|
687
|
+
raise ValueError('native snapshot number is outside exact integer range')
|
|
688
|
+
return int(value)
|
|
689
|
+
address = id(value)
|
|
690
|
+
if address not in NATIVE_OBJECTS:
|
|
691
|
+
if len(NATIVE_OBJECTS) >= 100000: raise ValueError('native snapshot exceeds identity bound')
|
|
692
|
+
NATIVE_OBJECTS[address] = (value, str(len(NATIVE_OBJECTS) + 1))
|
|
693
|
+
ident = NATIVE_OBJECTS[address][1]
|
|
694
|
+
if ident in seen: return {'kind': 'ref', 'id': ident}
|
|
695
|
+
seen.add(ident)
|
|
696
|
+
if isinstance(value, list):
|
|
697
|
+
return {'kind': 'array', 'id': ident, 'items': [encode(x) for x in value]}
|
|
698
|
+
if type(value) is set:
|
|
699
|
+
return {'kind': 'set', 'id': ident, 'items': [encode(x) for x in value]}
|
|
700
|
+
if isinstance(value, (set, frozenset)):
|
|
701
|
+
raise ValueError('unsupported native snapshot set type')
|
|
702
|
+
if isinstance(value, dict):
|
|
703
|
+
if any(not isinstance(k, (str, int, float)) or isinstance(k, bool) for k in value):
|
|
704
|
+
raise ValueError('unsupported native snapshot map key')
|
|
705
|
+
return {'kind': 'map', 'id': ident, 'items': [[encode(k), encode(v)] for k, v in value.items()]}
|
|
706
|
+
fields = vars(value)
|
|
707
|
+
if names is not None: fields = {name: fields[name] for name in names}
|
|
708
|
+
return {'kind': 'object', 'id': ident, 'items': [[k, encode(v)] for k, v in fields.items()]}
|
|
709
|
+
roots = sorted({l['path'][0] for l in S['leaves'] if l.get('path') and l['kind'] != 'frame'})
|
|
710
|
+
return {'version': 1, 'root': encode(obj, roots if select else None)}
|
|
661
711
|
|
|
662
712
|
def main():
|
|
663
713
|
fin = open(sys.argv[1], 'r'); fout = open(sys.argv[2], 'w')
|
|
@@ -683,6 +733,7 @@ def main():
|
|
|
683
733
|
elif op == 'get':
|
|
684
734
|
obj, stores = OBJS[req['id']]
|
|
685
735
|
res = {'state': state_of(obj, stores)}
|
|
736
|
+
elif op == 'native': res = {'snapshot': native_state(OBJS[req['id']][0])}
|
|
686
737
|
elif op == 'call': res = call(req)
|
|
687
738
|
elif op == 'coverage': res = {'hit': sorted(HIT)}
|
|
688
739
|
else: res = {'error': f"no op {op}"}
|
package/dist/core/rb/harness.rb
CHANGED
|
@@ -11,19 +11,152 @@ NOW = [0]
|
|
|
11
11
|
HIT = {}
|
|
12
12
|
S = {}
|
|
13
13
|
OBJS = {}
|
|
14
|
+
# Real references retained strongly: object_id reuse must never create aliases.
|
|
15
|
+
NATIVE_OBJECTS = {}.compare_by_identity
|
|
16
|
+
NATIVE_INVOCATION = [0]
|
|
17
|
+
NATIVE_IS = Object.instance_method(:instance_of?)
|
|
18
|
+
NATIVE_CLASS = Object.instance_method(:class)
|
|
19
|
+
NATIVE_METHOD = Object.instance_method(:method)
|
|
20
|
+
NATIVE_THREAD = Thread.method(:current)
|
|
21
|
+
NATIVE_CLASS_NAME = Module.instance_method(:name)
|
|
22
|
+
NATIVE_VARS = Object.instance_method(:instance_variables)
|
|
23
|
+
NATIVE_GET_VAR = Object.instance_method(:instance_variable_get)
|
|
24
|
+
NATIVE_EQUAL = BasicObject.instance_method(:equal?)
|
|
25
|
+
NATIVE_COPY_STRING = String.method(:new)
|
|
26
|
+
NATIVE_ARRAY_EACH = Array.instance_method(:each)
|
|
27
|
+
NATIVE_HASH_EACH = Hash.instance_method(:each_pair)
|
|
28
|
+
NATIVE_HASH_DEFAULT = Hash.instance_method(:default)
|
|
29
|
+
NATIVE_HASH_DEFAULT_PROC = Hash.instance_method(:default_proc)
|
|
30
|
+
def native_is?(value, klass) = NATIVE_IS.bind_call(value, klass)
|
|
31
|
+
def native_same?(a, b) = NATIVE_EQUAL.bind_call(a, b)
|
|
32
|
+
def native_class(value) = NATIVE_CLASS.bind_call(value)
|
|
33
|
+
def native_class_name(value) = NATIVE_CLASS_NAME.bind_call(native_class(value))
|
|
34
|
+
def native_state(root, bindings: false, records: false)
|
|
35
|
+
seen = {}
|
|
36
|
+
nodes = 0
|
|
37
|
+
encode = nil
|
|
38
|
+
encode = lambda do |value, object_root = false|
|
|
39
|
+
nodes += 1
|
|
40
|
+
raise ArgumentError, 'native snapshot exceeds node bound' if nodes > 10000
|
|
41
|
+
return value if native_same?(value, nil) || native_same?(value, true) || native_same?(value, false)
|
|
42
|
+
return NATIVE_COPY_STRING.call(value).freeze if native_is?(value, String)
|
|
43
|
+
# Symbols cross the wire as native enum labels, never choice indexes.
|
|
44
|
+
return value.to_s if native_is?(value, Symbol)
|
|
45
|
+
if native_is?(value, Integer) || native_is?(value, Float)
|
|
46
|
+
raise ArgumentError, 'native snapshot number is outside exact integer range' unless value.finite? && value.abs <= 9007199254740991 && value == value.to_i
|
|
47
|
+
return value.to_i
|
|
48
|
+
end
|
|
49
|
+
# A store exposes its actual Hash, retaining keys and native identity.
|
|
50
|
+
value = value.data if native_is?(value, GdpStore)
|
|
51
|
+
unless NATIVE_OBJECTS.key?(value)
|
|
52
|
+
raise ArgumentError, 'native snapshot exceeds identity bound' if NATIVE_OBJECTS.length >= 100000
|
|
53
|
+
NATIVE_OBJECTS[value] = (NATIVE_OBJECTS.length + 1).to_s
|
|
54
|
+
end
|
|
55
|
+
id = NATIVE_OBJECTS[value]
|
|
56
|
+
return {'kind' => 'ref', 'id' => id} if seen[id]
|
|
57
|
+
seen[id] = true
|
|
58
|
+
if native_is?(value, Array)
|
|
59
|
+
kind, items = 'array', []
|
|
60
|
+
NATIVE_ARRAY_EACH.bind_call(value) { |v| items << encode.call(v) }
|
|
61
|
+
elsif native_is?(value, Hash)
|
|
62
|
+
raise ArgumentError, 'unsupported native Hash default' unless native_same?(NATIVE_HASH_DEFAULT.bind_call(value), nil) && native_same?(NATIVE_HASH_DEFAULT_PROC.bind_call(value), nil)
|
|
63
|
+
kind = object_root || records ? 'object' : 'map'
|
|
64
|
+
items = []
|
|
65
|
+
NATIVE_HASH_EACH.bind_call(value) do |k, v|
|
|
66
|
+
valid = object_root || records ? native_is?(k, String) : native_is?(k, String) || native_is?(k, Integer)
|
|
67
|
+
raise ArgumentError, 'unsupported native snapshot map key' unless valid
|
|
68
|
+
items << [encode.call(k), encode.call(v)]
|
|
69
|
+
end
|
|
70
|
+
else
|
|
71
|
+
# Opaque Time/IO/Mutex/etc. have no faithful wire encoding.
|
|
72
|
+
vars = NATIVE_VARS.bind_call(value)
|
|
73
|
+
# An uninitialized Ruby instance variable reads as nil. Observe that
|
|
74
|
+
# actual read for source-declared roots too (e.g. @last before first hit).
|
|
75
|
+
if native_same?(value, root) && !bindings
|
|
76
|
+
declared = (S['leaves'] || []).filter_map { |l| l['path']&.first if l['kind'] != 'frame' }
|
|
77
|
+
vars |= declared.filter_map { |name| name.to_sym if name.is_a?(String) && name.start_with?('@') }
|
|
78
|
+
end
|
|
79
|
+
raise ArgumentError, "unsupported native snapshot object #{native_class(value)}" if vars.empty? && native_class(value) != S['cls']
|
|
80
|
+
kind = 'object'
|
|
81
|
+
items = vars.map { |k| [k.to_s.delete_prefix('@'), encode.call(NATIVE_GET_VAR.bind_call(value, k))] }
|
|
82
|
+
end
|
|
83
|
+
{'kind' => kind, 'id' => id, 'items' => items}
|
|
84
|
+
end
|
|
85
|
+
{'version' => 1, 'root' => encode.call(root, bindings)}
|
|
86
|
+
end
|
|
14
87
|
|
|
88
|
+
# Invocation-local observations contain only values a native operation actually
|
|
89
|
+
# returned/raised. Missing calls stay absent; repeated inconsistent reads refuse.
|
|
90
|
+
NATIVE_EVENTS = [nil]
|
|
91
|
+
NATIVE_EVENT_ERROR = [nil]
|
|
92
|
+
NATIVE_CALL_TYPES = {}
|
|
93
|
+
NATIVE_ACTIVE_THREAD = [nil]
|
|
94
|
+
def native_active? = NATIVE_EVENTS[0] && native_same?(NATIVE_THREAD.call, NATIVE_ACTIVE_THREAD[0])
|
|
95
|
+
def native_scalar(value)
|
|
96
|
+
return value if native_same?(value, nil) || native_same?(value, true) || native_same?(value, false)
|
|
97
|
+
return NATIVE_COPY_STRING.call(value).freeze if native_is?(value, String)
|
|
98
|
+
return value.to_s.freeze if native_is?(value, Symbol)
|
|
99
|
+
if native_is?(value, Integer) || native_is?(value, Float)
|
|
100
|
+
raise ArgumentError, 'native observation number is outside exact integer range' unless value.finite? && value.abs <= 9007199254740991 && value == value.to_i
|
|
101
|
+
return value.to_i
|
|
102
|
+
end
|
|
103
|
+
raise ArgumentError, "unsupported native observation value #{native_class(value)}"
|
|
104
|
+
end
|
|
105
|
+
def native_record(key, outcome, native_type = nil)
|
|
106
|
+
return unless native_active? && (events = NATIVE_EVENTS[0])
|
|
107
|
+
before = events['calls'][key]
|
|
108
|
+
previous_type = NATIVE_CALL_TYPES[key]
|
|
109
|
+
if native_type && previous_type && !native_same?(native_type, previous_type)
|
|
110
|
+
raise ArgumentError, "inconsistent native call type #{key}"
|
|
111
|
+
end
|
|
112
|
+
NATIVE_CALL_TYPES[key] = native_type if native_type
|
|
113
|
+
raise ArgumentError, "inconsistent native call #{key}" if before && before != outcome
|
|
114
|
+
events['calls'][key] = outcome
|
|
115
|
+
rescue StandardError => e
|
|
116
|
+
NATIVE_EVENT_ERROR[0] ||= "#{e.class}: #{e.message}"[0, 300]
|
|
117
|
+
end
|
|
118
|
+
def native_call(key)
|
|
119
|
+
value = yield
|
|
120
|
+
if native_active?
|
|
121
|
+
begin
|
|
122
|
+
native_record(key, {'kind' => 'returned', 'value' => native_scalar(value)}, native_class(value))
|
|
123
|
+
rescue StandardError => e
|
|
124
|
+
NATIVE_EVENT_ERROR[0] ||= "#{e.class}: #{e.message}"[0, 300]
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
value
|
|
128
|
+
rescue Exception => e # Record the actual runtime class, never the requested handler.
|
|
129
|
+
native_record(key, {'kind' => 'raised', 'raised' => native_class_name(e)})
|
|
130
|
+
raise
|
|
131
|
+
end
|
|
132
|
+
def native_clock(value)
|
|
133
|
+
if native_active? && (events = NATIVE_EVENTS[0])
|
|
134
|
+
begin
|
|
135
|
+
actual = native_scalar(value)
|
|
136
|
+
raise ArgumentError, 'inconsistent native clock reads' if events.key?('clock') && events['clock'] != actual
|
|
137
|
+
events['clock'] = actual
|
|
138
|
+
rescue StandardError => e
|
|
139
|
+
NATIVE_EVENT_ERROR[0] ||= "#{e.class}: #{e.message}"[0, 300]
|
|
140
|
+
end
|
|
141
|
+
end
|
|
142
|
+
value
|
|
143
|
+
end
|
|
15
144
|
module GdpClock
|
|
16
|
-
def now(*)
|
|
145
|
+
def now(*)
|
|
146
|
+
value = Time.at(NOW[0])
|
|
147
|
+
native_clock(value.to_i)
|
|
148
|
+
value
|
|
149
|
+
end
|
|
17
150
|
end
|
|
18
151
|
Time.singleton_class.prepend(GdpClock)
|
|
19
152
|
module GdpMono
|
|
20
|
-
def clock_gettime(*a) = a.length > 1 && a[1] != :float_second ? NOW[0] : NOW[0].to_f
|
|
153
|
+
def clock_gettime(*a) = native_clock(a.length > 1 && a[1] != :float_second ? NOW[0] : NOW[0].to_f)
|
|
21
154
|
end
|
|
22
155
|
Process.singleton_class.prepend(GdpMono)
|
|
23
156
|
# A clock object the caller stated: its time is the request's.
|
|
24
157
|
class GdpStatedClock
|
|
25
|
-
def current_time = NOW[0]
|
|
26
|
-
def now = NOW[0]
|
|
158
|
+
def current_time = native_clock(NOW[0])
|
|
159
|
+
def now = native_clock(NOW[0])
|
|
27
160
|
end
|
|
28
161
|
|
|
29
162
|
def enc_num(v)
|
|
@@ -43,7 +176,7 @@ CUR = {}
|
|
|
43
176
|
def answer(key) = (a = CUR[key]).nil? || a['none'] ? nil : build(a)
|
|
44
177
|
# (a call inside a rescue's begin: raises the class the request says; one left out runs as it is unless it raises)
|
|
45
178
|
def raising(key) = (r = CUR[key]&.[]('raise')) && raise(Object.const_get(r), 'gdp: raised where the request says')
|
|
46
|
-
def stub(key) = proc { |*_a, **_k| raising(key); answer(key) }
|
|
179
|
+
def stub(key) = proc { |*_a, **_k| native_call(key) { raising(key); answer(key) } }
|
|
47
180
|
# A store (stated, or an injected dependency inferred): get, set and delete over a Hash that keeps what is set; its
|
|
48
181
|
# other methods answered.
|
|
49
182
|
class GdpStore
|
|
@@ -171,9 +304,9 @@ def hello(req)
|
|
|
171
304
|
next unless (mod = a['patch']['mod'])
|
|
172
305
|
c = mod.split('::').reject(&:empty?).reduce(Object) { |o, n| o.const_defined?(n, false) ? o.const_get(n, false) : o.const_set(n, Module.new) }
|
|
173
306
|
m, st, key = a['patch']['path'][-1], stub(a['key']), a['key']
|
|
174
|
-
c.singleton_class.prepend(Module.new { a['pass'] ? define_method(m) { |*x, **k, &b| raising(key); super(*x, **k, &b) } : define_method(m, &st) })
|
|
307
|
+
c.singleton_class.prepend(Module.new { a['pass'] ? define_method(m) { |*x, **k, &b| native_call(key) { raising(key); super(*x, **k, &b) } } : define_method(m, &st) })
|
|
175
308
|
end
|
|
176
|
-
{'ok' => true}
|
|
309
|
+
{'ok' => true, 'nativeSnapshot' => 1, 'nativeBindings' => 1, 'nativeObservations' => 1, 'nativeEquality' => 'scalar'}
|
|
177
310
|
end
|
|
178
311
|
def make(specs)
|
|
179
312
|
$stores = {}
|
|
@@ -187,20 +320,55 @@ def call(req)
|
|
|
187
320
|
obj = OBJS[req['id']]
|
|
188
321
|
NOW[0] = Integer(req['now'] || 0)
|
|
189
322
|
CUR.replace(req['answers'] || {})
|
|
190
|
-
|
|
323
|
+
NATIVE_INVOCATION[0] += 1
|
|
324
|
+
raise ArgumentError, 'native invocation exceeds exact integer range' if NATIVE_INVOCATION[0] > 9007199254740991
|
|
325
|
+
NATIVE_EVENTS[0] = {'invocation' => NATIVE_INVOCATION[0], 'calls' => {}}
|
|
326
|
+
NATIVE_EVENT_ERROR[0] = nil
|
|
327
|
+
NATIVE_CALL_TYPES.clear
|
|
328
|
+
m = NATIVE_METHOD.bind_call(obj, req['m'])
|
|
191
329
|
pos, kw = call_args(m, req['a'])
|
|
192
330
|
before = frames(obj)
|
|
193
331
|
snap = S['discard'] ? state_of(obj) : nil
|
|
194
332
|
out, err = nil, nil
|
|
333
|
+
bindings = {'error' => 'native method entry was not observed'}
|
|
334
|
+
entered = false
|
|
335
|
+
# Defaults and keyword arguments are bound before :call. Read actual locals
|
|
336
|
+
# before the first body instruction, never the request's argument envelopes.
|
|
337
|
+
capture = TracePoint.new(:call) do |event|
|
|
338
|
+
next unless native_active?
|
|
339
|
+
next if entered || !native_same?(event.self, obj) || !native_same?(event.defined_class, m.owner) || !native_same?(event.method_id, m.original_name)
|
|
340
|
+
entered = true
|
|
341
|
+
begin
|
|
342
|
+
values = m.parameters.to_h do |kind, name|
|
|
343
|
+
raise ArgumentError, 'unsupported anonymous or block native parameter' if name.nil? || kind == :block
|
|
344
|
+
[name.to_s, event.binding.local_variable_get(name)]
|
|
345
|
+
end
|
|
346
|
+
bindings = {'snapshot' => native_state(values, bindings: true)}
|
|
347
|
+
rescue StandardError => e
|
|
348
|
+
bindings = {'error' => "#{e.class}: #{e.message}"[0, 300]}
|
|
349
|
+
end
|
|
350
|
+
end
|
|
195
351
|
begin
|
|
352
|
+
NATIVE_ACTIVE_THREAD[0] = NATIVE_THREAD.call
|
|
353
|
+
capture.enable(target_thread: NATIVE_THREAD.call)
|
|
196
354
|
out = traced { m.call(*pos, **kw) }
|
|
197
355
|
rescue StandardError => e
|
|
198
356
|
err = "#{e.class}: #{e.message}"[0, 300]
|
|
357
|
+
ensure
|
|
358
|
+
NATIVE_ACTIVE_THREAD[0] = nil
|
|
359
|
+
capture.disable
|
|
199
360
|
end
|
|
200
361
|
set_state(obj, snap) if err && snap
|
|
201
362
|
after = frames(obj)
|
|
202
363
|
before.each { |k, v| return {'frame' => k} if after[k] != v }
|
|
203
|
-
|
|
364
|
+
observations = begin
|
|
365
|
+
NATIVE_EVENT_ERROR[0] ? {'error' => NATIVE_EVENT_ERROR[0]} : {'snapshot' => native_state(NATIVE_EVENTS[0], bindings: true, records: true)}
|
|
366
|
+
rescue StandardError => e
|
|
367
|
+
{'error' => "#{e.class}: #{e.message}"[0, 300]}
|
|
368
|
+
ensure
|
|
369
|
+
NATIVE_EVENTS[0] = nil
|
|
370
|
+
end
|
|
371
|
+
{'out' => tag(out), 'nativeBindings' => bindings, 'nativeObservations' => observations, **(err ? {'err' => err} : {})}
|
|
204
372
|
end
|
|
205
373
|
|
|
206
374
|
fin, fout = File.open(ARGV[0], 'r'), File.open(ARGV[1], 'w')
|
|
@@ -226,6 +394,7 @@ fin.each_line do |line|
|
|
|
226
394
|
{'bad' => "#{e.class}: #{e.message}"[0, 300]}
|
|
227
395
|
end
|
|
228
396
|
when 'get' then {'state' => state_of(OBJS[req['id']])}
|
|
397
|
+
when 'native' then {'snapshot' => native_state(OBJS[req['id']])}
|
|
229
398
|
when 'call' then call(req)
|
|
230
399
|
when 'coverage' then {'hit' => HIT.keys.sort.map { |n| [File.basename(S['path']), n] }}
|
|
231
400
|
else {'error' => "no op #{op}"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export type SearchTermination = {
|
|
2
|
+
kind: 'wall-deadline' | 'work-exhausted';
|
|
3
|
+
phase: string;
|
|
4
|
+
scope?: 'search' | 'stage';
|
|
5
|
+
};
|
|
6
|
+
export type SearchContext = {
|
|
7
|
+
goal?: string;
|
|
8
|
+
stuck?: string;
|
|
9
|
+
why?: string;
|
|
10
|
+
witness?: Record<string, number>;
|
|
11
|
+
};
|
|
12
|
+
export type SearchTerminationFields = {
|
|
13
|
+
stopped?: true;
|
|
14
|
+
termination?: SearchTermination;
|
|
15
|
+
context?: SearchContext;
|
|
16
|
+
};
|
|
17
|
+
export declare const searchContext: (v: SearchContext & SearchTerminationFields) => SearchContext;
|
|
18
|
+
export declare const terminationWhy: (t: SearchTermination) => string;
|
|
19
|
+
type Completion = {
|
|
20
|
+
proven: boolean;
|
|
21
|
+
checked: boolean;
|
|
22
|
+
run?: unknown;
|
|
23
|
+
kernelProven?: boolean;
|
|
24
|
+
translation?: string;
|
|
25
|
+
stopped?: boolean;
|
|
26
|
+
termination?: unknown;
|
|
27
|
+
stats?: {
|
|
28
|
+
stopped?: boolean;
|
|
29
|
+
termination?: unknown;
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
export declare const completedSourceRefusal: (v: Completion | undefined) => boolean;
|
|
33
|
+
export declare const completedSearch: (v: Completion | undefined) => boolean;
|
|
34
|
+
export declare const stoppedSearch: <T extends SearchContext & SearchTerminationFields>(v: T, termination: SearchTermination) => T & SearchTerminationFields;
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export const searchContext = (v) => v.context ?? ({
|
|
2
|
+
...(v.goal === undefined ? {} : { goal: v.goal }), ...(v.stuck === undefined ? {} : { stuck: v.stuck }),
|
|
3
|
+
...(v.why === undefined ? {} : { why: v.why }), ...(v.witness === undefined ? {} : { witness: v.witness }),
|
|
4
|
+
});
|
|
5
|
+
export const terminationWhy = (t) => `${t.kind === 'wall-deadline' ? 'wall deadline reached' : 'counted work exhausted'} (${t.phase}${t.scope === 'stage' ? '; stage allowance' : ''})`;
|
|
6
|
+
// Terminal evidence of source refusal, never permission to publish a proof.
|
|
7
|
+
// In particular, neither a generic unknown nor interrupted source checking is
|
|
8
|
+
// completed merely because its mathematical part once succeeded.
|
|
9
|
+
export const completedSourceRefusal = (v) => !!v && v.proven === false && v.checked === false && v.kernelProven === true &&
|
|
10
|
+
(v.translation === 'unchecked' || v.translation === 'error') &&
|
|
11
|
+
v.stopped === undefined && v.termination === undefined && !v.stats?.stopped && v.stats?.termination === undefined;
|
|
12
|
+
export const completedSearch = (v) => !!v && (v.proven && v.checked || v.run !== undefined || completedSourceRefusal(v));
|
|
13
|
+
export const stoppedSearch = (v, termination) => ({ ...v, stopped: true, termination, context: searchContext(v), why: terminationWhy(termination) });
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { SearchTermination } from './search-termination.js';
|
|
2
|
+
export declare class WatchdogExpired extends Error {
|
|
3
|
+
readonly termination: SearchTermination;
|
|
4
|
+
constructor(phase: string);
|
|
5
|
+
}
|
|
6
|
+
export declare function withSearchWatchdog<T>(ms: number | undefined, run: () => T): T;
|
|
7
|
+
export declare function checkWatchdog(phase: string): void;
|
|
8
|
+
export declare function validateWatchdog(ms: number | undefined): void;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
let watchdogEnd = Infinity;
|
|
2
|
+
export class WatchdogExpired extends Error {
|
|
3
|
+
termination;
|
|
4
|
+
constructor(phase) {
|
|
5
|
+
super(`wall deadline reached (${phase}; explicit watchdog)`);
|
|
6
|
+
this.name = 'WatchdogExpired';
|
|
7
|
+
this.termination = { kind: 'wall-deadline', phase, scope: 'search' };
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export function withSearchWatchdog(ms, run) {
|
|
11
|
+
validateWatchdog(ms);
|
|
12
|
+
const outer = watchdogEnd;
|
|
13
|
+
if (ms !== undefined)
|
|
14
|
+
watchdogEnd = Math.min(outer, performance.now() + ms);
|
|
15
|
+
try {
|
|
16
|
+
checkWatchdog('search preflight');
|
|
17
|
+
const out = run();
|
|
18
|
+
if (out !== null && (typeof out === 'object' || typeof out === 'function') && typeof out.then === 'function')
|
|
19
|
+
throw new TypeError('search watchdog scope requires a synchronous callback');
|
|
20
|
+
checkWatchdog('search result');
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
watchdogEnd = outer;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export function checkWatchdog(phase) {
|
|
28
|
+
if (watchdogEnd !== Infinity && performance.now() >= watchdogEnd)
|
|
29
|
+
throw new WatchdogExpired(phase);
|
|
30
|
+
}
|
|
31
|
+
export function validateWatchdog(ms) {
|
|
32
|
+
if (ms !== undefined && (!Number.isFinite(ms) || ms < 0))
|
|
33
|
+
throw new RangeError('watchdogMs must be finite and nonnegative');
|
|
34
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { NativeExecutionObservation } from './native-observations.js';
|
|
1
2
|
export type Translation = 'exhaustive' | 'sampled' | 'unchecked' | 'error';
|
|
2
3
|
export type NativeObservation = {
|
|
3
4
|
where: string;
|
|
@@ -11,6 +12,8 @@ export type NativeObservation = {
|
|
|
11
12
|
result: unknown;
|
|
12
13
|
failed: boolean;
|
|
13
14
|
legacyResult?: boolean;
|
|
15
|
+
observed?: NativeExecutionObservation;
|
|
16
|
+
nativeEquality?: 'scalar';
|
|
14
17
|
};
|
|
15
18
|
export type NativeJournal = {
|
|
16
19
|
enabled: boolean;
|
|
@@ -26,6 +29,7 @@ export type TranslationFields = {
|
|
|
26
29
|
kernelProven?: boolean;
|
|
27
30
|
};
|
|
28
31
|
export declare function inheritSource(from: object, to: object, transparent?: boolean): void;
|
|
32
|
+
export declare function bindSourceMachine(rule: object, machine: object): void;
|
|
29
33
|
export declare function rememberNative(e: object, journal: NativeJournal): void;
|
|
30
34
|
export declare function attachSource(rule: object, e: object, generated: object[]): void;
|
|
31
35
|
export declare function attachNativeLaw(rule: object, law: object, name: string, method: string | undefined, evaluate: (observation: NativeObservation) => boolean): void;
|
|
@@ -39,6 +43,7 @@ export declare function translationVerdict<V extends {
|
|
|
39
43
|
why?: string;
|
|
40
44
|
stuck?: string;
|
|
41
45
|
}>(rule: object, laws: object[], verdict: V): TranslatedVerdict<V>;
|
|
46
|
+
export declare function requireSourceTranslation(rule: object, laws: object[]): void;
|
|
42
47
|
export declare const nativeSame: (a: unknown, b: unknown) => boolean;
|
|
43
48
|
export declare function nativeSnapshot(value: unknown, seen?: Map<object, unknown>): unknown;
|
|
44
49
|
export {};
|
|
@@ -19,6 +19,19 @@ export function inheritSource(from, to, transparent = false) {
|
|
|
19
19
|
if (transparent && source)
|
|
20
20
|
sources.set(to, source);
|
|
21
21
|
}
|
|
22
|
+
// Rule.machine makes a fresh structural model. Carry source provenance onto that
|
|
23
|
+
// exact model so public consumers that receive only a Machine still fail closed.
|
|
24
|
+
// The marker is enumerable here: spread/reconstruction keeps the warning, but
|
|
25
|
+
// never the private WeakMap journal (a copied machine is therefore rejected).
|
|
26
|
+
export function bindSourceMachine(rule, machine) {
|
|
27
|
+
const source = sources.get(rule);
|
|
28
|
+
if (source) {
|
|
29
|
+
mark(machine, true);
|
|
30
|
+
sources.set(machine, source);
|
|
31
|
+
}
|
|
32
|
+
else if (marked(rule))
|
|
33
|
+
mark(machine, true);
|
|
34
|
+
}
|
|
22
35
|
const evidence = new WeakMap();
|
|
23
36
|
const sources = new WeakMap();
|
|
24
37
|
const nativeLaws = new WeakMap();
|
|
@@ -69,6 +82,14 @@ export function translationVerdict(rule, laws, verdict) {
|
|
|
69
82
|
}
|
|
70
83
|
return { ...verdict, translation: journal.scope, translationChecks: checks };
|
|
71
84
|
}
|
|
85
|
+
// Lean export is a public proof boundary. It must repeat source admission from
|
|
86
|
+
// the bound machine and laws instead of trusting caller-supplied fields or an
|
|
87
|
+
// old verdict: the journal and native-law identities live only in these maps.
|
|
88
|
+
export function requireSourceTranslation(rule, laws) {
|
|
89
|
+
const verdict = translationVerdict(rule, laws, { proven: true, checked: true });
|
|
90
|
+
if (!verdict.proven || !verdict.checked)
|
|
91
|
+
throw new Error(verdict.why ?? 'source translation was not checked');
|
|
92
|
+
}
|
|
72
93
|
const sourceIdentity = new WeakMap(), cloneIdentity = new WeakMap();
|
|
73
94
|
let nextIdentity = 0;
|
|
74
95
|
const identify = (original, clone) => {
|