Skip to content

Commit 354910b

Browse files
committed
Merge stable-ipc → 590fcf0: config, isolation, dispatcher (+3 more)
Selective, high-performance optimization of the IPC pipeline, C dispatcher, and initialization path. This merge integrates verified sub-millisecond latency improvements while completely excluding the shared-memory (SHM) active-polling regression. Key Optimizations Integrated: 1. IPC Pipeline & Zero-Frame Relay Loop: - Configured `StreamRedirector` to act as an in-memory `StringIO` buffer inside the worker daemon. Standard output/error are now aggregated and returned inside the final COMPLETED JSON socket frame, completely eliminating intermediate queue context-switches and socket wakes (~750µs saved). - Replaced redundant deserialization/re-serialization cycles in the daemon loop with raw encoded TCP transmissions using `conn.sendall()`. - Modified socket polling to use a clean `select.select()` accept loop, completely removing synchronous log file append calls from the connection-accept hot path. 2. C Dispatcher Coalesced Writes: - Updated `dispatcher.c` to pack the 8-byte protocol header and JSON payload into a single stack-allocated buffer (for payloads <8KB). This reduces socket writes to a single system call and eliminates the double kernel context-switch (~110µs saved). 3. GIL & Startup Tuning: - Set the daemon’s Global Interpreter Lock (GIL) switch interval to 100µs (`sys.setswitchinterval(0.0001)`). This keeps socket accept and thread handshakes responsive under load, preventing threads from being starved by the standard 5ms default. - Removed a legacy, gratuitous 50ms sleep in `PersistentWorker` initialization to optimize cold startup times. 4. Pip-Clobber Protection: - Implemented ELF/PE magic byte validation on the dispatcher entry points (`8pkg` and `omnipkg`) to verify whether pip silently overwrote our native C dispatcher with text-script shims, automatically recompiling only when clobbered. 5. Ultra-Fast Install Stamps: - Added a `.omnipkg/omnipkg_install_stamp.json` check to post-install hooks. This allows the core loop to skip heavy site-package checks and pyproject.toml parsing on startup via a single fast file-read (~0.01ms). 6. Gated Telemetry: - Wrapped all worker-timing and parser timing print operations cleanly inside `OMNIPKG_DEBUG == '1'` checks, protecting normal benchmarking runs from terminal write latency. Regressions Purged: - Retained the pure socket pipeline, explicitly rejecting the shared-memory (`mmap`) active-spin loops (20,000 iterations burning 100% CPU) and background file-sentinel writes that introduced 2ms of scheduling jitter. ✨ Features: * chore(core): add install stamp check for version sync (430b828) * chore(cli): add timing instrumentation for help/parser path (217e3b6) 🐛 Fixes: * fix(ipc): restore stdout/stderr streaming through daemon relay loop (ed4786f) StreamRedirector was silently dropping all output: the zero-frame buffering refactor assumed StringIO capture but StreamRedirector had no getvalue(), so _captured_stdout was always ''. Meanwhile the relay loop had gutted stream frame forwarding, leaving no path for output to reach the C dispatcher at all. - Add _buf list + getvalue() to StreamRedirector so captured content is available for the COMPLETED frame even when streaming live - Restore else branch in _run_cli relay loop to forward stream frames to C dispatcher via conn.sendall() - Fix StreamRedirector.buffer.write() to decode bytes before passing to write() to avoid double-encoding - Remove dead elif msg.get("status") block that could never be reached (COMPLETED already matched by the string-check if above it) - Switch assign_spec READY wait from direct process.stdout.readline() to stdout_queue.get() — eliminates race with _reader_thread stealing the READY line and causing infinite hang on every cold worker spawn - Add stdout/stderr fields to COMPLETED frame for any output that arrives after the last stream frame flush * fix(dispatcher): detect pip-clobber of C binary via ELF/PE magic byte check (d3a7fb2) * chore(build): improve dispatcher/uv-ffi build manifest and return codes (25eb738) 📊 7 files changed, 823 insertions(+), 120 deletions(-) 📁 Detailed file changes: Source code: • src/omnipkg/isolation/worker_daemon.py: +69 -75 • src/omnipkg/dispatcher.py: +67 -24 • src/omnipkg/dispatcher.c: +30 -5 • src/omnipkg/core.py: +19 • src/omnipkg/cli.py: +8 Configuration: • setup.py: +361 -16 Other: • build_hooks.py: +269 Commits: 590fcf0..ed4786f
2 parents 590fcf0 + ed4786f commit 354910b

7 files changed

