feat: add per-project native server and SSE command streaming
build / jvm (push) Waiting to run
build / native (macos-15, macos-arm64) (push) Waiting to run
build / native (ubuntu-24.04, linux-x86_64) (push) Waiting to run
build / native (windows-2025, windows-x86_64) (push) Waiting to run
Test / Tests and coverage
Intrepid/AI Engineering/pipeline/head This commit looks good

Keep Spring in a persistent project server with lightweight clients, managed start/stop, bounded SSE subscriptions, cursor recovery and durable mutation outcomes. Preserve SQLite authority and transaction limits, and document reproducible native measurements.

Validation: 269 tests, 11 pipeline scenarios, full native/SSE smoke, native package verification and 17 installer tests passed. Implements WRK-000E / DEC-0001 / DEC-0002.
This commit is contained in:
2026-11-22 23:08:47 +00:00
parent 20bb4f02bc
commit 9a555cb3c6
64 changed files with 5062 additions and 29 deletions
+266
View File
@@ -0,0 +1,266 @@
#!/usr/bin/env python3
"""Exercise real native survey jobs over SSE in a disposable project; optionally measure the workload."""
import argparse
import concurrent.futures
import hashlib
import http.client
import json
from pathlib import Path
import platform
import re
import shutil
import statistics
import subprocess
import tempfile
import threading
import time
import uuid
def distribution(samples):
ordered = sorted(samples)
import math
return {"samples": len(samples), "p50Ms": statistics.median(samples),
"p95Ms": ordered[math.ceil(len(samples) * .95) - 1], "maxMs": ordered[-1], "rawMs": samples}
def read_event(response):
data, cursor, kind, size = [], None, None, 0
while True:
line = response.readline(128 * 1024 * 1024 + 1)
if not line:
raise RuntimeError("SSE ended before terminal notification")
size += len(line)
if size > 128 * 1024 * 1024:
raise RuntimeError("SSE frame exceeds limit")
line = line.decode("utf-8").rstrip("\r\n")
if not line:
if not data:
size = 0
continue
event = json.loads("\n".join(data))
if event["cursor"] != cursor or event["kind"] != kind:
raise RuntimeError("SSE frame identity mismatch")
return event
if line.startswith(":"):
continue
field, _, value = line.partition(":")
if value.startswith(" "):
value = value[1:]
if field == "id":
cursor = value
elif field == "event":
kind = value
elif field == "data":
data.append(value)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", required=True, type=Path)
parser.add_argument("--samples", type=int, default=20)
parser.add_argument("--questions", type=int, default=3)
parser.add_argument("--streams", type=int, default=4)
parser.add_argument("--fixture", type=Path)
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if args.samples < 1 or args.questions < 1 or not 1 <= args.streams <= 4:
parser.error("Use positive samples/questions and 1..4 streams")
binary = args.binary.resolve(strict=True)
with tempfile.TemporaryDirectory(prefix="aie-native-sse-") as temporary:
root = Path(temporary).resolve()
def cli(*command, directory=root):
result = subprocess.run([str(binary), *command], cwd=directory, text=True, capture_output=True, timeout=60)
if result.returncode:
raise RuntimeError("Native CLI failed: " + " ".join(command) + ": " + result.stderr)
return result.stdout
gate, ready = threading.Event(), [threading.Event() for _ in range(args.streams)]
ids = []
report = {"platform": platform.platform(), "binarySha256": hashlib.sha256(binary.read_bytes()).hexdigest(),
"buildIdentity": json.loads((binary.parent / "aie-package.json").read_text())["buildIdentity"],
"method": "Input POST start to first subsequent stdout/input/terminal SSE event, including command work and control response; no human think time.",
"concurrentStreams": args.streams, "questionsPerStream": args.questions}
try:
if args.fixture:
source = args.fixture.resolve(strict=True)
if json.loads(cli("server", "status", directory=source))["state"] != "STOPPED":
raise RuntimeError("Stop the synthetic fixture before copying")
shutil.copytree(source, root, dirs_exist_ok=True, ignore=shutil.ignore_patterns(".local"))
report["fixture"] = json.loads((root / "latency-fixture.json").read_text())
query_work = "WRK-0064"
else:
cli("init", "--name", "Disposable native SSE verification")
cli("work", "create", "Synthetic SSE workload")
query_work = "WRK-0001"
work = "WRK-0001"
def survey(count):
text = cli("survey", "create", work, "--title", "Synthetic SSE questions", "--author", "native-sse-fixture")
selected = re.search(r'\bid: "(SVY-\d+)"', text).group(1)
for index in range(count):
cli("survey", "question", work, selected, "--text", "Question " + str(index + 1) + " café 😀",
"--option", "One", "--option", "Two", "--author", "native-sse-fixture")
return selected
surveys = [survey(args.questions) for _ in range(args.streams)]
endpoint = json.loads((root / ".ai-engineering/.local/server/endpoint.json").read_text())
headers = {"Authorization": "Bearer " + endpoint["token"], "X-AIE-Instance": endpoint["instance"],
"X-AIE-Protocol": "1", "Content-Type": "application/json"}
def rpc(method, path, body=None):
connection = http.client.HTTPConnection("127.0.0.1", endpoint["port"], timeout=10)
try:
connection.request(method, path, body=None if body is None else json.dumps(body).encode(), headers=headers)
response = connection.getresponse()
payload = response.read()
if response.status != 200:
raise RuntimeError("Native RPC failed: " + path + " HTTP " + str(response.status))
return json.loads(payload)
finally:
connection.close()
def submit(selected):
request_id = str(uuid.uuid4())
view = rpc("POST", "/execute", {"id": request_id, "project": str(root), "cwd": str(root),
"argv": ["survey", "ask", work, selected, "--author", "native-sse-fixture"], "interactive": True})
if view["state"] in ("COMPLETED", "UNKNOWN"):
raise RuntimeError("Interactive job finished before input")
return request_id
def subscribe(request_id, cursor=None):
connection = http.client.HTTPConnection("127.0.0.1", endpoint["port"], timeout=10)
fields = dict(headers, Accept="text/event-stream")
if cursor:
fields["Last-Event-ID"] = cursor
connection.request("GET", "/requests/" + request_id + "/events", headers=fields)
response = connection.getresponse()
if response.status != 200 or not response.getheader("Content-Type", "").startswith("text/event-stream"):
connection.close()
raise RuntimeError("Native SSE subscription failed")
return connection, response
def monitor(index, request_id):
connection, response = subscribe(request_id)
output = {"stdout": b"", "stderr": b""}
answered, latencies, events, pending = 0, [], 0, None
try:
while True:
event = read_event(response)
if event["id"] != request_id:
raise RuntimeError("Cross-request SSE output")
events += 1
for stream in output:
text = event[stream].encode("utf-16-le", errors="surrogatepass")
offset = event[stream + "Offset"] * 2
old = output[stream]
if offset > len(old) or (event["kind"] == "snapshot" and len(text) < len(old)):
raise RuntimeError("Native SSE output gap")
overlap = min(len(old) - offset, len(text))
if old[offset:offset + overlap] != text[:overlap]:
raise RuntimeError("Native SSE output prefix changed")
output[stream] += text[overlap:]
if pending is not None and event["kind"] in ("stdout", "stderr", "input-required", "completed", "snapshot"):
latencies.append((time.perf_counter_ns() - pending) / 1_000_000)
pending = None
if event["state"] in ("COMPLETED", "UNKNOWN"):
if event["state"] != "COMPLETED" or event["exitCode"] != 0:
raise RuntimeError("Native SSE job failed: " + event["state"] + " exit=" + str(event["exitCode"])
+ " stderr=" + output["stderr"].decode("utf-16-le", errors="replace")[-2000:])
break
if event["needsInput"] and event["inputSequence"] > answered:
ready[index].set()
if not gate.wait(60):
raise RuntimeError("SSE benchmark gate timed out")
answered = event["inputSequence"]
pending = time.perf_counter_ns()
rpc("POST", "/input", {"id": request_id, "sequence": answered, "text": "1\n"})
if answered != args.questions or len(latencies) != args.questions:
raise RuntimeError("Native SSE input/event count mismatch")
if "café 😀" not in output["stdout"].decode("utf-16-le"):
raise RuntimeError("Native SSE Unicode prompt was not preserved")
saved = rpc("GET", "/requests/" + request_id)
for stream in output:
if output[stream].decode("utf-16-le") != saved[stream]:
raise RuntimeError("SSE output differs from durable result")
connection.close()
resumed, terminal = subscribe(request_id, event["cursor"])
try:
snapshot = read_event(terminal)
if snapshot["kind"] != "snapshot" or snapshot["state"] != "COMPLETED" or snapshot["stdout"] != saved["stdout"]:
raise RuntimeError("Late native SSE result recovery failed")
finally:
resumed.close()
return {"events": events, "inputToEventMs": latencies,
"stdoutSha256": hashlib.sha256(output["stdout"]).hexdigest()}
finally:
connection.close()
for selected in surveys:
ids.append(submit(selected))
with concurrent.futures.ThreadPoolExecutor(max_workers=args.streams) as workers:
futures = [workers.submit(monitor, index, selected) for index, selected in enumerate(ids)]
try:
for index, signal in enumerate(ready):
if not signal.wait(15):
if futures[index].done():
futures[index].result()
raise RuntimeError("Native SSE did not request input")
times = []
for _ in range(5):
cli("work", "show", query_work, "--format", "json")
for _ in range(args.samples):
before = time.perf_counter_ns()
value = json.loads(cli("work", "show", query_work, "--format", "json"))
times.append((time.perf_counter_ns() - before) / 1_000_000)
if value["id"] != query_work:
raise RuntimeError("Query failed while SSE streams were active")
report["queriesWithStreams"] = distribution(times)
rss = int(subprocess.check_output(["/bin/ps", "-o", "rss=", "-p", str(endpoint["pid"])], text=True).strip())
report["rssWithStreamsMiB"] = rss / 1024
finally:
gate.set()
report["jobs"] = [future.result(timeout=60) for future in futures]
report["inputToEvent"] = distribution([sample for job in report["jobs"] for sample in job["inputToEventMs"]])
cancelled_id = submit(survey(1))
ids.append(cancelled_id)
connection, response = subscribe(cancelled_id)
try:
while not read_event(response)["needsInput"]:
pass
rpc("POST", "/cancel", {"id": cancelled_id})
while True:
event = read_event(response)
if event["state"] in ("COMPLETED", "UNKNOWN"):
if event["state"] != "COMPLETED" or event["exitCode"] == 0 or not event["cancellationRequested"]:
raise RuntimeError("Native SSE cancellation result invalid")
report["cancellationVerified"] = True
break
finally:
connection.close()
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2) + "\n")
print("Native SSE smoke passed: streaming, Unicode, input, concurrency, terminal recovery and cancellation.")
except BaseException as failure:
report["failure"] = str(failure)
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2) + "\n")
raise
finally:
gate.set()
if "rpc" in locals():
for request_id in ids:
try:
rpc("POST", "/cancel", {"id": request_id})
except Exception:
pass # Cleanup still attempts the ordinary bounded stop below.
if (root / ".ai-engineering").exists():
cli("stop", "--timeout-seconds", "10")
if __name__ == "__main__":
main()