gdp-wired 0.50.2 → 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.
Files changed (49) hide show
  1. package/README.md +4 -2
  2. package/dist/core/cli.d.ts +12 -1
  3. package/dist/core/cli.js +62 -25
  4. package/dist/core/discover.d.ts +6 -1
  5. package/dist/core/discover.js +54 -7
  6. package/dist/core/dsl-deadline.d.ts +3 -0
  7. package/dist/core/dsl-deadline.js +26 -2
  8. package/dist/core/dsl.d.ts +3 -1
  9. package/dist/core/dsl.js +93 -30
  10. package/dist/core/effect.d.ts +12 -0
  11. package/dist/core/effect.js +26 -9
  12. package/dist/core/ex/harness.exs +171 -5
  13. package/dist/core/extract-c.js +63 -6
  14. package/dist/core/extract-check.d.ts +5 -1
  15. package/dist/core/extract-check.js +28 -10
  16. package/dist/core/extract-go-check.js +127 -1
  17. package/dist/core/extract-go.js +8 -2
  18. package/dist/core/extract-jvm.js +2 -2
  19. package/dist/core/extract-rs.js +51 -5
  20. package/dist/core/extract-step.js +40 -6
  21. package/dist/core/extract-swift.js +47 -3
  22. package/dist/core/extract.d.ts +8 -0
  23. package/dist/core/infer.d.ts +8 -0
  24. package/dist/core/infer.js +133 -16
  25. package/dist/core/jvm/Harness.java +135 -3
  26. package/dist/core/jvm/Rt.java +66 -4
  27. package/dist/core/laws.js +51 -10
  28. package/dist/core/native-law.d.ts +3 -1
  29. package/dist/core/native-law.js +126 -14
  30. package/dist/core/native-observations.d.ts +20 -0
  31. package/dist/core/native-observations.js +41 -0
  32. package/dist/core/native-wire.d.ts +1 -0
  33. package/dist/core/native-wire.js +16 -2
  34. package/dist/core/py/harness.py +21 -4
  35. package/dist/core/rb/harness.rb +178 -9
  36. package/dist/core/search-termination.d.ts +35 -0
  37. package/dist/core/search-termination.js +13 -0
  38. package/dist/core/search-watchdog.d.ts +8 -0
  39. package/dist/core/search-watchdog.js +34 -0
  40. package/dist/core/source-check.d.ts +3 -0
  41. package/dist/core/swift/Harness.swift +65 -4
  42. package/dist/core/swift/Main.swift +27 -4
  43. package/dist/core/wall.d.ts +3 -1
  44. package/dist/core/wall.js +7 -4
  45. package/dist/core/work-refusal.d.ts +3 -0
  46. package/dist/core/work-refusal.js +8 -0
  47. package/dist/kernel/prove.d.ts +2 -0
  48. package/dist/kernel/prove.js +13 -5
  49. package/package.json +1 -1
@@ -1 +1,2 @@
1
+ export declare const snapshotNativeBindings: (decode: (wire: unknown) => unknown, wire: unknown) => Record<string, unknown>;
1
2
  export declare function nativeWireDecoder(maxObjects?: number, maxNodes?: number): (wire: unknown) => unknown;
@@ -1,3 +1,7 @@
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));
1
5
  // Decode identity-bearing snapshots returned by the real native harness. This
2
6
  // is observation transport only: no model values or proof results are supplied.
