gdp-wired 0.50.4 → 0.50.6

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.
@@ -1481,13 +1481,9 @@ function renameKey(lin, from, to) {
1481
1481
  // just need a stronger invariant.
1482
1482
  export function search(m, law, depth = 3, bound = 2) {
1483
1483
  const run = interpret(m);
1484
- const holds = (params, st) => {
1485
- const finite = finiteLawBound(law);
1486
- if (finite)
1487
- return evalC({ op: 'all', key: law.forall, c: law.holds, finite: law.finite }, params, st, m);
1488
- const keys = law.forall ? [...new Set([0, ...Object.values(st.maps).flatMap(cells => [...cells.keys()])])] : [0];
1489
- return keys.every(key => evalC(law.holds, { ...params, ...(law.forall ? { [law.forall]: key } : {}) }, st, m));
1490
- };
1484
+ finiteLawBound(law); // Preserve validation of explicit finite-domain metadata.
1485
+ const condition = law.forall ? { op: 'all', key: law.forall, keys: law.keys, c: law.holds, finite: law.finite } : law.holds;
1486
+ const holds = (params, st) => evalC(condition, params, st, m);
1491
1487
  const tops = new Map();
1492
1488
  const conj = (c) => (c === undefined ? [] : c.op === 'and' ? c.xs.flatMap(conj) : [c]);
1493
1489
  for (const c of [...conj(m.pre), ...conj(m.assume)])
@@ -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.6",
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",