gdp-wired 0.50.4 → 0.50.5

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.
@@ -109,6 +109,7 @@ export type CodeSide = {
109
109
  call: (self: unknown, e: Ev, args: unknown[]) => {
110
110
  ok: true;
111
111
  value: unknown;
112
+ nativeFailed?: boolean;
112
113
  } | {
113
114
  ok: false;
114
115
  error: string;
@@ -645,7 +645,7 @@ export function drive(m, r, sorts, code, opts = {}) {
645
645
  }
646
646
  // Result fields in a prover witness are not state held by a pure
647
647
  // function. Compare the returned value below, never carry those fields.
648
- res = c.ok ? { snap: { leaves: {}, maps: {} }, out: c.value } : { refused: c.error };
648
+ res = c.ok ? { snap: { leaves: {}, maps: {} }, out: c.value, nativeFailed: c.nativeFailed } : { refused: c.error };
649
649
  }
650
650
  else if (isClass) {
651
651
  const self = side.self, c = code.call(self, e, args);
@@ -657,7 +657,7 @@ export function drive(m, r, sorts, code, opts = {}) {
657
657
  if (!c.ok)
658
658
  res = { refused: c.error };
659
659
  else
660
- res = { snap: code.snapOf(self, params), out: c.value, self };
660
+ res = { snap: code.snapOf(self, params), out: c.value, self, nativeFailed: c.nativeFailed };
661
661
  }
662
662
  else {
663
663
  const c = code.reduce(side.snap, e, args, params);
@@ -789,7 +789,7 @@ export function drive(m, r, sorts, code, opts = {}) {
789
789
  });
790
790
  const rk = m.results?.[e.call];
791
791
  journal.observations.push({ where, method: e.call, before, after, params: { ...params }, inputs: { ...inputs }, bindings: bindings ?? fallback,
792
- args: nativeArgs ?? [], result, failed: false, ...(observed ? { observed } : {}), ...(code.nativeEquality ? { nativeEquality: code.nativeEquality } : {}), legacyResult: !standalone && rk?.k === 'rec' && rk.fields.some(([field]) => field === 'value') });
792
+ args: nativeArgs ?? [], result, failed: res.nativeFailed ?? false, ...(observed ? { observed } : {}), ...(code.nativeEquality ? { nativeEquality: code.nativeEquality } : {}), legacyResult: !standalone && rk?.k === 'rec' && rk.fields.some(([field]) => field === 'value') });
793
793
  }
794
794
  next.side = afterSide;
795
795
  next.st = rule.st;
@@ -1055,7 +1055,7 @@ export function drive(m, r, sorts, code, opts = {}) {
1055
1055
  }
1056
1056
  if (!journal.reason)
1057
1057
  journal.observations.push({ where: `exhaustive native input ${++ordinal}`, method: event.call,
1058
- before: {}, after: {}, params: {}, inputs: {}, bindings, args: savedArgs, result, failed: false, ...(observed ? { observed } : {}), ...(code.nativeEquality ? { nativeEquality: code.nativeEquality } : {}) });
1058
+ before: {}, after: {}, params: {}, inputs: {}, bindings, args: savedArgs, result, failed: returned.nativeFailed ?? false, ...(observed ? { observed } : {}), ...(code.nativeEquality ? { nativeEquality: code.nativeEquality } : {}) });
1059
1059
  return;
1060
1060
  }
1061
1061
  for (const value of finite[at])
@@ -26,6 +26,16 @@ export function extractPython(at, opts = {}) {
26
26
  return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: [] };
27
27
  throw e;
28
28
  }