3
7
  export function nativeWireDecoder(maxObjects = 100000, maxNodes = 10000) {
@@ -30,7 +34,7 @@ export function nativeWireDecoder(maxObjects = 100000, maxNodes = 10000) {
30
34
  throw Error('unbound native snapshot reference');
31
35
  return objects.get(id).value;
32
36
  }
33
- if (kind !== 'object' && kind !== 'array' && kind !== 'map')
37
+ if (kind !== 'object' && kind !== 'array' && kind !== 'map' && kind !== 'set')
34
38
  throw Error('unsupported native snapshot kind');
35
39
  if (seen.has(id))
36
40
  throw Error('duplicate native snapshot identity');
@@ -41,7 +45,7 @@ export function nativeWireDecoder(maxObjects = 100000, maxNodes = 10000) {
41
45
  if (!kept) {
42
46
  if (objects.size >= maxObjects)
43
47
  throw Error('native snapshot exceeds identity bound');
44
- const fresh = kind === 'array' ? [] : kind === 'map' ? new Map() : Object.create(null);
48
+ const fresh = kind === 'array' ? [] : kind === 'map' ? new Map() : kind === 'set' ? new Set() : Object.create(null);
45
49
  kept = { kind, value: fresh };
46
50
  objects.set(id, kept);
47
51
  }
@@ -53,6 +57,16 @@ export function nativeWireDecoder(maxObjects = 100000, maxNodes = 10000) {
53
57
  for (const item of node.items)
54
58
  target.push(decode(item));
55
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
+ }
56
70
  else if (kind === 'map') {
57
71
  const target = kept.value;
58
72
  target.clear();
@@ -592,7 +592,7 @@ def hello(req):
592
592
  S['cls'] = getattr(mod, req['cls'].rpartition('.')[2]) if req.get('cls') else None
593
593
  S['loop'] = asyncio.new_event_loop()
594
594
  asyncio.set_event_loop(S['loop'])
595
- return {'ok': True, 'nativeSnapshot': 1}
595
+ return {'ok': True, 'nativeSnapshot': 1, 'nativeBindings': 1, 'nativeEquality': 'scalar'}
596
596
 
597
597
  def make(args):
598
598
  global OBJ_STORES
@@ -640,6 +640,19 @@ def call(req):
640
640
  try: kwargs = fixed_args(req['a'], {})
641
641
  except OverflowError as e:
642
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]}
643
656
  before = frames(obj if S['cls'] is not None else None)
644
657
  snap = state_of(obj, stores) if S.get('discard') and S['cls'] is not None else None
645
658
  sys.settrace(tracer)
@@ -658,11 +671,11 @@ def call(req):
658
671
  after = frames(obj if S['cls'] is not None else None)
659
672
  for k in before:
660
673
  if after.get(k) != before[k]: return {'frame': k}
661
- 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 {})}
662
675
 
663
676
  # Native observation transport for ordered containers. Retain real references
664
677
  # so Python cannot recycle an address and manufacture cross-snapshot identity.
665
- def native_state(obj):
678
+ def native_state(obj, select=True):
666
679
  seen = set()
667
680
  count = [0]
668
681
  def encode(value, names=None):
@@ -682,6 +695,10 @@ def native_state(obj):
682
695
  seen.add(ident)
683
696
  if isinstance(value, list):
684
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')
685
702
  if isinstance(value, dict):
686
703
  if any(not isinstance(k, (str, int, float)) or isinstance(k, bool) for k in value):
687
704
  raise ValueError('unsupported native snapshot map key')
@@ -690,7 +707,7 @@ def native_state(obj):
690
707
  if names is not None: fields = {name: fields[name] for name in names}
691
708
  return {'kind': 'object', 'id': ident, 'items': [[k, encode(v)] for k, v in fields.items()]}
692
709
  roots = sorted({l['path'][0] for l in S['leaves'] if l.get('path') and l['kind'] != 'frame'})
693
- return {'version': 1, 'root': encode(obj, roots)}
710
+ return {'version': 1, 'root': encode(obj, roots if select else None)}
694
711
 
695
712
  def main():
696
713
  fin = open(sys.argv[1], 'r'); fout = open(sys.argv[2], 'w')
@@ -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(*) = Time.at(NOW[0])
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
- m = obj.method(req['m'])
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
- {'out' => tag(out), **(err ? {'err' => err} : {})}
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;
@@ -1,6 +1,46 @@
1
1
  // gdp-wired's check harness for Swift, its fixed part (core/extract-swift.ts appends it, after the part generated for the
2
2
  // type read, to the type's file in the check's copy of the package): JSON, the requests, the stores, the answers.
3
3
  // Pure Swift, no Foundation (importing it into the code's file could change what its names resolve to).