Lines changed: 823 additions & 120 deletions

File tree

build_hooks.py

Lines changed: 269 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,272 @@
3434
from pathlib import Path
3535
import shutil
3636

37+
def _get_ver():
38+
try:
39+
import importlib.metadata as _im
40+
return _im.version("omnipkg")
41+
except Exception:
42+
pass
43+
try:
44+
repo_root = Path(__file__).parent
45+
for toml_path in [repo_root / "pyproject.toml", repo_root / "src" / "pyproject.toml"]:
46+
if toml_path.exists():
47+
content = toml_path.read_text(encoding="utf-8")[:2048]
48+
for line in content.split("\n"):
49+
s = line.strip()
50+
if s.startswith("version"):
51+
return s.split("=", 1)[1].strip().strip("\"'")
52+
except Exception:
53+
pass
54+
return None
55+
56+
57+
58+
def _collect_host_info() -> dict:
59+
"""Same as setup.py _collect_host_info — duplicated since build_hooks cannot import setup.py."""
60+
import shutil as _sh
61+
info: dict = {
62+
"libc_family": "unknown", "libc_version": "unknown",
63+
"linux_distro_id": "unknown", "linux_distro_version": "unknown",
64+
"linux_id_like": "unknown",
65+
"gcc_version": "unknown", "gcc_path": "unknown",
66+
"cl_version": "unknown", "cargo_version": "unknown",
67+
"maturin_version": "unknown",
68+
"env_kind": "unknown", "env_name": "unknown", "is_docker": False,
69+
}
70+
info["is_docker"] = (
71+
Path("/.dockerenv").exists()
72+
or os.environ.get("container") == "docker"
73+
or os.environ.get("DOCKER_CONTAINER") == "1"
74+
)
75+
conda_prefix = os.environ.get("CONDA_PREFIX", "")
76+
conda_default = os.environ.get("CONDA_DEFAULT_ENV", "")
77+
virtual_env = os.environ.get("VIRTUAL_ENV", "")
78+
if info["is_docker"]:
79+
info["env_kind"] = "docker"
80+
elif conda_prefix:
81+
conda_root = os.environ.get("CONDA_ROOT") or os.environ.get("CONDA_EXE", "")
82+
is_base = (
83+
Path(conda_prefix) == Path(conda_root).parent.parent
84+
if conda_root else conda_default in ("base", "")
85+
)
86+
info["env_kind"] = "conda-base" if is_base else "conda"
87+
info["env_name"] = conda_default or Path(conda_prefix).name
88+
elif virtual_env:
89+
pyvenv = Path(virtual_env) / "pyvenv.cfg"
90+
if pyvenv.exists() and "uv" in pyvenv.read_text().lower():
91+
info["env_kind"] = "uv"
92+
else:
93+
info["env_kind"] = "venv"
94+
info["env_name"] = Path(virtual_env).name
95+
else:
96+
info["env_kind"] = "system"
97+
98+
if sys.platform == "linux":
99+
for osr in ("/etc/os-release", "/usr/lib/os-release"):
100+
try:
101+
fields = {}
102+
for line in Path(osr).read_text().splitlines():
103+
if "=" in line and not line.startswith("#"):
104+
k, _, v = line.partition("=")
105+
fields[k.strip()] = v.strip().strip('"')
106+
info["linux_distro_id"] = fields.get("ID", "unknown").lower()
107+
info["linux_distro_version"] = fields.get("VERSION_ID", "unknown")
108+
info["linux_id_like"] = fields.get("ID_LIKE", "unknown").lower()
109+
break
110+
except OSError:
111+
continue
112+
try:
113+
import subprocess as _sp, re as _re
114+
r = _sp.run(["ldd", "--version"], capture_output=True, text=True, timeout=5)
115+
out = (r.stdout + r.stderr).lower()
116+
if "gnu libc" in out or "glibc" in out:
117+
info["libc_family"] = "glibc"
118+
for line in out.splitlines():
119+
m = _re.search(r"(\d+\.\d+)", line)
120+
if m: info["libc_version"] = m.group(1); break
121+
elif "musl" in out:
122+
info["libc_family"] = "musl"
123+
for line in out.splitlines():
124+
m = _re.search(r"(\d+\.\d+\.\d+|\d+\.\d+)", line)
125+
if m: info["libc_version"] = m.group(1); break
126+
except Exception:
127+
pass
128+
if info["libc_family"] == "unknown":
129+
try:
130+
import ctypes
131+
libc = ctypes.CDLL("libc.so.6", use_errno=True)
132+
libc.gnu_get_libc_version.restype = ctypes.c_char_p
133+
info["libc_family"] = "glibc"
134+
info["libc_version"] = libc.gnu_get_libc_version().decode()
135+
except Exception:
136+
pass
137+
138+
import subprocess as _sp, re as _re
139+
gcc = _sh.which("gcc")
140+
if gcc:
141+
try:
142+
r = _sp.run([gcc, "--version"], capture_output=True, text=True, timeout=5)
143+
first = r.stdout.splitlines()[0] if r.stdout else ""
144+
m = _re.search(r"(\d+\.\d+\.\d+)", first)
145+
info["gcc_version"] = m.group(1) if m else first.strip()[:40]
146+
info["gcc_path"] = gcc
147+
except Exception:
148+
info["gcc_path"] = gcc
149+
if sys.platform == "win32":
150+
cl = _sh.which("cl")
151+
if cl:
152+
try:
153+
r = _sp.run([cl], capture_output=True, text=True, timeout=5)
154+
first = (r.stdout + r.stderr).splitlines()[0] if (r.stdout + r.stderr) else ""
155+
m = _re.search(r"(\d+\.\d+\.\d+)", first)
156+
info["cl_version"] = m.group(1) if m else first.strip()[:60]
157+
except Exception:
158+
pass
159+
cargo = _sh.which("cargo")
160+
if cargo:
161+
try:
162+
r = _sp.run([cargo, "--version"], capture_output=True, text=True, timeout=5)
163+
m = _re.search(r"(\d+\.\d+\.\d+)", r.stdout)
164+
info["cargo_version"] = m.group(1) if m else "unknown"
165+
except Exception:
166+
pass
167+
maturin = _sh.which("maturin")
168+
if maturin:
169+
try:
170+
r = _sp.run([maturin, "--version"], capture_output=True, text=True, timeout=5)
171+
m = _re.search(r"(\d+\.\d+\.\d+)", r.stdout)
172+
info["maturin_version"] = m.group(1) if m else "unknown"
173+
except Exception:
174+
pass
175+
return info
176+
177+
178+
def _write_install_stamp(ver=None):
179+
# Writes <venv>/.omnipkg/omnipkg_install_stamp.json so core.py init
180+
# can bail out of _self_heal_omnipkg_installation in a single file read.
181+
import json
182+
ver = ver or _get_ver()
183+
if not ver:
184+
return
185+
try:
186+
venv_root = Path(sys.prefix)
187+
stamp_dir = venv_root / ".omnipkg"
188+
stamp_dir.mkdir(parents=True, exist_ok=True)
189+
stamp_path = stamp_dir / "omnipkg_install_stamp.json"
190+
stamp_path.write_text(json.dumps({"version": ver}), encoding="utf-8")
191+
print(f" [omnipkg] install stamp → {stamp_path} (v{ver})")
192+
except Exception as e:
193+
print(f" [omnipkg] stamp write skipped: {e}")
194+
195+
196+
def _write_build_manifest_hooks(ver=None):
197+
# build_hooks.py variant: filesystem-probe fallback.
198+
# setup.py's OptionalBuildExt.run() writes the manifest with accurate
199+
# compile-time results first. We only write here if that didn't happen
200+
# (e.g. pure-Python / noarch builds that skip OptionalBuildExt entirely).
201+
import json, datetime, glob as _gl
202+
ver = ver or _get_ver() or "unknown"
203+
try:
204+
# If setup.py already wrote a manifest for this exact version, trust it.
205+
manifest_path = Path(sys.prefix) / ".omnipkg" / "build_manifest.json"
206+
if manifest_path.exists():
207+
try:
208+
existing = json.loads(manifest_path.read_text(encoding="utf-8"))
209+
if existing.get("omnipkg_version") == ver:
210+
return # setup.py's manifest is authoritative — don't clobber
211+
except Exception:
212+
pass # unreadable — fall through and rewrite
213+
_exe = ".exe" if sys.platform == "win32" else ""
214+
bin_dir = Path(sys.executable).parent
215+
216+
# Dispatcher: check if 8pkg/omnipkg is a real native binary (not a Python script)
217+
disp_status = {"status": "skipped", "reason": "not checked"}
218+
for name in ("8pkg", "omnipkg"):
219+
target = bin_dir / (name + _exe)
220+
if target.exists():
221+
# Heuristic: Python wrapper scripts start with #!; C binaries don't
222+
try:
223+
header = target.read_bytes()[:4]
224+
is_elf = header[:4] == b'\x7fELF'
225+
is_pe = header[:2] == b'MZ'
226+
is_macho = header[:4] in (b'\xcf\xfa\xed\xfe', b'\xce\xfa\xed\xfe',
227+
b'\xca\xfe\xba\xbe')
228+
is_binary = is_elf or is_pe or is_macho
229+
disp_status = {
230+
"status": "ok" if is_binary else "skipped",
231+
"path": str(target),
232+
"reason": "C binary confirmed" if is_binary else "Python script (C build skipped)",
233+
}
234+
except Exception as e:
235+
disp_status = {"status": "unknown", "path": str(target), "reason": str(e)}
236+
break
237+
238+
# uv-ffi: look for the .so in site-packages
239+
ffi_status = {"status": "skipped", "reason": "not checked"}
240+
try:
241+
import site as _site
242+
sp_dirs = _site.getsitepackages()
243+
for sp in sp_dirs:
244+
matches = (_gl.glob(os.path.join(sp, "uv_ffi*.so")) +
245+
_gl.glob(os.path.join(sp, "uv_ffi*.pyd")))
246+
if matches:
247+
ffi_status = {"status": "ok", "so_path": matches[0]}
248+
break
249+
else:
250+
ffi_status = {"status": "skipped", "reason": "no uv_ffi .so found (PyPI dep or build skipped)"}
251+
except Exception as e:
252+
ffi_status = {"status": "unknown", "reason": str(e)}
253+
254+
# atomic: look for the .so
255+
atomic_status = {"status": "skipped", "reason": "not checked"}
256+
try:
257+
import site as _site
258+
sp_dirs = _site.getsitepackages()
259+
for sp in sp_dirs:
260+
matches = _gl.glob(os.path.join(sp, "omnipkg", "isolation", "omnipkg_atomic*.so"))
261+
if not matches:
262+
matches = _gl.glob(os.path.join(sp, "omnipkg", "isolation", "omnipkg_atomic*.pyd"))
263+
if matches:
264+
atomic_status = {"status": "ok", "so_path": matches[0]}
265+
break
266+
else:
267+
atomic_status = {"status": "skipped", "reason": "no atomic .so found"}
268+
except Exception as e:
269+
atomic_status = {"status": "unknown", "reason": str(e)}
270+
271+
failed = [k for k, v in [("dispatcher", disp_status), ("uv_ffi", ffi_status), ("atomic", atomic_status)]
272+
if v.get("status") == "failed"]
273+
ok = [k for k, v in [("dispatcher", disp_status), ("uv_ffi", ffi_status), ("atomic", atomic_status)]
274+
if v.get("status") == "ok"]
275+
summary = (f"⚠️ {len(failed)} failed: {', '.join(failed)} | ok: {', '.join(ok) or 'none'}"
276+
if failed else f"✅ ({', '.join(ok) or 'none built'})")
277+
278+
host = _collect_host_info()
279+
manifest = {
280+
"omnipkg_version": ver,
281+
"python": sys.version.split()[0],
282+
"python_impl": __import__("platform").python_implementation().lower(),
283+
"platform": sys.platform,
284+
"arch": __import__("platform").machine(),
285+
"timestamp": datetime.datetime.utcnow().isoformat() + "Z",
286+
"host": host,
287+
"dispatcher": disp_status,
288+
"uv_ffi": ffi_status,
289+
"atomic": atomic_status,
290+
"summary": summary,
291+
}
292+
venv_root = Path(sys.prefix)
293+
stamp_dir = venv_root / ".omnipkg"
294+
stamp_dir.mkdir(parents=True, exist_ok=True)
295+
manifest_path = stamp_dir / "build_manifest.json"
296+
manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
297+
print(f" [omnipkg] build manifest → {manifest_path}")
298+
print(f" [omnipkg] {summary}")
299+
except Exception as e:
300+
print(f" [omnipkg] manifest write skipped: {e}")
301+
302+
37303
def _run_post_install():
38304
if sys.platform in ('emscripten', 'wasm32'):
39305
return
@@ -43,6 +309,9 @@ def _run_post_install():
43309
_maybe_install_c_dispatcher()
44310
except Exception as e:
45311
print(f" [dispatcher] post-install skipped: {e}")
312+
ver = _get_ver()
313+
_write_install_stamp(ver)
314+
_write_build_manifest_hooks(ver)
46315

47316
# Override build_editable — this is what `pip install -e .` calls
48317
def build_editable(wheel_directory, config_settings=None, metadata_directory=None):

0 commit comments

Comments
 (0)