29
- const harness = () => ({ cmd: opts.python ?? 'python3', args: [here('harness.py')], env: { PYTHONDONTWRITEBYTECODE: '1', ...(opts.djangoSettings ? { DJANGO_SETTINGS_MODULE: opts.djangoSettings } : {}) }, hello: { root: mod.root, path: mod.path, module: mod.module } });
29
+ const harness = (read) => {
30
+ const methods = read.cls ? mod.recs[read.cls]?.methods : Object.fromEntries(mod.entries.flatMap(e => e.k === 'func' ? [[mod.funcs[e.id].name, e.id]] : []));
31
+ const nativeMethods = Object.fromEntries(Object.keys(read.args).flatMap(name => {
32
+ const id = methods?.[name], f = id ? mod.funcs[id] : undefined;
33
+ if (!f)
34
+ return [];
35
+ const decorators = f.decorators.map(d => Number(/:(\d+):\d+$/.exec(d.p)?.[1])).filter(Number.isFinite);
36
+ return [[name, { file: f.span[0], line: Math.min(f.span[1], ...decorators) }]];
37
+ }));
38
+ return { cmd: opts.python ?? 'python3', args: [here('harness.py')], env: { PYTHONDONTWRITEBYTECODE: '1', ...(opts.djangoSettings ? { DJANGO_SETTINGS_MODULE: opts.djangoSettings } : {}) }, hello: { root: mod.root, path: mod.path, module: mod.module, nativeMethods } };
39
+ };
30
40
  return extractStep(mod, harness, opts);
31
41
  }