4
+ // Raw source-language values only. Object equality is intentionally scalar-only.
5
+ func __gdpNativeUnsupported(_ reason: String) throws -> __GdpJ { throw __GdpBad(why: reason) }
6
+ func __gdpNativeInt<T: BinaryInteger>(_ x: T) throws -> __GdpJ {
7
+ guard let n = Int64(exactly: x), n >= -9007199254740991, n <= 9007199254740991 else { throw __GdpBad(why: "native integer outside safe range") }
8
+ return .n(String(n))
9
+ }
10
+ func __gdpNativeNode(_ kind: String, _ items: [__GdpJ]) throws -> __GdpJ {
11
+ guard __gdpS.nativeID < 9007199254740991, items.count <= 10000 else { throw __GdpBad(why: "native snapshot bound") }
12
+ let id = __gdpS.nativeID; __gdpS.nativeID += 1
13
+ return .o(["kind": .s(kind), "id": .s(String(id)), "items": .a(items)])
14
+ }
15
+ func __gdpNativeObject(_ items: [(String, __GdpJ)]) throws -> __GdpJ { try __gdpNativeNode("object", items.map { .a([.s($0.0), $0.1]) }) }
16
+ func __gdpNativeMap(_ items: [__GdpJ]) throws -> __GdpJ { try __gdpNativeNode("map", items) }
17
+ func __gdpNativeFrame(_ read: () throws -> __GdpJ) -> __GdpJ {
18
+ do { return .o(["snapshot": .o(["version": .n("1"), "root": try read()])]) } catch { return .o(["error": .s("\(error)")]) }
19
+ }
20
+ func __gdpNativeScalar(_ x: Any, _ depth: Int = 0) throws -> __GdpJ {
21
+ guard depth < 8 else { throw __GdpBad(why: "native optional bound") }
22
+ if let b = x as? Bool { return .b(b) }
23
+ if let s = x as? String { return .s(s) }
24
+ if let n = x as? any BinaryInteger { return try __gdpNativeInt(n) }
25
+ let mirror = Mirror(reflecting: x)
26
+ if mirror.displayStyle == .optional { return try mirror.children.first.map { try __gdpNativeScalar($0.value, depth + 1) } ?? .null }
27
+ throw __GdpBad(why: "unsupported native answer type")
28
+ }
29
+ final class __GdpCapture: @unchecked Sendable {
30
+ var invocation = 0; var calls: [String: __GdpJ] = [:]; var error: String?
31
+ }
32
+ let __gdpCapture = __GdpCapture()
33
+ func __gdpObservationFrame() -> __GdpJ {
34
+ if let error = __gdpCapture.error { return .o(["error": .s(error)]) }
35
+ return __gdpNativeFrame {
36
+ try __gdpNativeObject([("invocation", .n(String(__gdpCapture.invocation))), ("calls", try __gdpNativeObject(try __gdpCapture.calls.map { key, value in (key, try __gdpNativeObject([("kind", .s("returned")), ("value", value)])) }))])
37
+ }
38
+ }
39
+ func __gdpRecordNative(_ key: String, _ value: __GdpJ) {
40
+ var text = ""; value.write(&text)
41
+ if let previous = __gdpCapture.calls[key] { var old = ""; previous.write(&old); if old != text { __gdpCapture.error = "differing repeated native call \(key)" } }
42
+ else { __gdpCapture.calls[key] = value }
43
+ }
4
44
  struct __GdpBad: Error { let why: String }
5
45
  struct __GdpErr: Error { let why: String }
