pg-language-integrated 0.3.0rc2__py3-none-any.whl

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 (154) hide show
  1. pg_adaptive/__init__.py +2 -0
  2. pg_adaptive/coordinator.py +30 -0
  3. pg_chaos/__init__.py +2 -0
  4. pg_chaos/__main__.py +2 -0
  5. pg_chaos/cli.py +22 -0
  6. pg_chaos/runtime.py +525 -0
  7. pg_core/__init__.py +31 -0
  8. pg_core/__main__.py +6 -0
  9. pg_core/benchmark.py +390 -0
  10. pg_core/bridge.py +294 -0
  11. pg_core/bridge_worker.py +128 -0
  12. pg_core/cli.py +294 -0
  13. pg_core/compiler.py +1136 -0
  14. pg_core/data/dictionary.json +318 -0
  15. pg_core/data/external_lock.json +25 -0
  16. pg_core/data/grammar.ebnf +95 -0
  17. pg_core/dictionary.py +244 -0
  18. pg_core/dispatch.py +237 -0
  19. pg_core/errors.py +138 -0
  20. pg_core/external/__init__.py +1 -0
  21. pg_core/external/runtime.py +66 -0
  22. pg_core/external_registry.py +300 -0
  23. pg_core/model.py +206 -0
  24. pg_core/native/pg_bridge_runtime.c +88 -0
  25. pg_core/native/pg_bridge_runtime.h +22 -0
  26. pg_core/native/pg_memory_probe.c +64 -0
  27. pg_core/native/pg_native_runtime.c +698 -0
  28. pg_core/native/pg_native_runtime.h +178 -0
  29. pg_core/native_backend.py +965 -0
  30. pg_core/native_input.py +161 -0
  31. pg_core/optimizer.py +447 -0
  32. pg_core/parser.py +494 -0
  33. pg_core/release.py +88 -0
  34. pg_core/runtime.py +813 -0
  35. pg_health/__init__.py +15 -0
  36. pg_health/__main__.py +2 -0
  37. pg_health/cli.py +25 -0
  38. pg_health/release.py +10 -0
  39. pg_health/runtime.py +188 -0
  40. pg_jisho/__init__.py +15 -0
  41. pg_jisho/__main__.py +3 -0
  42. pg_jisho/cli.py +63 -0
  43. pg_jisho/workspace.py +510 -0
  44. pg_language_integrated-0.3.0rc2.dist-info/METADATA +78 -0
  45. pg_language_integrated-0.3.0rc2.dist-info/RECORD +154 -0
  46. pg_language_integrated-0.3.0rc2.dist-info/WHEEL +5 -0
  47. pg_language_integrated-0.3.0rc2.dist-info/entry_points.txt +22 -0
  48. pg_language_integrated-0.3.0rc2.dist-info/top_level.txt +19 -0
  49. pg_live/__init__.py +4 -0
  50. pg_live/__main__.py +5 -0
  51. pg_live/cli.py +256 -0
  52. pg_live/errors.py +23 -0
  53. pg_live/model.py +57 -0
  54. pg_live/release.py +40 -0
  55. pg_live/session.py +644 -0
  56. pg_mining/__init__.py +3 -0
  57. pg_mining/__main__.py +2 -0
  58. pg_mining/cli.py +24 -0
  59. pg_mining/release.py +23 -0
  60. pg_mining/runtime.py +105 -0
  61. pg_multinode/__init__.py +1 -0
  62. pg_multinode/__main__.py +2 -0
  63. pg_multinode/cli.py +14 -0
  64. pg_multinode/runtime.py +526 -0
  65. pg_orgnet/__init__.py +12 -0
  66. pg_orgnet/__main__.py +2 -0
  67. pg_orgnet/cli.py +12 -0
  68. pg_orgnet/release.py +27 -0
  69. pg_orgnet/runtime.py +574 -0
  70. pg_preview/__init__.py +4 -0
  71. pg_preview/__main__.py +2 -0
  72. pg_preview/api_probe.py +39 -0
  73. pg_preview/cli.py +78 -0
  74. pg_preview/core.py +476 -0
  75. pg_preview/cuda.py +26 -0
  76. pg_preview/legacy_net.py +32 -0
  77. pg_preview/library.py +141 -0
  78. pg_preview/net.py +170 -0
  79. pg_preview/net_cli.py +31 -0
  80. pg_preview/platform.py +149 -0
  81. pg_preview/security.py +17 -0
  82. pg_preview/stdlib.py +66 -0
  83. pg_recovery/__init__.py +6 -0
  84. pg_recovery/__main__.py +2 -0
  85. pg_recovery/cli.py +24 -0
  86. pg_recovery/release.py +25 -0
  87. pg_recovery/runtime.py +203 -0
  88. pg_robustness/__init__.py +9 -0
  89. pg_robustness/__main__.py +2 -0
  90. pg_robustness/cli.py +23 -0
  91. pg_robustness/runtime.py +384 -0
  92. pg_root/__init__.py +10 -0
  93. pg_root/__main__.py +2 -0
  94. pg_root/cli.py +12 -0
  95. pg_root/release.py +21 -0
  96. pg_root/runtime.py +272 -0
  97. pg_safe/__init__.py +7 -0
  98. pg_safe/__main__.py +2 -0
  99. pg_safe/cli.py +20 -0
  100. pg_safe/release.py +23 -0
  101. pg_safe/runtime.py +419 -0
  102. pg_sdk/__init__.py +20 -0
  103. pg_sdk/__main__.py +5 -0
  104. pg_sdk/cli.py +171 -0
  105. pg_sdk/debugger.py +249 -0
  106. pg_sdk/errors.py +42 -0
  107. pg_sdk/ffi.py +196 -0
  108. pg_sdk/ffi_worker.py +110 -0
  109. pg_sdk/lsp.py +295 -0
  110. pg_sdk/release.py +88 -0
  111. pg_sdk/stdlib.py +276 -0
  112. pg_sdk/supervisor.py +395 -0
  113. pg_sdk/targets.py +245 -0
  114. pg_system/__init__.py +15 -0
  115. pg_system/__main__.py +5 -0
  116. pg_system/cli.py +170 -0
  117. pg_system/compiler.py +331 -0
  118. pg_system/data/system.ebnf +29 -0
  119. pg_system/errors.py +87 -0
  120. pg_system/materialize.py +242 -0
  121. pg_system/message_queue.py +61 -0
  122. pg_system/model.py +268 -0
  123. pg_system/parser.py +258 -0
  124. pg_system/release.py +59 -0
  125. pg_system/runtime.py +538 -0
  126. pg_system/scheduler.py +108 -0
  127. pg_system/units.py +213 -0
  128. pg_system/worker.py +43 -0
  129. pg_system_link/__init__.py +15 -0
  130. pg_system_link/__main__.py +5 -0
  131. pg_system_link/cli.py +171 -0
  132. pg_system_link/compiler.py +378 -0
  133. pg_system_link/data/system_link.ebnf +30 -0
  134. pg_system_link/errors.py +47 -0
  135. pg_system_link/materialize.py +266 -0
  136. pg_system_link/model.py +239 -0
  137. pg_system_link/parser.py +165 -0
  138. pg_system_link/release.py +64 -0
  139. pg_system_link/runtime.py +858 -0
  140. pg_system_link/scheduler.py +212 -0
  141. pg_system_link/systems.py +372 -0
  142. pg_system_link/worker.py +110 -0
  143. pg_team/__init__.py +13 -0
  144. pg_team/__main__.py +2 -0
  145. pg_team/cli.py +14 -0
  146. pg_team/release.py +25 -0
  147. pg_team/runtime.py +493 -0
  148. pg_vm/__init__.py +37 -0
  149. pg_vm/__main__.py +3 -0
  150. pg_vm/cli.py +83 -0
  151. pg_vm/release.py +43 -0
  152. pg_vm/replan.py +177 -0
  153. pg_vm/runtime.py +693 -0
  154. pg_vm/sim_gpu.py +241 -0
