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
+3 -1
View File
@@ -8,5 +8,7 @@ package = Path(sys.argv[1]).resolve()
files = {str(path.relative_to(package)): hashlib.sha256(path.read_bytes()).hexdigest()
for path in sorted(package.rglob("*")) if path.is_file() and path.name != "aie-package.json"}
manifest = {"schemaVersion": 1, "aieVersion": "0.1.0", "protocolVersion": 4,
"sqliteVersion": "3.54.1", "files": files}
"sqliteVersion": "3.54.1", "localServerProtocol": 1, "localServerEvents": "sse",
"buildIdentity": (Path(__file__).resolve().parents[1] / "build/generated/serverIdentity/aie-build.txt").read_text().strip(),
"files": files}
(package / "aie-package.json").write_text(json.dumps(manifest, indent=2) + "\n")
+11 -2
View File
@@ -5,7 +5,12 @@ set -euo pipefail
aie_binary=${1:?Usage: native-smoke.sh /absolute/path/to/ai-engineering}
aie_source_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)
aie_fixture=$(mktemp -d "${TMPDIR:-/tmp}/ai-engineering-smoke.XXXXXX")
if [[ "${AIE_KEEP_FIXTURE:-0}" != 1 ]]; then trap 'rm -rf "$aie_fixture"' EXIT; fi
source "$aie_source_root/scripts/stop-fixture-servers.sh"
cleanup_native_fixture() {
stop_fixture_servers "$aie_fixture" "$aie_binary" || return 1
if [[ "${AIE_KEEP_FIXTURE:-0}" != 1 ]]; then rm -rf "$aie_fixture"; fi
}
trap cleanup_native_fixture EXIT
cd "$aie_fixture"
"$aie_binary" --help > help.txt
@@ -305,6 +310,8 @@ while [ "$#" -gt 0 ]; do
shift
done
while IFS= read -r line; do :; done
# Make the synthetic provider pending long enough to exercise the native SSE client.
/bin/sleep 0.2
classification=0
case "$provider" in
codex) while IFS= read -r line; do case "$line" in *'"activity"'*) classification=1;; esac; done < "$schema";;
@@ -331,7 +338,8 @@ aie_without_git agent doctor --format json > doctor.json
grep -q '"compatible" : true' doctor.json
aie_without_git work create --mode DIRECT --approval WAIVED --human-approved --choice-reason "Explicit synthetic fixture policy" 'Provider protocol' > work.yaml
aie_without_git discussion add WRK-0001 --text 'Synthetic source for provider protocol tests' > source.md
aie_without_git agent run WRK-0001 --task 'Summarize the synthetic note' --request-id classified --format json > codex.json
aie_without_git agent run WRK-0001 --task 'Summarize the synthetic note' --request-id classified --format json > codex.json 2> codex.stderr
grep -q '(SSE)' codex.stderr
grep -q '"classification" : {' codex.json
aie_without_git agent run WRK-0001 --activity analyze --task 'Continue from persisted context' --request-id reviewed --format json > claude.json
grep -q '"transport" : "claude-cli"' claude.json
@@ -627,3 +635,4 @@ if [[ "${AIE_KEEP_FIXTURE:-0}" == 1 ]]; then echo "Fixture retained: $aie_fixtur
# Exercise the default SQLite backend, gates and migration separately from legacy fixtures.
bash "$aie_source_root/scripts/native-sqlite-smoke.sh" "$aie_binary"
python3 "$aie_source_root/scripts/native-sse-smoke.py" --binary "$aie_binary"
+6 -1
View File
@@ -3,7 +3,12 @@ set -euo pipefail
binary=${1:?Usage: native-sqlite-smoke.sh /absolute/package/ai-engineering}
source_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)
fixture=$(mktemp -d "${TMPDIR:-/tmp}/aie-sqlite-smoke.XXXXXXXX")
trap 'rm -rf "$fixture"' EXIT
source "$source_root/scripts/stop-fixture-servers.sh"
cleanup_sqlite_fixture() {
stop_fixture_servers "$fixture" "$binary" || return 1
rm -rf "$fixture"
}
trap cleanup_sqlite_fixture EXIT
mkdir "$fixture/local"
cd "$fixture/local"
run() { PATH="$fixture/no-tools" "$binary" "$@"; }
+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()
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Measure disposable native clients/servers; never install or alter a real project."""
import argparse
import datetime
import hashlib
import json
import math
import os
from pathlib import Path
import platform
import shutil
import statistics
import subprocess
import sys
import time
def distribution(samples):
ordered = sorted(samples)
return {"samples": len(samples), "minMs": ordered[0], "p50Ms": statistics.median(samples),
"p95Ms": ordered[math.ceil(len(samples) * .95) - 1], "maxMs": ordered[-1], "rawMs": samples}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", type=Path, required=True)
parser.add_argument("--baseline", type=Path, required=True)
parser.add_argument("--directory", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--samples", type=int, default=100)
parser.add_argument("--starts", type=int, default=10)
parser.add_argument("--fixture", type=Path, help="Copy a previously generated, stopped synthetic fixture into the new directory.")
parser.add_argument("--server-baseline", type=Path, help="Also compare a preserved server package, such as the pre-SSE build.")
args = parser.parse_args()
if args.samples < 20 or args.starts < 5:
parser.error("Use at least 20 samples and 5 starts")
binary, baseline = args.binary.resolve(strict=True), args.baseline.resolve(strict=True)
root = args.directory.absolute()
root.mkdir(parents=True, exist_ok=False)
dataset = root / "nominal"
roots = [dataset]
def run(directory, *command, executable=binary):
before = time.perf_counter_ns()
result = subprocess.run([str(executable), *command], cwd=directory, text=True,
capture_output=True, timeout=60)
elapsed = (time.perf_counter_ns() - before) / 1_000_000
if result.returncode:
raise RuntimeError(f"{command}: exit {result.returncode}: {result.stderr}")
return result.stdout, elapsed
def stop(directory):
if (directory / ".ai-engineering").exists():
run(directory, "stop", "--timeout-seconds", "10")
report = {"observedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"environment": {"platform": platform.platform(), "machine": platform.machine(),
"logicalCpus": os.cpu_count(), "initialLoadAverage": os.getloadavg()},
"method": {"works": 100, "notesPerWork": 10, "storage": "sqlite",
"git": False, "provider": False, "freshClientPerSample": True,
"percentile": "nearest rank", "cold": "process cold; OS file caches not flushed"},
"candidate": {"path": str(binary), "sha256": hashlib.sha256(binary.read_bytes()).hexdigest(),
"package": json.loads((binary.parent / "aie-package.json").read_text())},
"baseline": {"path": str(baseline), "sha256": hashlib.sha256(baseline.read_bytes()).hexdigest()}}
if sys.platform == "darwin":
for key, name in (("cpu", "machdep.cpu.brand_string"), ("physicalMemoryBytes", "hw.memsize")):
report["environment"][key] = subprocess.check_output(["/usr/sbin/sysctl", "-n", name], text=True).strip()
try:
if args.fixture:
source = args.fixture.resolve(strict=True)
status = json.loads(run(source, "server", "status")[0])
if status["state"] != "STOPPED":
raise RuntimeError("Stop the synthetic source fixture before copying")
print("Copying the stopped synthetic dataset; operational server state excluded...", flush=True)
shutil.copytree(source, dataset, ignore=shutil.ignore_patterns(".local"))
report["method"]["copiedFixture"] = str(source)
else:
print("Generating 100 Works and 1,000 notes through the public CLI...", flush=True)
subprocess.run([sys.executable, str(Path(__file__).with_name("latency-fixture.py")),
"--binary", str(binary), "--directory", str(dataset), "--works", "100", "--entries", "10"],
check=True, stdout=subprocess.DEVNULL, timeout=1800)
report["fixture"] = json.loads((dataset / "latency-fixture.json").read_text())
if report["fixture"]["works"] != 100 or report["fixture"]["entriesPerWork"] != 10:
raise RuntimeError("Expected the nominal 100 Work / 10 note fixture")
command = ("work", "show", "WRK-0064", "--format", "json")
report["method"]["command"] = list(command)
expected = json.loads(run(dataset, *command)[0])
def sample(executable=binary):
output, milliseconds = run(dataset, *command, executable=executable)
if json.loads(output) != expected:
raise RuntimeError("Benchmark output differs between invocations/builds")
return milliseconds
print("Measuring process-cold readiness and automatic first use...", flush=True)
starts, first = [], []
for _ in range(args.starts):
stop(dataset)
starts.append(run(dataset, "start")[1])
stop(dataset)
first.append(sample())
report["readiness"] = distribution(starts)
report["firstUse"] = distribution(first)
print("Measuring ready-server roundtrips...", flush=True)
for _ in range(10):
sample()
report["warm"] = distribution([sample() for _ in range(args.samples)])
print("Measuring preserved per-call native baseline against identical records...", flush=True)
stop(dataset)
for _ in range(5):
sample(baseline)
report["baseline"]["version"] = run(dataset, "--version", executable=baseline)[0].strip()
report["baseline"]["roundtrip"] = distribution([sample(baseline) for _ in range(args.samples)])
if args.server_baseline:
previous = args.server_baseline.resolve(strict=True)
print("Measuring the preserved server implementation on identical records...", flush=True)
run(dataset, "start", executable=previous)
try:
for _ in range(10):
sample(previous)
report["serverBaseline"] = {"path": str(previous), "sha256": hashlib.sha256(previous.read_bytes()).hexdigest(),
"package": json.loads((previous.parent / "aie-package.json").read_text()),
"roundtrip": distribution([sample(previous) for _ in range(args.samples)])}
finally:
run(dataset, "stop", "--timeout-seconds", "10", executable=previous)
print("Measuring idle resident memory for 1/5/10 active projects...", flush=True)
run(dataset, "start")
sample()
report["method"]["memoryWorkload"] = "Fresh server then work show per project; first project has 100 Works/1000 notes, remaining projects one Work each. Summed process RSS, shared pages may be counted repeatedly."
report["memory"] = []
for count in range(1, 11):
if count > 1:
project = root / ("project-" + str(count))
project.mkdir()
roots.append(project)
run(project, "init", "--name", "Disposable memory project " + str(count))
run(project, "work", "create", "One resident Work")
stop(project)
run(project, "start")
run(project, "work", "show", "WRK-0001", "--format", "json")
if count in (1, 5, 10):
time.sleep(1)
processes = []
for project in roots:
status = json.loads(run(project, "server", "status")[0])
if status["state"] != "RUNNING":
raise RuntimeError("Memory fixture server is not running")
pid = status["server"]["pid"]
rss_kib = int(subprocess.check_output(["/bin/ps", "-o", "rss=", "-p", str(pid)], text=True).strip())
processes.append({"pid": pid, "rssMiB": rss_kib / 1024})
report["memory"].append({"projects": count, "processes": processes,
"totalRssMiB": sum(item["rssMiB"] for item in processes)})
report["acceptance"] = {"warmP95AtMost100Ms": report["warm"]["p95Ms"] <= 100,
"allReadinessAtMost1000Ms": report["readiness"]["maxMs"] <= 1000}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({"warm": {k: v for k, v in report["warm"].items() if k != "rawMs"},
"readiness": {k: v for k, v in report["readiness"].items() if k != "rawMs"},
"acceptance": report["acceptance"]}, indent=2), flush=True)
return 0 if all(report["acceptance"].values()) else 1
finally:
for project in reversed(roots):
stop(project)
if __name__ == "__main__":
sys.exit(main())
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Source from a smoke script; stop only servers below that script's disposable root.
stop_fixture_servers() {
local fixture_root=$1 fixture_binary=$2 endpoint project
while IFS= read -r -d '' endpoint; do
project=${endpoint%/.ai-engineering/.local/server/endpoint.json}
"$fixture_binary" --project "$project" stop --timeout-seconds 10 >/dev/null || return 1
done < <(find "$fixture_root" -type f -path '*/.ai-engineering/.local/server/endpoint.json' -print0)
}
+6
View File
@@ -52,11 +52,15 @@ printf '%s\n' "$PWD" "$JAVA_HOME" "$GRAALVM_HOME" "$@" >> "$FIXTURE_LOG"
[[ "${FIXTURE_BUILD_EXIT:-0}" == 0 ]] || exit "$FIXTURE_BUILD_EXIT"
[[ "${FIXTURE_MISSING_BINARY:-0}" == 0 ]] || exit 0
mkdir -p build/native/package
mkdir -p build/generated/serverIdentity
printf '%064d\\n' 0 > build/generated/serverIdentity/aie-build.txt
cat > build/native/package/ai-engineering <<'EOF'
#!/bin/bash
case "${1:-}" in
--version) echo "ai-engineering 0.1.0" ;;
init) mkdir -p .ai-engineering; touch .ai-engineering/aie.db ;;
server) printf '{"state":"RUNNING","server":{"protocol":1,"build":"%064d"}}\\n' 0 ;;
work) [[ "${2:-}" != show ]] || echo '{"id":"WRK-0001"}' ;;
*) echo "fixture CLI" ;;
esac
exit "${FIXTURE_BINARY_EXIT:-0}"
@@ -69,6 +73,8 @@ EOF
chmod +x build/native/package/sqlite3
if [[ "${FIXTURE_MISSING_LIBRARY:-0}" == 0 ]]; then echo "fixture library" > build/native/package/libsqlitejdbc.so; fi
python3 scripts/native-package-manifest.py build/native/package
# This installer fixture models the earlier JSON-only server package, without real sockets.
python3 -c 'import json; from pathlib import Path; p=Path("build/native/package/aie-package.json"); m=json.loads(p.read_text()); m.pop("localServerEvents",None); p.write_text(json.dumps(m))'
if [[ "${FIXTURE_CORRUPT_PACKAGE:-0}" == 1 ]]; then echo "changed" >> build/native/package/libsqlitejdbc.so; fi
''')
+26
View File
@@ -11,6 +11,10 @@ package = Path(sys.argv[1]).resolve()
manifest = json.loads((package / "aie-package.json").read_text())
if manifest.get("schemaVersion") != 1 or manifest.get("protocolVersion") != 4:
raise SystemExit("Unsupported native package manifest")
if manifest.get("localServerProtocol") not in (None, 1):
raise SystemExit("Unsupported local server protocol")
if manifest.get("localServerEvents") not in (None, "sse"):
raise SystemExit("Unsupported local server event transport")
expected = manifest["files"]
actual = set()
for path in package.rglob("*"):
@@ -41,4 +45,26 @@ with tempfile.TemporaryDirectory(prefix="aie-package-check-") as temporary:
result = subprocess.check_output([str(sqlite), "-readonly", str(database), "PRAGMA quick_check;"], text=True).strip()
if result != "ok":
raise SystemExit("Packaged SQLite cannot read the native AIE database")
if manifest.get("localServerProtocol") == 1:
try:
subprocess.run([str(aie), "start"], cwd=root, check=True, stdout=subprocess.DEVNULL, timeout=20)
status = json.loads(subprocess.check_output([str(aie), "server", "status"], cwd=root, text=True, timeout=10))
if status["state"] != "RUNNING" or status["server"]["protocol"] != 1 or status["server"]["build"] != manifest["buildIdentity"]:
raise SystemExit("Native server build/protocol mismatch")
subprocess.run([str(aie), "work", "create", "Disposable server verification"], cwd=root,
check=True, stdout=subprocess.DEVNULL, timeout=20)
work = json.loads(subprocess.check_output([str(aie), "work", "show", "WRK-0001", "--format", "json"], cwd=root, text=True, timeout=20))
if work["id"] != "WRK-0001":
raise SystemExit("Native client/server roundtrip failed")
except BaseException:
log = root / ".ai-engineering/.local/server/startup.log"
if log.is_file():
print(log.read_text()[-12000:], file=sys.stderr)
raise
finally:
subprocess.run([str(aie), "stop", "--timeout-seconds", "10"], cwd=root,
check=True, stdout=subprocess.DEVNULL, timeout=15)
if manifest.get("localServerEvents") == "sse":
subprocess.run([sys.executable, str(Path(__file__).with_name("native-sse-smoke.py")),
"--binary", str(aie)], check=True, timeout=120)
print("Native package verified:", package)