6
46
  indirect enum __GdpJ {
@@ -64,7 +104,13 @@ extension UInt8: __GdpAns { static func __gdpOf(_ j: __GdpJ?) throws -> UInt8 {
64
104
  extension Bool: __GdpAns { static func __gdpOf(_ j: __GdpJ?) throws -> Bool { try __gdpBool(j) }; static var __gdpZero: Bool { false } }
65
105
  extension String: __GdpAns { static func __gdpOf(_ j: __GdpJ?) throws -> String { try __gdpStr(j) }; static var __gdpZero: String { "" } }
66
106
  extension Optional: __GdpAns where Wrapped: __GdpAns { static func __gdpOf(_ j: __GdpJ?) throws -> Optional<Wrapped> { __gdpIsNone(j) ? nil : try Wrapped.__gdpOf(j) }; static var __gdpZero: Optional<Wrapped> { nil } }
67
- func __gdpAnswer<T: __GdpAns>(_ k: String) -> T { do { return try T.__gdpOf(__gdpS.answers[k]) } catch { fatalError("gdp: no answer for \(k)") } }
107
+ func __gdpAnswer<T: __GdpAns>(_ k: String) -> T {
108
+ do {
109
+ let value = try T.__gdpOf(__gdpS.answers[k])
110
+ do { __gdpRecordNative(k, try __gdpNativeScalar(value)) } catch { __gdpCapture.error = "unsupported actual answer: \(error)" }
111
+ return value
112
+ } catch { __gdpCapture.error = "actual answer conversion failed: \(error)"; fatalError("gdp: no answer for \(k)") }
113
+ }
68
114
  func __gdpZero<T: __GdpAns>() -> T { T.__gdpZero }
69
115
  final class __GdpStore: @unchecked Sendable { var data: [String: __GdpJ] = [:] }
70
116
  func __gdpStoreGet<T: __GdpAns>(_ s: __GdpStore, _ k: String) -> T { do { return try T.__gdpOf(s.data[k] ?? .null) } catch { fatalError("gdp: the store holds no \(T.self) at \(k)") } }
@@ -78,9 +124,17 @@ func __gdpTpl(_ t: String, _ k: String) -> String? {
78
124
  }
79
125
  func __gdpFill(_ t: String, _ h: String) -> String { guard let (pre, post) = __gdpSplit(t) else { return t }; return pre + h + post }
80
126
  func __gdpOut(_ m: [String: __GdpJ]) -> String { var o = ""; __GdpJ.o(m).write(&o); return o }
81
- public func __gdpOp(_ line: String) -> String { var p = __GdpParse(line); if case .s(let op)? = p.val()["op"] { return op }; return "" }
127
+ public func __gdpOp(_ line: String) -> String {
128
+ var p = __GdpParse(line); let req = p.val()
129
+ guard case .s(let op)? = req["op"] else { return "" }
130
+ if op == "call" {
131
+ __gdpCapture.invocation += 1
132
+ __gdpS.binding = .o(["error": .s("native arguments were not bound")])
133
+ }
134
+ return op
135
+ }
82
136
  public func __gdpCrash(_ op: String, _ how: String) -> String {
83
- op == "call" ? __gdpOut(["out": .null, "err": .s("a crash (\(how): a trap, a precondition, fatalError, nil force-unwrapped)")]) : op == "at" ? __gdpOut(["bad": .s("a crash setting the state (\(how))")]) : __gdpOut(["err": .s("a crash in init (\(how))")])
137
+ op == "call" ? __gdpOut(["out": .null, "err": .s("a crash (\(how): a trap, a precondition, fatalError, nil force-unwrapped)"), "nativeBindings": __gdpS.binding, "nativeObservations": .o(["error": .s("child native observation unavailable after crash")])]) : op == "at" ? __gdpOut(["bad": .s("a crash setting the state (\(how))")]) : __gdpOut(["err": .s("a crash in init (\(how))")])
84
138
  }
85
139
  func __gdpStoresOk() -> String? {
86
140
  for (n, st) in __gdpS.cur { for k in st.data.keys where !(__gdpTpls[n] ?? []).contains(where: { __gdpTpl($0, k) != nil }) { return "the store \(n) holds \(k), a key no template of the rule names" } }
@@ -91,7 +145,7 @@ public func __gdpHandle(_ line: String) -> String {
91
145
  let req = p.val()
92
146
  guard case .s(let op)? = req["op"] else { return __gdpOut(["error": .s("no op")]) }
93
147
  switch op {
94
- case "hello": __gdpS.discard = __gdpIsTrue(req["discard"]); return __gdpOut(["ok": .b(true)])
148
+ case "hello": __gdpS.discard = __gdpIsTrue(req["discard"]); return __gdpOut(["ok": .b(true), "nativeSnapshot": .n("1"), "nativeBindings": .n("1"), "nativeObservations": .n("1"), "nativeEquality": .s("scalar")])
95
149
  case "new", "at":
96
150
  __gdpS.cur = [:]
97
151
  do {
@@ -105,7 +159,12 @@ public func __gdpHandle(_ line: String) -> String {
105
159
  __gdpS.cur = __gdpS.stores[i - 1]
106
160
  if let bad = __gdpStoresOk() { return __gdpOut(["error": .s(bad)]) }
107
161
  return __gdpOut(["state": .o(__gdpGet(__gdpS.objs[i - 1]))])
162
+ case "native":
163
+ guard let i = req["id"]?.text.flatMap({ Int($0) }), i >= 1, i <= __gdpS.objs.count else { return __gdpOut(["error": .s("no object")]) }
164
+ __gdpS.cur = __gdpS.stores[i - 1]
165
+ var result = ""; __gdpNativeFrame { try __gdpNative(__gdpS.objs[i - 1]) }.write(&result); return result
108
166
  case "call":
167
+ __gdpCapture.calls = [:]; __gdpCapture.error = nil
109
168
  guard let i = req["id"]?.text.flatMap({ Int($0) }), i >= 1, i <= __gdpS.objs.count, case .s(let m)? = req["m"] else { return __gdpOut(["error": .s("no object")]) }
110
169
  __gdpS.cur = __gdpS.stores[i - 1]
111
170
  if case .o(let a)? = req["answers"] { __gdpS.answers = a } else { __gdpS.answers = [:] }
@@ -117,6 +176,8 @@ public func __gdpHandle(_ line: String) -> String {
117
176
  catch { res = ["out": .null, "err": .s("\(error)")] }
118
177
  let after = __gdpFrames(__gdpS.objs[i - 1])
119
178
  for (k, v) in before where after[k] != v { return __gdpOut(["frame": .s(k)]) }
179
+ res["nativeBindings"] = __gdpS.binding
180
+ res["nativeObservations"] = __gdpObservationFrame()
120
181
  return __gdpOut(res)
121
182
  case "coverage": return __gdpOut(["hit": .a([])])
122
183
  default: return __gdpOut(["error": .s("no op \(op)")])
@@ -11,21 +11,44 @@ func run() {
11
11
  let args = CommandLine.arguments
12
12
  guard args.count >= 3, let fin = fopen(args[args.count - 2], "r") else { return }
13
13
  let fout = open(args[args.count - 1], O_WRONLY)
14
+ guard fout >= 0 else { fclose(fin); return }
14
15
  typealias Fork = @convention(c) () -> Int32
15
16
  let fork = unsafeBitCast(dlsym(dlopen(nil, RTLD_NOW), "fork"), to: Fork.self)
16
17
  var line: UnsafeMutablePointer<CChar>? = nil
17
18
  var cap = 0
19
+ defer { if let line { free(line) }; fclose(fin); close(fout) }
18
20
  while getline(&line, &cap, fin) > 0 {
19
21
  let req = String(cString: line!)
20
22
  let op = __gdpOp(req)
21
23
  var res: String
22
24
  if op == "new" || op == "at" || op == "call" {
25
+ // A crashed child's journal is unavailable; never fabricate it from the request.
26
+ // The successful parent execution records its own actual calls.
23
27
  let pid = fork()
24
- if pid == 0 { if getenv("GDP_SWIFT_DEBUG") == nil { dup2(open("/dev/null", O_WRONLY), 2) }; _ = __gdpHandle(req); _exit(0) }
28
+ if pid == 0 {
29
+ if getenv("GDP_SWIFT_DEBUG") == nil {
30
+ let fd = open("/dev/null", O_WRONLY)
31
+ if fd >= 0 { _ = dup2(fd, 2); if fd != 2 { close(fd) } }
32
+ }
33
+ _ = __gdpHandle(req)
34
+ _exit(0)
35
+ }
25
36
  var st: Int32 = 0
26
- _ = waitpid(pid, &st, 0)
27
- let sig = st & 0x7f, code = (st >> 8) & 0xff
28
- if sig != 0 || code != 0 { res = __gdpCrash(op, sig != 0 ? "signal \(sig)" : "exit \(code)") } else { res = __gdpHandle(req) }
37
+ var waited: Int32 = -1
38
+ if pid > 0 {
39
+ repeat { waited = waitpid(pid, &st, 0) } while waited == -1 && errno == EINTR
40
+ if waited == -1 && errno != ECHILD {
41
+ // Only the still-owned child can be signalled; never a process group.
42
+ _ = kill(pid, SIGKILL)
43
+ var reaped: Int32
44
+ repeat { reaped = waitpid(pid, &st, 0) } while reaped == -1 && errno == EINTR
45
+ }
46
+ }
47
+ if pid <= 0 || waited != pid { res = "{\"error\":\"child execution unavailable\"}" }
48
+ else {
49
+ let sig = st & 0x7f, code = (st >> 8) & 0xff
50
+ if sig != 0 || code != 0 { res = __gdpCrash(op, sig != 0 ? "signal \(sig)" : "exit \(code)") } else { res = __gdpHandle(req) }
51
+ }
29
52
  } else { res = __gdpHandle(req) }
30
53
  res += "\n"
31
54
  _ = res.withCString { write(fout, $0, strlen($0)) }
@@ -1,4 +1,5 @@
1
1
  import { type WallDeadline } from '../kernel/prove.js';
2
+ import type { SearchTermination } from './search-termination.js';
2
3
  export { wallDeadline, withBudget, budgetEnd, inBudget, checkBudget, checkWorkEndpoint, BudgetExpired, searchNow } from '../kernel/prove.js';
3
4
  export { traceNow } from './trace-clock.js';
4
5
  export declare const searchDateNow: () => number;
@@ -6,6 +7,7 @@ export declare const searchWall: (ms: number) => WallDeadline;
6
7
  export declare const transportEnd: (until: number, cap?: number) => number;
7
8
  export declare class WallExpired extends Error {
8
9
  readonly phase: string;
9
- constructor(phase: string);
10
+ readonly termination?: SearchTermination | undefined;
11
+ constructor(phase: string, termination?: SearchTermination | undefined);
10
12
  }
11
13
  export declare function checkWall(phase: string): void;