@@ -0,0 +1,2 @@
1
+ from .coordinator import PGAdaptiveCoordinator, ParallelAnalysis, AdaptiveCycle
2
+ __all__ = ["PGAdaptiveCoordinator", "ParallelAnalysis", "AdaptiveCycle"]
@@ -0,0 +1,30 @@
1
+ """No-AI adaptive coordinator: deterministic mining, telemetry and replan only."""
2
+ from dataclasses import dataclass
3
+ from typing import Any
4
+ from pg_mining import PGMining, PGMiningReport
5
+ from pg_health import PGHealthMonitor, PGHealthReport, HealthTelemetry
6
+ @dataclass(frozen=True)
7
+ class ParallelAnalysis:
8
+ mining: PGMiningReport
9
+ parallel: bool=False
10
+ @dataclass(frozen=True)
11
+ class AdaptiveCycle:
12
+ analysis: ParallelAnalysis
13
+ health: PGHealthReport
14
+ replan: Any
15
+ result: dict
16
+ class PGAdaptiveCoordinator:
17
+ def __init__(self,mining=None,health=None,trace_window=512):
18
+ self.mining=mining or PGMining(); self.health=health or PGHealthMonitor(); self.trace_window=max(32,min(4096,int(trace_window)))
19
+ def analyze(self,program,*,vm_trace=(),runtime_logs=(),mining_policy=None):
20
+ from collections import deque
21
+ trace=tuple(dict(x) for x in deque(vm_trace,maxlen=self.trace_window))
22
+ return ParallelAnalysis(self.mining.analyze(trace,mining_policy))
23
+ def cycle(self,program,inputs,*,vm,vm_policy,telemetry=None,runtime_logs=(),mining_policy=None,replan_context=None):
24
+ original=vm.plan(program,inputs,vm_policy)
25
+ analysis=self.analyze(program,vm_trace=vm.trace,runtime_logs=runtime_logs,mining_policy=mining_policy)
26
+ health=self.health.evaluate(telemetry or HealthTelemetry(source="default-empty"))
27
+ decision=vm.replan(program,inputs,vm_policy,original,health_report=health,mining_report=analysis.mining,context=replan_context)
28
+ final_plan,final_policy=(original,vm_policy) if decision.status=="deferred" else (decision.plan or original,decision.policy or vm_policy)
29
+ result=vm._execute_plan(program,inputs,final_policy,final_plan,replan_decision=decision)
30
+ return AdaptiveCycle(analysis,health,decision,result)
pg_chaos/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ from .runtime import PG_CHAOS_VERSION, PGChaosFailure, ChaosCampaignResult, PGChaosDrill
2
+ __all__ = ["PG_CHAOS_VERSION", "PGChaosFailure", "ChaosCampaignResult", "PGChaosDrill"]
pg_chaos/__main__.py ADDED
@@ -0,0 +1,2 @@
1
+ from .cli import main
2
+ raise SystemExit(main())
pg_chaos/cli.py ADDED
@@ -0,0 +1,22 @@
1
+ from __future__ import annotations
2
+ import argparse, json
3
+ from .runtime import PG_CHAOS_VERSION, PGChaosDrill
4
+
5
+ def main(argv=None):
6
+ p=argparse.ArgumentParser(prog="pg-chaos")
7
+ sub=p.add_subparsers(dest="cmd",required=True)
8
+ sub.add_parser("info")
9
+ run=sub.add_parser("run")
10
+ run.add_argument("--crash",type=int,default=25)
11
+ run.add_argument("--partition",type=int,default=1000)
12
+ run.add_argument("--authority",type=int,default=100)
13
+ run.add_argument("--team",type=int,default=100)
14
+ run.add_argument("--snapshots",type=int,default=250)
15
+ run.add_argument("--compound",type=int,default=1000)
16
+ run.add_argument("--disaster",type=int,default=10)
17
+ ns=p.parse_args(argv)
18
+ if ns.cmd=="info":
19
+ print(json.dumps({"release":f"PG-Chaos-{PG_CHAOS_VERSION}","status":"compound-failure-simulation"},indent=2)); return 0
20
+ out=PGChaosDrill().run_all(crash=ns.crash,partition=ns.partition,authority=ns.authority,team=ns.team,snapshots=ns.snapshots,compound=ns.compound,disaster=ns.disaster)
21
+ print(json.dumps(out,ensure_ascii=False,indent=2)); return 0 if out["status"]=="PASS" else 1
22
+ if __name__=="__main__": raise SystemExit(main())
pg_chaos/runtime.py ADDED
@@ -0,0 +1,525 @@
1
+ from __future__ import annotations
2
+
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ from dataclasses import asdict, dataclass, replace
5
+ from pathlib import Path
6
+ from typing import Any
7
+ import json
8
+ import os
9
+ import random
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ import time
14
+ import zipfile
15
+
16
+ from pg_orgnet import (
17
+ PGOrgNetwork, OrgGroup, NetworkBoundaryError, OrgAuthorizationError,
18
+ OrgConflictError,
19
+ )
20
+ from pg_root import PGRootAuthority
21
+ from pg_recovery import PGRecoveryManager
22
+ from pg_team import PGTeamWorkspace, ProjectSnapshot, TeamActor, TeamPolicy, TeamConflictError
23
+
24
+ PG_CHAOS_VERSION = "0.1.0"
25
+
26
+
27
+ class PGChaosFailure(RuntimeError):
28
+ pass
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class ChaosCampaignResult:
33
+ name: str
34
+ seed: int
35
+ iterations: int
36
+ passed: int
37
+ safe_blocks: int
38
+ failures: int
39
+ duration_ms: float
40
+ invariants: tuple[str, ...]
41
+ details: dict[str, Any]
42
+
43
+ def to_dict(self) -> dict[str, Any]:
44
+ return asdict(self)
45
+
46
+
47
+ class PGChaosDrill:
48
+ """Compound failure drills for the PG simulation platform.
49
+
50
+ These drills deliberately combine failures that are individually covered by
51
+ PG-Robustness 0.1: process death, internal-network partition, concurrent
52
+ authority changes, stale collaboration revisions and corrupted checkpoints.
53
+ The harness proves simulation invariants only; it is not production HA or
54
+ distributed-consensus certification.
55
+ """
56
+
57
+ def __init__(self) -> None:
58
+ pass
59
+
60
+ @staticmethod
61
+ def _make_org() -> tuple[PGRootAuthority, PGOrgNetwork]:
62
+ root = PGRootAuthority("CHAOS-ROOT")
63
+ org = PGOrgNetwork(root, network_id="CORP-INTERNAL")
64
+ org.define_group(OrgGroup("Developers", ("Read", "Edit", "Build", "OrgRequest")))
65
+ org.define_group(OrgGroup("Reviewers", ("Read", "TeamApprove", "GroupApprove", "PermissionApprove", "OrgRequest")))
66
+ org.define_group(OrgGroup("Operators", ("Read", "TeamApply", "OrgApply", "DeviceManage", "OrgRequest")))
67
+ org.define_group(OrgGroup("Production-Admin", ("Deploy", "RawAccess"), sensitive=True, required_approvals=2, approver_permissions=("GroupApprove",)))
68
+ for uid in ("alice", "bob", "reviewer1", "reviewer2", "operator"):
69
+ org.enroll_user(uid, display_name=uid)
70
+ org.set_membership_bootstrap("alice", "Developers")
71
+ org.set_membership_bootstrap("reviewer1", "Reviewers")
72
+ org.set_membership_bootstrap("reviewer2", "Reviewers")
73
+ org.set_membership_bootstrap("operator", "Operators")
74
+ allp = (
75
+ "Read", "Edit", "Build", "OrgRequest", "TeamApprove", "GroupApprove",
76
+ "PermissionApprove", "TeamApply", "OrgApply", "DeviceManage", "Deploy", "RawAccess",
77
+ )
78
+ org.enroll_device("alice-dev", permission_ceiling=allp, allowed_users=("alice",))
79
+ org.enroll_device("review-pc", permission_ceiling=allp, allowed_users=("reviewer1", "reviewer2"))
80
+ org.enroll_device("ops-pc", permission_ceiling=allp, allowed_users=("operator",))
81
+ return root, org
82
+
83
+ @staticmethod
84
+ def _session(org: PGOrgNetwork, user: str, device: str, project: str = "proj"):
85
+ return org.open_session(user, device, project_scope=project, network_id="CORP-INTERNAL")
86
+
87
+ @staticmethod
88
+ def _corrupt_snapshot(src: Path, dst: Path) -> None:
89
+ with zipfile.ZipFile(src, "r") as zin:
90
+ manifest = zin.read("manifest.json")
91
+ payload = json.loads(zin.read("payload.json"))
92
+ payload["state"] = "tampered-after-crash"
93
+ with zipfile.ZipFile(dst, "w", compression=zipfile.ZIP_DEFLATED) as zout:
94
+ zout.writestr("manifest.json", manifest)
95
+ zout.writestr("payload.json", json.dumps(payload, sort_keys=True, indent=2))
96
+
97
+ @staticmethod
98
+ def _run_crash_worker(ledger_path: Path, effect_id: str) -> int:
99
+ # Separate interpreter: persist the external effect and die before the PG
100
+ # environment can commit its local post-effect state.
101
+ code = r'''
102
+ import json, os, sys
103
+ p=sys.argv[1]; effect=sys.argv[2]
104
+ try:
105
+ with open(p, 'r', encoding='utf-8') as f: data=json.load(f)
106
+ except FileNotFoundError:
107
+ data={"effects":[]}
108
+ if effect not in data["effects"]: data["effects"].append(effect)
109
+ tmp=p+".tmp"
110
+ with open(tmp,'w',encoding='utf-8') as f:
111
+ json.dump(data,f,sort_keys=True); f.flush(); os.fsync(f.fileno())
112
+ os.replace(tmp,p)
113
+ os._exit(23)
114
+ '''
115
+ proc = subprocess.run([sys.executable, "-c", code, str(ledger_path), effect_id], check=False)
116
+ return int(proc.returncode)
117
+
118
+ def process_crash_recovery(self, *, iterations: int = 50, seed: int = 3501) -> ChaosCampaignResult:
119
+ rng = random.Random(seed)
120
+ start = time.perf_counter()
121
+ passed = blocked = failures = 0
122
+ fallback_count = 0
123
+ with tempfile.TemporaryDirectory(prefix="pg-chaos-crash-") as td:
124
+ td = Path(td)
125
+ manager = PGRecoveryManager("chaos-recovery-key")
126
+ for i in range(iterations):
127
+ try:
128
+ effect = f"payment:effect-{seed}-{i}"
129
+ checkpoint = td / f"cp-{i}.pgsnap"
130
+ ledger = td / f"ledger-{i}.json"
131
+ base = {"state": "safe", "counter": i, "external_effect_ledger": []}
132
+ manager.create_snapshot(checkpoint, base, kind="Verified-Checkpoint", created_by="chaos", recovery_tested=True)
133
+ rc = self._run_crash_worker(ledger, effect)
134
+ if rc != 23:
135
+ raise PGChaosFailure(f"crash worker returned {rc}")
136
+ persisted = json.loads(ledger.read_text(encoding="utf-8"))["effects"]
137
+ if persisted.count(effect) != 1:
138
+ raise PGChaosFailure("durable external effect was not committed exactly once")
139
+ current = {"state": "partial-after-crash", "counter": -1, "external_effect_ledger": list(persisted)}
140
+ rr = manager.restore_snapshot(checkpoint, current, safe_point="checkpoint")
141
+ if rr.status != "restored" or rr.restored_state.get("state") != "safe":
142
+ raise PGChaosFailure("checkpoint did not restore after process crash")
143
+ if list(rr.external_effects_preserved).count(effect) != 1:
144
+ raise PGChaosFailure("recovery duplicated or erased committed external effect")
145
+ # Simulated retry after recovery: durable effect-ID check suppresses replay.
146
+ retry_ledger = list(rr.external_effects_preserved)
147
+ if effect not in retry_ledger:
148
+ retry_ledger.append(effect)
149
+ if retry_ledger.count(effect) != 1:
150
+ raise PGChaosFailure("post-recovery retry duplicated external effect")
151
+ passed += 1
152
+ except Exception:
153
+ failures += 1
154
+ return ChaosCampaignResult(
155
+ "process-crash-recovery", seed, iterations, passed, blocked, failures,
156
+ (time.perf_counter() - start) * 1000,
157
+ (
158
+ "external effect survives process death exactly once",
159
+ "PG state restores only from a verified Safe Point checkpoint",
160
+ "post-recovery retry does not replay a committed effect ID",
161
+ ),
162
+ {"child_exit_code": 23, "fallbacks": fallback_count},
163
+ )
164
+
165
+ def network_partition(self, *, iterations: int = 5000, seed: int = 3502) -> ChaosCampaignResult:
166
+ rng = random.Random(seed)
167
+ start = time.perf_counter()
168
+ passed = blocked = failures = 0
169
+ root, org = self._make_org()
170
+ session = self._session(org, "alice", "alice-dev")
171
+ for i in range(iterations):
172
+ try:
173
+ # Sign before partition on some iterations to verify existing
174
+ # credentials cannot cross an active network partition.
175
+ signed = org.sign_operation(session, {"action": "EDIT", "i": i})
176
+ org.partition_device_network("alice-dev")
177
+ d = org.authorize(signed, required_permission="Edit")
178
+ if d.allowed:
179
+ raise PGChaosFailure("pre-partition signed operation crossed active partition")
180
+ blocked += 1
181
+ try:
182
+ org.open_session("alice", "alice-dev", project_scope="proj", network_id="CORP-INTERNAL")
183
+ raise PGChaosFailure("partitioned device opened a new session")
184
+ except NetworkBoundaryError:
185
+ blocked += 1
186
+ org.heal_device_network("alice-dev")
187
+ # Old pre-partition operation remains unused and may be authorized
188
+ # after link restoration; a subsequent replay must still fail.
189
+ if not org.authorize(signed, required_permission="Edit").allowed:
190
+ raise PGChaosFailure("healed internal network failed valid unused operation")
191
+ if org.authorize(signed, required_permission="Edit").allowed:
192
+ raise PGChaosFailure("healed network accepted signed-operation replay")
193
+ # Randomly prove a fresh operation too.
194
+ if rng.random() < 0.2:
195
+ fresh = org.sign_operation(session, {"action": "BUILD", "i": i})
196
+ if not org.authorize(fresh, required_permission="Build").allowed:
197
+ raise PGChaosFailure("fresh operation failed after network heal")
198
+ passed += 1
199
+ except Exception:
200
+ failures += 1
201
+ # Keep campaign deterministic after a failed case.
202
+ org.heal_device_network("alice-dev")
203
+ return ChaosCampaignResult(
204
+ "network-partition", seed, iterations, passed, blocked, failures,
205
+ (time.perf_counter() - start) * 1000,
206
+ (
207
+ "active partition blocks existing signed traffic and new sessions",
208
+ "healing restores internal-network access without expanding permissions",
209
+ "nonce replay protection survives partition/heal cycles",
210
+ ),
211
+ {"audit_chain_ok": org.verify_audit_chain(), "partition_events": iterations},
212
+ )
213
+
214
+ def concurrent_authority_changes(self, *, iterations: int = 250, seed: int = 3503) -> ChaosCampaignResult:
215
+ start = time.perf_counter()
216
+ passed = blocked = failures = 0
217
+ root, org = self._make_org()
218
+ for i in range(iterations):
219
+ try:
220
+ # Two changes are created against the same organization revision.
221
+ requester = self._session(org, "alice", "alice-dev")
222
+ a = org.propose_change(requester, kind="SET_DIRECT_PERMISSION", subject_id="bob", target="Deploy", value=(i % 2 == 0), reason=f"race-a-{i}")
223
+ b = org.propose_change(requester, kind="SET_DIRECT_PERMISSION", subject_id="bob", target="RawAccess", value=(i % 2 == 1), reason=f"race-b-{i}")
224
+ for rid in (a.request_id, b.request_id):
225
+ org.approve_change(rid, self._session(org, "reviewer1", "review-pc"))
226
+ org.approve_change(rid, self._session(org, "reviewer2", "review-pc"))
227
+ def apply(rid: str) -> str:
228
+ try:
229
+ org.apply_change(rid, self._session(org, "operator", "ops-pc"))
230
+ return "APPLIED"
231
+ except OrgConflictError:
232
+ return "STALE"
233
+ with ThreadPoolExecutor(max_workers=2) as ex:
234
+ outcomes = list(ex.map(apply, (a.request_id, b.request_id)))
235
+ if sorted(outcomes) != ["APPLIED", "STALE"]:
236
+ raise PGChaosFailure(f"authority race produced {outcomes}")
237
+ if i % 64 == 0 and not org.verify_audit_chain():
238
+ raise PGChaosFailure("OrgNet audit chain broke during concurrent authority changes")
239
+ passed += 1
240
+ blocked += 1
241
+ except Exception:
242
+ failures += 1
243
+ if not org.verify_audit_chain():
244
+ failures += 1
245
+ return ChaosCampaignResult(
246
+ "concurrent-authority", seed, iterations, passed, blocked, failures,
247
+ (time.perf_counter() - start) * 1000,
248
+ (
249
+ "two writes against one organization revision cannot both apply",
250
+ "losing concurrent authority change becomes STALE rather than auto-merged",
251
+ "authority audit chain remains intact",
252
+ ),
253
+ {"final_revision": org.revision, "audit_entries": len(org.audit)},
254
+ )
255
+
256
+ def concurrent_team_changes(self, *, iterations: int = 250, seed: int = 3504) -> ChaosCampaignResult:
257
+ start = time.perf_counter()
258
+ passed = blocked = failures = 0
259
+ for i in range(iterations):
260
+ try:
261
+ initial = ProjectSnapshot(revision=0, source_files={"main.pg": "alpha\n"})
262
+ ws = PGTeamWorkspace(initial, policy=TeamPolicy())
263
+ author = TeamActor("author", "human", ("Read", "Edit"))
264
+ reviewer = TeamActor("reviewer", "human", ("Read", "TeamApprove"))
265
+ applier = TeamActor("operator", "human", ("Read", "TeamApply"))
266
+ pa = ws.propose(author, replace(initial, source_files={"main.pg": f"A-{i}\n"}), reason="race-a")
267
+ pb = ws.propose(author, replace(initial, source_files={"main.pg": f"B-{i}\n"}), reason="race-b")
268
+ ws.approve(pa.proposal_id, reviewer)
269
+ ws.approve(pb.proposal_id, reviewer)
270
+ def apply(pid: str) -> str:
271
+ try:
272
+ ws.apply(pid, applier)
273
+ return "APPLIED"
274
+ except TeamConflictError:
275
+ return "STALE"
276
+ with ThreadPoolExecutor(max_workers=2) as ex:
277
+ outcomes = list(ex.map(apply, (pa.proposal_id, pb.proposal_id)))
278
+ if sorted(outcomes) != ["APPLIED", "STALE"]:
279
+ raise PGChaosFailure(f"team race produced {outcomes}")
280
+ if ws.current.revision != 1 or not ws.verify_audit_chain():
281
+ raise PGChaosFailure("PG-Team concurrent apply damaged revision/audit state")
282
+ passed += 1
283
+ blocked += 1
284
+ except Exception:
285
+ failures += 1
286
+ return ChaosCampaignResult(
287
+ "concurrent-team", seed, iterations, passed, blocked, failures,
288
+ (time.perf_counter() - start) * 1000,
289
+ (
290
+ "two proposals against one Team revision cannot both apply",
291
+ "stale semantic proposal is rejected instead of silently merged",
292
+ "Team audit hash chain remains intact",
293
+ ),
294
+ {},
295
+ )
296
+
297
+ def snapshot_chain(self, *, iterations: int = 1000, seed: int = 3505) -> ChaosCampaignResult:
298
+ start = time.perf_counter()
299
+ passed = blocked = failures = 0
300
+ with tempfile.TemporaryDirectory(prefix="pg-chaos-snap-") as td:
301
+ td = Path(td)
302
+ manager = PGRecoveryManager("chaos-chain-key")
303
+ for i in range(iterations):
304
+ try:
305
+ primary = td / f"primary-{i}.pgsnap"
306
+ secondary = td / f"secondary-{i}.pgsnap"
307
+ corrupt = td / f"corrupt-{i}.pgsnap"
308
+ manager.create_snapshot(secondary, {"state": "older-safe", "generation": i, "external_effect_ledger": []}, kind="PG-Environment", created_by="chaos", recovery_tested=True)
309
+ manager.create_snapshot(primary, {"state": "newest-safe", "generation": i + 1, "external_effect_ledger": []}, kind="Verified-Checkpoint", created_by="chaos", recovery_tested=True)
310
+ self._corrupt_snapshot(primary, corrupt)
311
+ current = {"state": "broken", "external_effect_ledger": [f"effect:{i}"]}
312
+ selected = None
313
+ for candidate in (corrupt, secondary):
314
+ rr = manager.restore_snapshot(candidate, current, safe_point="checkpoint")
315
+ if rr.status == "restored":
316
+ selected = rr
317
+ break
318
+ blocked += 1
319
+ if selected is None:
320
+ raise PGChaosFailure("recovery chain exhausted despite valid secondary snapshot")
321
+ if selected.restored_state.get("state") != "older-safe":
322
+ raise PGChaosFailure("recovery chain did not choose the valid secondary snapshot")
323
+ if f"effect:{i}" not in selected.external_effects_preserved:
324
+ raise PGChaosFailure("recovery chain erased post-snapshot external effect")
325
+ passed += 1
326
+ except Exception:
327
+ failures += 1
328
+ return ChaosCampaignResult(
329
+ "snapshot-chain", seed, iterations, passed, blocked, failures,
330
+ (time.perf_counter() - start) * 1000,
331
+ (
332
+ "corrupt newest checkpoint is never restored",
333
+ "next verified candidate can recover PG environment state",
334
+ "external-effect ledger survives fallback to an older snapshot",
335
+ ),
336
+ {},
337
+ )
338
+
339
+ def compound(self, *, iterations: int = 1000, seed: int = 3506) -> ChaosCampaignResult:
340
+ rng = random.Random(seed)
341
+ start = time.perf_counter()
342
+ passed = blocked = failures = 0
343
+ root, org = self._make_org()
344
+ for i in range(iterations):
345
+ try:
346
+ # One deterministic mini-drill combines network isolation and a
347
+ # conflicting authority mutation. The partitioned worker cannot
348
+ # advance; the internal operator can advance exactly one revision.
349
+ s = self._session(org, "alice", "alice-dev")
350
+ pre = org.sign_operation(s, {"action": "EDIT", "i": i})
351
+ org.partition_device_network("alice-dev")
352
+ if org.authorize(pre, required_permission="Edit").allowed:
353
+ raise PGChaosFailure("compound drill let partitioned operation through")
354
+ blocked += 1
355
+ org.heal_device_network("alice-dev")
356
+ if not org.authorize(pre, required_permission="Edit").allowed:
357
+ raise PGChaosFailure("compound drill failed healed operation")
358
+ # Random certificate/device fault after healing must not broaden rights.
359
+ if rng.randrange(20) == 0:
360
+ org.partition_device_network("alice-dev")
361
+ try:
362
+ self._session(org, "alice", "alice-dev")
363
+ raise PGChaosFailure("partitioned device acquired session")
364
+ except NetworkBoundaryError:
365
+ blocked += 1
366
+ finally:
367
+ org.heal_device_network("alice-dev")
368
+ # Full-chain verification is O(history); checkpoint it rather than
369
+ # turning the harness itself into an O(n^2) workload.
370
+ if i % 128 == 0 and not org.verify_audit_chain():
371
+ raise PGChaosFailure("compound drill broke audit chain")
372
+ passed += 1
373
+ except Exception:
374
+ failures += 1
375
+ if org.is_device_partitioned("alice-dev"):
376
+ org.heal_device_network("alice-dev")
377
+ if not org.verify_audit_chain():
378
+ failures += 1
379
+ return ChaosCampaignResult(
380
+ "compound-chaos", seed, iterations, passed, blocked, failures,
381
+ (time.perf_counter() - start) * 1000,
382
+ (
383
+ "network isolation never broadens authority",
384
+ "healing never bypasses nonce/audit invariants",
385
+ "compound fault sequence keeps OrgNet audit chain valid",
386
+ ),
387
+ {"audit_entries": len(org.audit)},
388
+ )
389
+
390
+ def disaster_chain(self, *, iterations: int = 25, seed: int = 3507) -> ChaosCampaignResult:
391
+ """End-to-end chained disaster drill.
392
+
393
+ Each iteration combines: two authority changes against one revision,
394
+ internal-network partition, a real child-process death after durable
395
+ external effect commit, corruption of the newest snapshot, fallback to
396
+ an older verified snapshot, network heal and a concurrent apply race.
397
+ """
398
+ start = time.perf_counter()
399
+ passed = blocked = failures = 0
400
+ root, org = self._make_org()
401
+ manager = PGRecoveryManager("chaos-disaster-key")
402
+ with tempfile.TemporaryDirectory(prefix="pg-chaos-disaster-") as td:
403
+ td = Path(td)
404
+ for i in range(iterations):
405
+ try:
406
+ # Prepare two governance writes against exactly one revision.
407
+ requester = self._session(org, "alice", "alice-dev")
408
+ req_a = org.propose_change(requester, kind="SET_DIRECT_PERMISSION", subject_id="bob", target="Deploy", value=(i % 2 == 0), reason=f"disaster-a-{i}")
409
+ req_b = org.propose_change(requester, kind="SET_DIRECT_PERMISSION", subject_id="bob", target="RawAccess", value=(i % 2 == 1), reason=f"disaster-b-{i}")
410
+ for rid in (req_a.request_id, req_b.request_id):
411
+ org.approve_change(rid, self._session(org, "reviewer1", "review-pc"))
412
+ org.approve_change(rid, self._session(org, "reviewer2", "review-pc"))
413
+
414
+ # Build two recovery generations, then destroy the newest one.
415
+ older = td / f"older-{i}.pgsnap"
416
+ newest = td / f"newest-{i}.pgsnap"
417
+ corrupt = td / f"newest-corrupt-{i}.pgsnap"
418
+ manager.create_snapshot(older, {"state": "older-safe", "generation": i, "external_effect_ledger": []}, kind="PG-Environment", created_by="chaos", recovery_tested=True)
419
+ manager.create_snapshot(newest, {"state": "newest-safe", "generation": i + 1, "external_effect_ledger": []}, kind="Verified-Checkpoint", created_by="chaos", recovery_tested=True)
420
+ self._corrupt_snapshot(newest, corrupt)
421
+
422
+ # A signed request is in-flight when its endpoint is partitioned.
423
+ edit_session = self._session(org, "alice", "alice-dev")
424
+ in_flight = org.sign_operation(edit_session, {"action": "EDIT", "iteration": i})
425
+ org.partition_device_network("alice-dev", actor="disaster-controller")
426
+ if org.authorize(in_flight, required_permission="Edit").allowed:
427
+ raise PGChaosFailure("partition admitted in-flight operation")
428
+ blocked += 1
429
+
430
+ # External world effect commits, then the PG worker dies before
431
+ # local post-effect state is committed.
432
+ effect = f"payment:disaster-{seed}-{i}"
433
+ ledger = td / f"ledger-{i}.json"
434
+ rc = self._run_crash_worker(ledger, effect)
435
+ if rc != 23:
436
+ raise PGChaosFailure(f"disaster child returned {rc}")
437
+ effects = json.loads(ledger.read_text(encoding="utf-8"))["effects"]
438
+ if effects.count(effect) != 1:
439
+ raise PGChaosFailure("durable effect not exactly-once before recovery")
440
+
441
+ # Newest snapshot is corrupt, so explicitly fall through to
442
+ # the older verified generation while preserving world effects.
443
+ current = {"state": "partial-crash", "external_effect_ledger": list(effects)}
444
+ restored = None
445
+ for candidate in (corrupt, older):
446
+ rr = manager.restore_snapshot(candidate, current, safe_point="checkpoint")
447
+ if rr.status == "restored":
448
+ restored = rr
449
+ break
450
+ blocked += 1
451
+ if restored is None or restored.restored_state.get("state") != "older-safe":
452
+ raise PGChaosFailure("disaster recovery chain failed")
453
+ if list(restored.external_effects_preserved).count(effect) != 1:
454
+ raise PGChaosFailure("recovery erased or duplicated world effect")
455
+
456
+ # Heal the endpoint; the previously unused signed operation can
457
+ # be accepted once, but never twice.
458
+ org.heal_device_network("alice-dev", actor="disaster-controller")
459
+ if not org.authorize(in_flight, required_permission="Edit").allowed:
460
+ raise PGChaosFailure("healed endpoint rejected valid unused operation")
461
+ if org.authorize(in_flight, required_permission="Edit").allowed:
462
+ raise PGChaosFailure("replayed in-flight operation after heal")
463
+ blocked += 1
464
+
465
+ # The governance split resolves with exactly one writer winning.
466
+ def apply(rid: str) -> str:
467
+ try:
468
+ org.apply_change(rid, self._session(org, "operator", "ops-pc"))
469
+ return "APPLIED"
470
+ except OrgConflictError:
471
+ return "STALE"
472
+ with ThreadPoolExecutor(max_workers=2) as ex:
473
+ outcomes = list(ex.map(apply, (req_a.request_id, req_b.request_id)))
474
+ if sorted(outcomes) != ["APPLIED", "STALE"]:
475
+ raise PGChaosFailure(f"disaster authority split produced {outcomes}")
476
+ blocked += 1
477
+
478
+ if i % 8 == 0 and not org.verify_audit_chain():
479
+ raise PGChaosFailure("audit chain broke during disaster chain")
480
+ passed += 1
481
+ except Exception:
482
+ failures += 1
483
+ if org.is_device_partitioned("alice-dev"):
484
+ org.heal_device_network("alice-dev", actor="disaster-repair")
485
+ if not org.verify_audit_chain():
486
+ failures += 1
487
+ return ChaosCampaignResult(
488
+ "e2e-disaster-chain", seed, iterations, passed, blocked, failures,
489
+ (time.perf_counter() - start) * 1000,
490
+ (
491
+ "partition blocks in-flight authority while process crash occurs",
492
+ "corrupt newest snapshot falls back to older verified generation",
493
+ "committed external effect remains exactly-once across Recovery",
494
+ "healed signed operation is accepted once and replay remains blocked",
495
+ "concurrent authority mutations resolve to one APPLIED and one STALE",
496
+ ),
497
+ {"child_exit_code": 23, "audit_entries": len(org.audit), "final_revision": org.revision},
498
+ )
499
+
500
+ def run_all(
501
+ self, *, crash: int = 25, partition: int = 1000, authority: int = 100,
502
+ team: int = 100, snapshots: int = 250, compound: int = 1000, disaster: int = 10,
503
+ ) -> dict[str, Any]:
504
+ results = [
505
+ self.process_crash_recovery(iterations=crash),
506
+ self.network_partition(iterations=partition),
507
+ self.concurrent_authority_changes(iterations=authority),
508
+ self.concurrent_team_changes(iterations=team),
509
+ self.snapshot_chain(iterations=snapshots),
510
+ self.compound(iterations=compound),
511
+ self.disaster_chain(iterations=disaster),
512
+ ]
513
+ failures = sum(r.failures for r in results)
514
+ return {
515
+ "version": PG_CHAOS_VERSION,
516
+ "status": "PASS" if failures == 0 else "FAIL",
517
+ "campaigns": [r.to_dict() for r in results],
518
+ "totals": {
519
+ "iterations": sum(r.iterations for r in results),
520
+ "passed": sum(r.passed for r in results),
521
+ "safe_blocks": sum(r.safe_blocks for r in results),
522
+ "failures": failures,
523
+ "duration_ms": sum(r.duration_ms for r in results),
524
+ },
525
+ }
pg_core/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ """PG-Core 1.4 with frozen live dictionaries and typed general bridges."""
2
+
3
+ from .compiler import PGCompiler
4
+ from .bridge import PGBridgeExecutor
5
+ from .benchmark import PGBenchmark
6
+ from .dictionary import TypeDictionary
7
+ from .dispatch import DispatchPlan, PGDispatchRunner, make_plan
8
+ from .external_registry import ExternalRegistry
9
+ from .native_backend import PGNativeBuilder, PGNativeEmitter
10
+ from .native_input import PGInputPacker
11
+ from .optimizer import PGOptimizer
12
+ from .runtime import PGRuntime
13
+ from .release import release_info
14
+
15
+ __all__ = [
16
+ "ExternalRegistry",
17
+ "DispatchPlan",
18
+ "PGCompiler",
19
+ "PGBridgeExecutor",
20
+ "PGBenchmark",
21
+ "PGDispatchRunner",
22
+ "PGNativeBuilder",
23
+ "PGNativeEmitter",
24
+ "PGInputPacker",
25
+ "PGOptimizer",
26
+ "PGRuntime",
27
+ "release_info",
28
+ "make_plan",
29
+ "TypeDictionary",
30
+ ]
31
+ __version__ = "1.4.0"
pg_core/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ from .cli import main
2
+
3
+
4
+ if __name__ == "__main__":
5
+ raise SystemExit(main())
6
+