Skip to content

Commit 2ae5956

Browse files
committed
merge: interactive hunk-by-hunk port stash-ipc-work → stable-ipc
Merged via hunk_merger — 47 hunks reviewed across 2 file(s): 14 taken · 25 kept ours · 8 edited · 0 skipped Per-file decisions: src/omnipkg/dispatcher.c: +1 taken, 13 kept src/omnipkg/isolation/worker_daemon.py: +13 taken, 12 kept, 8 edited Staged: 2 files changed, 66 insertions(+), 43 deletions(-) Source branch : stash-ipc-work Target branch : stable-ipc Session date : 2026-05-30 02:12:11 [gitship-hunk-merger]
1 parent d3a7fb2 commit 2ae5956

2 files changed

Lines changed: 66 additions & 43 deletions

File tree

src/omnipkg/dispatcher.c

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -629,10 +629,28 @@ static int send_json_msg(int sock, const char *json_str) {
629629
uint64_t len = (uint64_t)strlen(json_str);
630630
uint8_t be_len[8];
631631
for (int i = 0; i < 8; i++)
632-
be_len[7 - i] = (uint8_t)((len >> (i * 8)) & 0xFF);
633-
if (!write_all(sock, be_len, 8)) return 0;
634-
if (!write_all(sock, json_str, (size_t)len)) return 0;
635-
return 1;
632+
* This eliminates the double kernel wake-up that was costing ~110us:
633+
* Python would wake on the 8-byte header, block waiting for the payload,
634+
* OS context-switched back to C, C sent payload, switched back to Python.
635+
* A single write lets the kernel deliver everything in one shot. */
636+
if (len < 8192) {
637+
/* Hot path: stack-allocated, zero heap pressure */
638+
uint8_t buf[8192 + 8];
639+
for (int i = 0; i < 8; i++)
640+
buf[7 - i] = (uint8_t)((len >> (i * 8)) & 0xFF);
641+
memcpy(buf + 8, json_str, (size_t)len);
642+
return write_all(sock, buf, (size_t)(len + 8));
643+
}
644+
645+
/* Cold path: large payload (rare — run_cli argv is almost always < 8KB) */
646+
uint8_t *buf = (uint8_t *)malloc((size_t)(len + 8));
647+
if (!buf) return 0;
648+
for (int i = 0; i < 8; i++)
649+
buf[7 - i] = (uint8_t)((len >> (i * 8)) & 0xFF);
650+
memcpy(buf + 8, json_str, (size_t)len);
651+
int ok = write_all(sock, buf, (size_t)(len + 8));
652+
free(buf);
653+
return ok;
636654
}
637655