@@ -6708,9 +6708,9 @@ function checkStepOnce(h, read, r, sorts, opts) {
6708
6708
  const out = res.out;
6709
6709
  const rk = m.results?.[e.call];
6710
6710
  if (!rk)
6711
- return { ok: true, value: undefined };
6711
+ return { ok: true, value: undefined, nativeFailed: failed };
6712
6712
  if (rk.k === 'scalar')
6713
- return { ok: true, value: value(out) };
6713
+ return { ok: true, value: value(out), nativeFailed: failed };
6714
6714
  const o = {};
6715
6715
  for (const [f] of rk.fields) {
6716
6716
  if (f === 'failed')
@@ -6724,7 +6724,7 @@ function checkStepOnce(h, read, r, sorts, opts) {
6724
6724
  if (f.startsWith('effect:'))
6725
6725
  o[f] = !!res.effects?.[f.slice(7)];
6726
6726
  }
6727
- return { ok: true, value: o };
6727
+ return { ok: true, value: o, nativeFailed: failed };
6728
6728
  },
6729
6729
  ...(native ? { nativeState: (self) => {
6730
6730
  const result = ask({ op: 'native', id: self });
@@ -13,6 +13,11 @@ EFF = {}
13
13
  HIT = set()
14
14
  S = {}
15
15
  NATIVE_OBJECTS = {}
16
+ NATIVE_INVOCATION = [0]
17
+ NATIVE_EVENTS = [None]
18
+ NATIVE_EVENT_ERROR = [None]
19
+ NATIVE_CALL_TYPES = {}
20
+ NATIVE_SOURCE_CODES = {}
16
21
 
17
22
  def datetime_in(v, unit):
18
23
  epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc if unit == 'datetime-utc' else None)
@@ -524,6 +529,26 @@ def raised(r):
524
529
  except Exception:
525
530
  e = cls.__new__(cls); e.args = ('gdp: raised where the request says',); return e
526
531
 
532
+ # Only actual, invocation-local outcomes are evidence. Repeated calls must agree.
533
+ def native_record(key, value=None, error=None):
534
+ events = NATIVE_EVENTS[0]
535
+ if events is None: return
536
+ try:
537
+ if error is not None:
538
+ outcome, kind = {'kind': 'raised', 'raised': type(error).__name__}, type(error)
539
+ else:
540
+ if type(value) not in (type(None), bool, str, int, float):
541
+ raise ValueError('unsupported native external-call value')
542
+ if type(value) in (int, float) and (not (-9007199254740991 <= value <= 9007199254740991) or int(value) != value):
543
+ raise ValueError('native external-call value is outside exact integer range')
544
+ outcome, kind = {'kind': 'returned', 'value': value}, type(value)
545
+ if key in events['calls'] and (events['calls'][key] != outcome or NATIVE_CALL_TYPES[key] is not kind):
546
+ raise ValueError('native external call returned inconsistent values in one invocation')
547
+ events['calls'][key] = outcome
548
+ NATIVE_CALL_TYPES[key] = kind
549
+ except Exception as e:
550
+ NATIVE_EVENT_ERROR[0] = NATIVE_EVENT_ERROR[0] or f'{type(e).__name__}: {e}'[:300]
551
+
527
552
  def stub(key, is_async, orig=None):
528
553
  # (orig: a call left out, run as it is unless the request says it raises)
529
554
  def value(a_, k_):
@@ -534,10 +559,22 @@ def stub(key, is_async, orig=None):
534
559
  return build(a, {})
535
560
  if is_async:
536
561
  async def f(*a, **k):
537
- v = value(a, k)
538
- return (await v) if orig is not None and inspect.isawaitable(v) else v
562
+ try:
563
+ v = value(a, k)
564
+ v = (await v) if orig is not None and inspect.isawaitable(v) else v
565
+ except Exception as e:
566
+ native_record(key, error=e)
567
+ raise
568
+ native_record(key, value=v)
569
+ return v
539
570
  return f
540
- def g(*a, **k): return value(a, k)
571
+ def g(*a, **k):
572
+ try: v = value(a, k)
573
+ except Exception as e:
574
+ native_record(key, error=e)
575
+ raise
576
+ native_record(key, value=v)
577
+ return v
541
578
  return g
542
579
 
543
580
  def patch_target(p):
@@ -558,7 +595,7 @@ def hello(req):
558
595
  S['root'] = os.path.realpath(req['root'])
559
596
  # Only files the reader actually used, including imported bases; never arbitrary repository imports.
560
597
  S['sources'] = {os.path.realpath(os.path.join(S['root'], name)): name for name, _ in req['arms']}
561
- REAL.clear(); HIT.clear()
598
+ REAL.clear(); HIT.clear(); NATIVE_SOURCE_CODES.clear()
562
599
  sys.path.insert(0, req['root'])
563
600
  if os.environ.get('DJANGO_SETTINGS_MODULE'):
564
601
  import django
@@ -592,7 +629,7 @@ def hello(req):
592
629
  S['cls'] = getattr(mod, req['cls'].rpartition('.')[2]) if req.get('cls') else None
593
630
  S['loop'] = asyncio.new_event_loop()
594
631
  asyncio.set_event_loop(S['loop'])
595
- return {'ok': True, 'nativeSnapshot': 1, 'nativeBindings': 1, 'nativeEquality': 'scalar'}
632
+ return {'ok': True, 'nativeSnapshot': 1, 'nativeBindings': 1, 'nativeObservations': 1, 'nativeEquality': 'scalar'}
596
633
 
597
634
  def make(args):
598
635
  global OBJ_STORES
@@ -626,6 +663,47 @@ def set_globals(stores):
626
663
  if isinstance(table, ORMTable): table.install()
627
664
  for g in S.get('globals') or []: setattr(importlib.import_module(g['mod']), g['name'], stores[g['name']])
628
665
 
666
+ def native_callable(fn, method):
667
+ native_fn = fn.__func__ if isinstance(fn, types.MethodType) else fn
668
+ seen = set()
669
+ while True:
670
+ if not isinstance(native_fn, types.FunctionType):
671
+ raise ValueError('unsupported native callable for parameter capture')
672
+ if id(native_fn) in seen or len(seen) >= 32:
673
+ raise ValueError('customized native signature metadata is unsupported')
674
+ seen.add(id(native_fn))
675
+ if any(dict.__contains__(native_fn.__dict__, name) for name in ('__signature__', '__text_signature__')):
676
+ raise ValueError('customized native signature metadata is unsupported')
677
+ if not dict.__contains__(native_fn.__dict__, '__wrapped__'): break
678
+ native_fn = dict.__getitem__(native_fn.__dict__, '__wrapped__')
679
+ expected = (S.get('nativeMethods') or {}).get(method)
680
+ if len(seen) > 1 and expected is None:
681
+ raise ValueError('customized native signature metadata is unsupported')
682
+ if expected is not None and (os.path.realpath(native_fn.__code__.co_filename) != os.path.realpath(os.path.join(S['root'], expected['file'])) or native_fn.__code__.co_name != method or native_fn.__code__.co_firstlineno != expected['line']):
683
+ raise ValueError('customized native signature metadata is unsupported')
684
+ if len(seen) > 1:
685
+ file = os.path.realpath(native_fn.__code__.co_filename)
686
+ if file not in NATIVE_SOURCE_CODES:
687
+ with open(file, 'rb') as source: compiled = compile(source.read(), native_fn.__code__.co_filename, 'exec', dont_inherit=True)
688
+ codes = []
689
+ def collect(code):
690
+ codes.append(code)
691
+ for value in code.co_consts:
692
+ if isinstance(value, types.CodeType): collect(value)
693
+ collect(compiled)
694
+ NATIVE_SOURCE_CODES[file] = codes
695
+ candidates = [code for code in NATIVE_SOURCE_CODES[file] if code.co_name == method and code.co_firstlineno == expected['line']]
696
+ if len(candidates) != 1 or candidates[0] != native_fn.__code__:
697
+ raise ValueError('customized native signature metadata is unsupported')
698
+ # A wrapper chain nominates a candidate only. Inspect genuine code/defaults;
699
+ # invocation below must observe this exact code with unchanged arguments.
700
+ fresh = types.FunctionType(native_fn.__code__, native_fn.__globals__, native_fn.__name__, native_fn.__defaults__, native_fn.__closure__)
701
+ fresh.__kwdefaults__ = native_fn.__kwdefaults__
702
+ receiver = fn.__self__ if isinstance(fn, types.MethodType) else None
703
+ receiver_name = next(iter(inspect.signature(fresh).parameters), None) if isinstance(fn, types.MethodType) else None
704
+ signature = inspect.signature(types.MethodType(fresh, receiver) if receiver_name is not None else fresh, follow_wrapped=False)
705
+ return native_fn.__code__, signature, receiver_name, receiver
706
+
629
707
  def call(req):
630
708
  obj, stores = OBJS[req['id']]
631
709
  global OBJ_STORES
@@ -640,22 +718,41 @@ def call(req):
640
718
  try: kwargs = fixed_args(req['a'], {})
641
719
  except OverflowError as e:
642
720
  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.
721
+ # Snapshot call-bound values before a wrapper/body can mutate them. Admission
722
+ # also requires the source method's real entry frame, never just __wrapped__.
723
+ target, entered = None, None
645
724
  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)
725
+ target, signature, receiver_name, receiver = native_callable(fn, req['m'])
726
+ bound = signature.bind(**kwargs)
652
727
  bound.apply_defaults()
653
728
  native_bindings = {'snapshot': native_state(types.SimpleNamespace(**bound.arguments), select=False)}
654
729
  except Exception as e:
730
+ target = None
655
731
  native_bindings = {'error': f'{type(e).__name__}: {e}'[:300]}
732
+ def capture(frame, event, arg):
733
+ nonlocal entered, native_bindings
734
+ if event == 'call' and frame.f_code is target:
735
+ if entered is not None and frame is not entered:
736
+ native_bindings = {'error': 'native source method entered more than once in one invocation'}
737
+ elif entered is None:
738
+ entered = frame
739
+ try:
740
+ if receiver_name is not None and frame.f_locals.get(receiver_name) is not receiver:
741
+ raise ValueError('native source method receiver differs from the called receiver')
742
+ values = {name: frame.f_locals[name] for name in bound.arguments}
743
+ actual = native_state(types.SimpleNamespace(**values), select=False)
744
+ if json.dumps(actual['root']['items']) != json.dumps(native_bindings['snapshot']['root']['items']):
745
+ raise ValueError('decorator changed native arguments before source method entry')
746
+ except Exception as e:
747
+ native_bindings = {'error': f'{type(e).__name__}: {e}'[:300]}
748
+ return tracer(frame, event, arg)
656
749
  before = frames(obj if S['cls'] is not None else None)
657
750
  snap = state_of(obj, stores) if S.get('discard') and S['cls'] is not None else None
658
- sys.settrace(tracer)
751
+ NATIVE_INVOCATION[0] += 1
752
+ NATIVE_EVENTS[0] = {'invocation': NATIVE_INVOCATION[0], 'calls': {}}
753
+ NATIVE_EVENT_ERROR[0] = None
754
+ NATIVE_CALL_TYPES.clear()
755
+ sys.settrace(capture)
659
756
  try:
660
757
  with pinned(): out = run(fn(**kwargs))
661
758
  err = None
@@ -667,11 +764,22 @@ def call(req):
667
764
  with open(os.environ['GDP_HARNESS_LOG'], 'a') as f: f.write(f"{req['m']} {json.dumps(req.get('answers'))}\n{traceback.format_exc()}\n")
668
765
  finally:
669
766
  sys.settrace(None)
767
+ if target is not None and entered is None:
768
+ native_bindings = {'error': 'native source method entry was not observed'}
769
+ try:
770
+ if NATIVE_EVENT_ERROR[0]: native_observations = {'error': NATIVE_EVENT_ERROR[0]}
771
+ else:
772
+ events = NATIVE_EVENTS[0]
773
+ calls = types.SimpleNamespace(**{key: types.SimpleNamespace(**value) for key, value in events['calls'].items()})
774
+ native_observations = {'snapshot': native_state(types.SimpleNamespace(invocation=events['invocation'], calls=calls), select=False)}
775
+ except Exception as e:
776
+ native_observations = {'error': f'{type(e).__name__}: {e}'[:300]}
777
+ finally: NATIVE_EVENTS[0] = None
670
778
  if err is not None and snap is not None: set_state(obj, stores, snap)
671
779
  after = frames(obj if S['cls'] is not None else None)
672
780
  for k in before:
673
781
  if after.get(k) != before[k]: return {'frame': k}
674
- return {'out': tag(out), 'nativeBindings': native_bindings, **({'err': err} if err is not None else {}), **({'effects': dict(EFF)} if EFF else {})}
782
+ return {'out': tag(out), 'nativeBindings': native_bindings, 'nativeObservations': native_observations, **({'err': err} if err is not None else {}), **({'effects': dict(EFF)} if EFF else {})}
675
783
 
676
784
  # Native observation transport for ordered containers. Retain real references
677
785
  # so Python cannot recycle an address and manufacture cross-snapshot identity.
@@ -679,6 +787,7 @@ def native_state(obj, select=True):
679
787
  seen = set()
680
788
  count = [0]
681
789
  def encode(value, names=None):
790
+ if type(value) is FakeStore: value = value.data
682
791
  count[0] += 1
683
792
  if count[0] > 10000: raise ValueError('native snapshot exceeds node bound')
684
793
  if value is None or isinstance(value, (str, bool)): return value
@@ -706,7 +815,7 @@ def native_state(obj, select=True):
706
815
  fields = vars(value)
707
816
  if names is not None: fields = {name: fields[name] for name in names}
708
817
  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'})
818
+ roots = sorted({l['path'][0] for l in S['leaves'] if l.get('path') and l['kind'] != 'frame'} | {l['store'].split('.')[0] for l in S['leaves'] if l.get('store')})
710
819
  return {'version': 1, 'root': encode(obj, roots if select else None)}
711
820
 
712
821
  def main():
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.50.4",
3
+ "version": "0.50.5",
4
4
  "description": "An automatic prover for stateful rules (budgets, caps, windows, workflows, policies): laws proven with no proof to write, checked again in Lean, counterexamples found on the GPU, the rule shipped as code",
5
5
  "keywords": [
6
6
  "verification",