638656
static char* recv_json_msg(int sock) {

src/omnipkg/isolation/worker_daemon.py

Lines changed: 44 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -4050,10 +4050,16 @@ def _run_cli(self, req, conn):
40504050
pass
40514051

40524052
_t_ready = _rt.perf_counter()
4053-
safe_print(f"[RUN-CLI] ready_line={repr(ready_line)} ({(_t_ready-_t_got_worker)*1000:.2f}ms)", file=sys.stderr)
4053+
if os.environ.get('OMNIPKG_DEBUG') == '1':
4054+
_elapsed_us = int((_t_ready - locals().get('_t_post_flush', _t_ready)) * 1000000)
4055+
safe_print(f"[RUN-CLI-T] queue.get READY={_elapsed_us}us drained={_drain_count} line={repr(ready_line)}", file=sys.stderr)
4056+
4057+
_t_first_frame = None
4058+
_frame_count = 0
40544059

40554060
if ready_parsed is None:
4056-
safe_print(f"[RUN-CLI] worker READY timeout - subprocess fallback", file=sys.stderr)
4061+
if os.environ.get('OMNIPKG_DEBUG') == '1':
4062+
safe_print(f"[RUN-CLI] worker READY timeout - subprocess fallback", file=sys.stderr)
40574063
worker.force_shutdown()
40584064
try:
40594065
_fb_python = req.get("python_exe") or sys.executable
@@ -4079,13 +4085,16 @@ def _run_cli(self, req, conn):
40794085
send_json(conn, {"status": "ERROR", "error": str(_fb_err), "exit_code": 1})
40804086
return
40814087

4088+
# ── Zero-frame relay loop ─────────────────────────────────────────
4089+
# Worker now captures stdout/stderr into StringIO and embeds them
4090+
# in the single COMPLETED frame. No stream frames are emitted.
4091+
# This eliminates ~750us of queue-wake overhead (was 5x ~150us).
4092+
#
4093+
# Protocol: worker sends exactly two frames: READY then COMPLETED.
4094+
# NEEDS_INPUT still works: worker sends NEEDS_INPUT mid-execution
4095+
# (only for interactive commands), we relay it, then loop back.
40824096
while True:
40834097
try:
4084-
# Use a short poll interval so we remain responsive.
4085-
# safe_input() in the worker blocks until it gets a
4086-
# stdin_line reply, so there's no busy-spin here -
4087-
# the worker simply won't produce output until we
4088-
# send the reply.
40894098
line = worker.stdout_queue.get(timeout=86400.0)
40904099
except queue.Empty:
40914100
break
@@ -4096,49 +4105,44 @@ def _run_cli(self, req, conn):
40964105
msg = json.loads(line)
40974106

40984107
# stdout / stderr stream - forward to C dispatcher
4099-
if msg.get("stream"):
4108+
if '"status": "COMPLETED"' in line or '"status": "SHM_COMPLETED"' in line or '"status": "ERROR"' in line:
4109+
_t_completed = _rt.perf_counter()
4110+
_completed_cleanly = ('"status": "COMPLETED"' in line) or ('"status": "SHM_COMPLETED"' in line)
41004111
try:
4101-
send_json(conn, msg)
4112+
worker._last_result = json.loads(line)
4113+
except Exception as _parse_err:
4114+
if os.environ.get('OMNIPKG_DEBUG') == '1':
4115+
safe_print(f"[RUN-CLI] terminal frame parse failed: {_parse_err!r} line={line[:120]!r}", file=sys.stderr)
4116+
4117+
raw = line.encode("utf-8")
4118+
try:
4119+
conn.sendall(len(raw).to_bytes(8, "big") + raw)
41024120
except Exception:
4103-
break
4121+
pass
4122+
4123+
if os.environ.get('OMNIPKG_DEBUG') == '1':
4124+
safe_print(f"[RUN-CLI] COMPLETED in {(_t_completed-_t0)*1000:.2f}ms total frames={_frame_count}", file=sys.stderr)
4125+
break
41044126

4105-
# NEEDS_INPUT - relay prompt to C dispatcher, wait for
4106-
# the user's reply, then send it back to the worker
4107-
elif msg.get("status") == "NEEDS_INPUT":
4127+
elif '"status": "NEEDS_INPUT"' in line:
4128+
# Interactive command — relay prompt, read reply, loop
41084129
try:
4109-
# 1. Forward the NEEDS_INPUT frame to the C dispatcher.
4110-
# It will print the prompt on the real terminal and
4111-
# send back {"type":"stdin_line","data":"<text>"}.
4112-
send_json(conn, msg)
4113-
4114-
# 2. Wait for the stdin_line reply from the C dispatcher.
4115-
# We read directly from conn (the socket) here.
4116-
# recv_json() must be your existing framed-read helper.
4117-
reply = recv_json(conn) # blocks until dispatcher replies
4118-
4130+
msg_ni = json.loads(line)
4131+
send_json(conn, msg_ni)
4132+
reply = recv_json(conn)
41194133
if reply and reply.get("type") == "stdin_line":
4120-
# 3. Forward the user's input to the worker over its stdin.
41214134
worker.process.stdin.write(json.dumps(reply) + "\n")
4122-
worker.process.stdin.flush()
41234135
else:
4124-
# Unexpected reply or closed conn - send empty line
4125-
# so the worker doesn't hang forever.
4126-
worker.process.stdin.write(
4127-
json.dumps({"type": "stdin_line", "data": ""}) + "\n"
4128-
)
4129-
worker.process.stdin.flush()
4136+
worker.process.stdin.write('{"type": "stdin_line", "data": ""}\\n')
4137+
worker.process.stdin.flush()
41304138
except Exception as _ni_err:
4131-
safe_print(f"[RUN-CLI] NEEDS_INPUT relay failed: {_ni_err}", file=sys.stderr)
4132-
# Send empty line - worker returns default and continues.
4139+
if os.environ.get('OMNIPKG_DEBUG') == '1':
4140+
safe_print(f"[RUN-CLI] NEEDS_INPUT relay failed: {_ni_err}", file=sys.stderr)
41334141
try:
4134-
worker.process.stdin.write(
4135-
json.dumps({"type": "stdin_line", "data": ""}) + "\n"
4136-
)
4142+
worker.process.stdin.write('{"type": "stdin_line", "data": ""}\\n')
41374143
worker.process.stdin.flush()
41384144
except Exception:
41394145
break
4140-
# Continue the loop - worker resumes and will send more output.
4141-
41424146
# COMPLETED / ERROR - forward and finish
41434147
elif msg.get("status") in ("COMPLETED", "ERROR"):
41444148
_t_completed = _rt.perf_counter()
@@ -4721,7 +4725,7 @@ def _execute_code(
47214725
with self.pool_lock:
47224726
self.workers[worker_key] = {
47234727
"worker": worker,
4724-
"pinned": pin,
4728+
"pinned": pin,
47254729
"created": time.time(),
47264730
"last_used": time.time(),
47274731
"request_count": 0,
@@ -7517,6 +7521,7 @@ def cli_idle_config(python_version: str = None, count: int = None):
75177521
#
75187522

75197523
if __name__ == "__main__":
7524+
sys.setswitchinterval(0.0001) # 100us GIL slice: 39 threads, was 5ms default
75207525
# CRITICAL: Check if we're a daemon child on Windows FIRST
75217526
if IS_WINDOWS and os.environ.get("OMNIPKG_DAEMON_CHILD") == "1":
75227527
try:

0 commit comments

Comments
 (0)