observation: deliver one execution event sequence to stream and snapshot
This commit is contained in:
1 parent
f83d992c61
commit
404d559b86
97 files changed
+2672
-3128
No files matched your search
@@ -1,145 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Black-box consumer for Marqdo Execution Events v1 (RFC-OBS-0001).
|
||||
|
||||
This is an independent consumer: it imports only the Python standard library
|
||||
and the `jsonschema` package, never the Rust workspace, and it consumes the
|
||||
output of a released `marqdo` binary (or a checked-in fixture).
|
||||
|
||||
Usage:
|
||||
execution_events_consumer.py EVENTS.jsonl
|
||||
execution_events_consumer.py - # read stdin
|
||||
execution_events_consumer.py --schema-check FILE.jsonl
|
||||
|
||||
Checks:
|
||||
* every line is one JSON object validated against
|
||||
`spec/schemas/execution-events-v1.schema.json`;
|
||||
* `stream.opened` is first (seq 0), `run.started` occurs at most once,
|
||||
exactly one terminal event on a complete stream, nothing follows it;
|
||||
* `seq` is contiguous and strictly increasing;
|
||||
* `run_id` and protocol/schema are consistent across lines;
|
||||
* `stdout.chunk`/`stderr.chunk` base64 decodes and `byte_count` matches;
|
||||
* an unknown schema major is rejected, never treated as v1.
|
||||
|
||||
Exit status 0 means the stream validated. 2 means invalid input, 3 means an
|
||||
incomplete stream (no terminal event; a legal boundary after SIGKILL/EOF).
|
||||
"""
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from jsonschema import Draft202012Validator
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
SCHEMA_PATH = ROOT / "spec" / "schemas" / "execution-events-v1.schema.json"
|
||||
SCHEMA = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
|
||||
Draft202012Validator.check_schema(SCHEMA)
|
||||
VALIDATOR = Draft202012Validator(SCHEMA)
|
||||
|
||||
SCHEMA_NAME = "marqdo.execution-events"
|
||||
SCHEMA_VERSION = 1
|
||||
TERMINALS = {"run.completed", "run.failed", "run.rejected"}
|
||||
|
||||
|
||||
class Invalid(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def parse_line(number, raw):
|
||||
try:
|
||||
event = json.loads(raw)
|
||||
except json.JSONDecodeError as error:
|
||||
raise Invalid(f"line {number}: not JSON: {error}") from error
|
||||
if not isinstance(event, dict):
|
||||
raise Invalid(f"line {number}: event is not a JSON object")
|
||||
errors = sorted(VALIDATOR.iter_errors(event), key=str)
|
||||
if errors:
|
||||
raise Invalid(f"line {number}: schema: {errors[0].message}")
|
||||
return event
|
||||
|
||||
|
||||
def check_chunk(event):
|
||||
payload = event["payload"]
|
||||
if payload.get("encoding") != "base64":
|
||||
raise Invalid(f"seq {event['seq']}: unsupported chunk encoding")
|
||||
try:
|
||||
data = base64.b64decode(payload["data_base64"], validate=True)
|
||||
except (binascii.Error, ValueError) as error:
|
||||
raise Invalid(f"seq {event['seq']}: data_base64 is not valid base64: {error}") from error
|
||||
if len(data) != payload["byte_count"]:
|
||||
raise Invalid(
|
||||
f"seq {event['seq']}: byte_count={payload['byte_count']} but decoded {len(data)} bytes"
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
def consume(lines, require_terminal=True):
|
||||
events = [parse_line(number, raw) for number, raw in enumerate(lines, start=1)]
|
||||
if not events:
|
||||
raise Invalid("empty stream")
|
||||
|
||||
first = events[0]
|
||||
if first["kind"] != "stream.opened":
|
||||
raise Invalid("first event must be stream.opened")
|
||||
if first["seq"] != 0:
|
||||
raise Invalid("stream.opened must have seq 0")
|
||||
if first["schema"] != SCHEMA_NAME or first["schema_version"] != SCHEMA_VERSION:
|
||||
raise Invalid("stream.opened does not negotiate marqdo.execution-events v1")
|
||||
|
||||
run_id = first["run_id"]
|
||||
chunks = bytearray()
|
||||
terminal = None
|
||||
started = 0
|
||||
for index, event in enumerate(events):
|
||||
seq = event["seq"]
|
||||
if seq != index:
|
||||
raise Invalid(f"seq {seq} at line {index + 1}; expected {index}")
|
||||
if event["schema"] != SCHEMA_NAME or event["schema_version"] != SCHEMA_VERSION:
|
||||
raise Invalid(f"seq {seq}: inconsistent schema negotiation")
|
||||
if event["run_id"] != run_id:
|
||||
raise Invalid(f"seq {seq}: run_id changed within one stream")
|
||||
if terminal is not None:
|
||||
raise Invalid(f"seq {seq}: event follows terminal {terminal}")
|
||||
if event["kind"] == "run.started":
|
||||
started += 1
|
||||
if started > 1:
|
||||
raise Invalid("more than one run.started")
|
||||
if event["kind"] in TERMINALS:
|
||||
terminal = event["kind"]
|
||||
if event["kind"] in ("stdout.chunk", "stderr.chunk"):
|
||||
chunks.extend(check_chunk(event))
|
||||
|
||||
if require_terminal and terminal is None:
|
||||
return 3, f"incomplete stream: {len(events)} events, no terminal event"
|
||||
if terminal == "run.completed" and started != 1:
|
||||
raise Invalid("run.completed requires exactly one preceding run.started")
|
||||
if terminal == "run.failed" and started != 1:
|
||||
raise Invalid("run.failed requires exactly one preceding run.started")
|
||||
if terminal == "run.rejected" and started != 0:
|
||||
raise Invalid("run.rejected must not be preceded by run.started")
|
||||
return 0, (
|
||||
f"ok: {len(events)} events, terminal={terminal}, "
|
||||
f"stdout+stderr bytes={len(chunks)}"
|
||||
)
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 2:
|
||||
raise SystemExit(__doc__)
|
||||
target = argv[1]
|
||||
if target == "-":
|
||||
lines = [line for line in sys.stdin.read().splitlines() if line.strip()]
|
||||
else:
|
||||
text = pathlib.Path(target).read_text(encoding="utf-8")
|
||||
lines = [line for line in text.splitlines() if line.strip()]
|
||||
try:
|
||||
status, message = consume(lines)
|
||||
except Invalid as error:
|
||||
raise SystemExit(f"execution events consumer: INVALID: {error}")
|
||||
print(f"execution events consumer: {message}")
|
||||
raise SystemExit(status)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv)
|
||||
@@ -1 +0,0 @@
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":3,"kind":"stdout.chunk","payload":{"encoding":"base64","byte_count":13}}
|
||||
@@ -1 +0,0 @@
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":4,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"m","span":{"start":1}}}
|
||||
@@ -1 +0,0 @@
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":5,"kind":"run.completed","payload":{"status":"ok"}}
|
||||
@@ -1 +0,0 @@
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.execution-events","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}}
|
||||
@@ -1 +0,0 @@
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened"}
|
||||
@@ -1 +0,0 @@
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.execution-events","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}}
|
||||
@@ -1 +0,0 @@
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":-1,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.execution-events","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}}
|
||||
@@ -1 +0,0 @@
|
||||
{"schema":"marqdo.execution-events","schema_version":2,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.execution-events","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}}
|
||||
@@ -1,14 +0,0 @@
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.execution-events","schema_version":1},"observation":{"level":"values","values":true,"selected_variables":["visible_count"],"selected_parameters":["n"],"allow_text_values":false},"limits":{"max_observation_events":100,"max_observation_bytes":1048576,"max_value_bytes":256}}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":1,"kind":"run.started","payload":{"entry":"root:demo@0.1.0::index.mq.md::main","mode":"project","source":{"root_id":"root:demo@0.1.0","analysis_digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"started_unix_ms":1763800000000}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":2,"kind":"call.enter","payload":{"frame_id":"f1","parent_frame_id":null,"function_id":"root:demo@0.1.0::index.mq.md::main","module_id":"root:demo@0.1.0::index.mq.md","span":null}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":3,"kind":"parameter.observed","payload":{"frame_id":"f1","name":"n","source":"provided","value_type":"Int","module_id":"root:demo@0.1.0::index.mq.md","span":null,"value_state":"observed","value":{"type":"int","decimal":"5"}}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":4,"kind":"variable.assigned","payload":{"frame_id":"f1","name":"visible_count","value_type":"Int","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":80,"end":100},"value_state":"observed","value":{"type":"int","decimal":"42"}}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":5,"kind":"variable.assigned","payload":{"frame_id":"f1","name":"secret_token","value_type":"Text","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":110,"end":150},"value_state":"redacted"}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":6,"kind":"branch.eval","payload":{"frame_id":"f1","result":true,"module_id":"root:demo@0.1.0::index.mq.md","span":{"start":160,"end":170}}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":7,"kind":"loop.iteration","payload":{"frame_id":"f1","decision":"continue","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":180,"end":190}}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":8,"kind":"effect","payload":{"operation":"print","result_code":"ok","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":200,"end":210}}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":9,"kind":"stderr.chunk","payload":{"encoding":"base64","data_base64":"AA==","byte_count":1}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":10,"kind":"return","payload":{"frame_id":"f1","value_type":"Int","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":220,"end":230}}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":11,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"root:demo@0.1.0::index.mq.md","span":null}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":12,"kind":"observation.truncated","payload":{"reason":"event_budget","limit":100,"written":100,"dropped":null}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":13,"kind":"run.completed","payload":{"status":"ok","value":{"type":"int","decimal":"42"}}}
|
||||
@@ -1,6 +0,0 @@
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.execution-events","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":1,"kind":"run.started","payload":{"entry":"root:demo@0.1.0::index.mq.md::main","mode":"project","source":{"root_id":"root:demo@0.1.0","analysis_digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"started_unix_ms":1763800000000}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":2,"kind":"call.enter","payload":{"frame_id":"f1","parent_frame_id":null,"function_id":"root:demo@0.1.0::index.mq.md::main","module_id":"root:demo@0.1.0::index.mq.md","span":null}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":3,"kind":"stdout.chunk","payload":{"encoding":"base64","data_base64":"5byA5aeL5paH5pysCg==","byte_count":13}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":4,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":10,"end":20}}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":5,"kind":"run.completed","payload":{"status":"ok","value":{"type":"int","decimal":"10"}}}
|
||||
+4
-4
@@ -1,8 +1,8 @@
|
||||
# Execution Events v1 fixtures
|
||||
# Observation fixtures
|
||||
|
||||
These are the minimal executable fixtures from RFC-OBS-0001 §13 plus the
|
||||
schema-validation fixtures used by
|
||||
[`execution_events_consumer.py`](../../execution_events_consumer.py).
|
||||
[`observation_consumer.py`](../../observation_consumer.py).
|
||||
|
||||
| File | Purpose |
|
||||
|---|---|
|
||||
@@ -16,6 +16,6 @@ schema-validation fixtures used by
|
||||
The `.mq.md` files are inputs to the released CLI:
|
||||
|
||||
```bash
|
||||
marqdo run tests/consumers/fixtures/execution-events/basic.mq.md --event-stream jsonl
|
||||
python3 tests/consumers/execution_events_consumer.py /tmp/events.jsonl
|
||||
marqdo run tests/consumers/fixtures/observation/basic.mq.md --output jsonl
|
||||
python3 tests/consumers/observation_consumer.py /tmp/events.jsonl
|
||||
```
|
||||
File renamed without changes.
@@ -0,0 +1 @@
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":3,"kind":"stdout.chunk","payload":{"encoding":"base64","byte_count":13}}
|
||||
@@ -0,0 +1 @@
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":4,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"m","span":{"start":1}}}
|
||||
@@ -0,0 +1 @@
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":5,"kind":"run.completed","payload":{"status":"ok"}}
|
||||
@@ -0,0 +1 @@
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.observation","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}}
|
||||
@@ -0,0 +1 @@
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened"}
|
||||
@@ -0,0 +1 @@
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.observation","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}}
|
||||
@@ -0,0 +1 @@
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":-1,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.observation","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}}
|
||||
@@ -0,0 +1 @@
|
||||
{"schema":"marqdo.observation","schema_version":2,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.observation","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}}
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,14 @@
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"observation":{"level":"values","values":true,"selected_variables":["visible_count"],"selected_parameters":["n"],"allow_text_values":false},"limits":{"max_observation_events":100,"max_observation_bytes":1048576,"max_value_bytes":256}}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":1,"kind":"run.started","payload":{"entry":"root:demo@0.1.0::index.mq.md::main","mode":"project","source":{"root_id":"root:demo@0.1.0","analysis_digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"started_unix_ms":1763800000000}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":2,"kind":"call.enter","payload":{"frame_id":"f1","parent_frame_id":null,"function_id":"root:demo@0.1.0::index.mq.md::main","module_id":"root:demo@0.1.0::index.mq.md","span":null}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":3,"kind":"parameter.observed","payload":{"frame_id":"f1","name":"n","source":"provided","value_type":"Int","module_id":"root:demo@0.1.0::index.mq.md","span":null,"value_state":"observed","value":{"type":"int","decimal":"5"}}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":4,"kind":"variable.assigned","payload":{"frame_id":"f1","name":"visible_count","value_type":"Int","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":80,"end":100},"value_state":"observed","value":{"type":"int","decimal":"42"}}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":5,"kind":"variable.assigned","payload":{"frame_id":"f1","name":"secret_token","value_type":"Text","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":110,"end":150},"value_state":"redacted"}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":6,"kind":"branch.eval","payload":{"frame_id":"f1","result":true,"module_id":"root:demo@0.1.0::index.mq.md","span":{"start":160,"end":170}}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":7,"kind":"loop.iteration","payload":{"frame_id":"f1","decision":"continue","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":180,"end":190}}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":8,"kind":"effect","payload":{"operation":"print","result_code":"ok","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":200,"end":210},"frame_id":"f1"}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":9,"kind":"stderr.chunk","payload":{"encoding":"base64","data_base64":"AA==","byte_count":1}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":10,"kind":"return","payload":{"frame_id":"f1","value_type":"Int","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":220,"end":230}}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":11,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"root:demo@0.1.0::index.mq.md","span":null}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":12,"kind":"observation.truncated","payload":{"reason":"event_budget","limit":100,"written":100,"dropped":null}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":13,"kind":"run.completed","payload":{"status":"ok","value":{"type":"int","decimal":"42"},"value_type":"Int"}}
|
||||
@@ -0,0 +1,6 @@
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":1,"kind":"run.started","payload":{"entry":"root:demo@0.1.0::index.mq.md::main","mode":"project","source":{"root_id":"root:demo@0.1.0","analysis_digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"started_unix_ms":1763800000000}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":2,"kind":"call.enter","payload":{"frame_id":"f1","parent_frame_id":null,"function_id":"root:demo@0.1.0::index.mq.md::main","module_id":"root:demo@0.1.0::index.mq.md","span":null}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":3,"kind":"stdout.chunk","payload":{"encoding":"base64","data_base64":"5byA5aeL5paH5pysCg==","byte_count":13}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":4,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":10,"end":20}}}
|
||||
{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":5,"kind":"run.completed","payload":{"status":"ok","value":{"type":"int","decimal":"10"},"value_type":"Int"}}
|
||||
File renamed without changes.
@@ -0,0 +1,216 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Consume real Marqdo observation output using public contracts only."""
|
||||
import argparse
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
SCHEMAS = pathlib.Path(__file__).resolve().parents[2] / "spec" / "schemas"
|
||||
EVENT_SCHEMA = json.loads((SCHEMAS / "observation-event.schema.json").read_text())
|
||||
SCHEMA = "marqdo.observation"
|
||||
KINDS = set(EVENT_SCHEMA["properties"]["kind"]["enum"])
|
||||
TERMINALS = {"run.completed": "ok", "run.failed": "error", "run.rejected": "rejected"}
|
||||
|
||||
|
||||
class Invalid(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def current_document(value):
|
||||
return (
|
||||
isinstance(value, dict)
|
||||
and value.get("schema") == SCHEMA
|
||||
and type(value.get("schema_version")) is int
|
||||
and value["schema_version"] == 1
|
||||
)
|
||||
|
||||
|
||||
def check_source(source, events, analysis_path, source_root):
|
||||
raw = analysis_path.read_bytes()
|
||||
report = json.loads(raw)
|
||||
if report.get("schema") != "marqdo.analysis" or report.get("schema_version") != 3:
|
||||
raise Invalid("unsupported Analysis format")
|
||||
expected = "sha256:" + hashlib.sha256(raw).hexdigest()
|
||||
if source is None or source["analysis_digest"] != expected:
|
||||
raise Invalid("Analysis digest mismatch")
|
||||
if source["root_id"] != report["project"]["root_id"]:
|
||||
raise Invalid("Analysis project identity mismatch")
|
||||
|
||||
modules = {module["id"]: module for module in report["modules"]}
|
||||
checked_sources = {}
|
||||
for event in events:
|
||||
payload = event["payload"]
|
||||
functions = [payload["function_id"]] if "function_id" in payload else []
|
||||
for function in functions:
|
||||
if function.rsplit("::", 1)[0] not in modules:
|
||||
raise Invalid("unknown function module")
|
||||
if "module_id" not in payload:
|
||||
continue
|
||||
module_id = payload["module_id"]
|
||||
if module_id not in modules:
|
||||
raise Invalid("unknown event module")
|
||||
span = payload.get("span")
|
||||
if span is not None and not 0 <= span["start"] <= span["end"]:
|
||||
raise Invalid("invalid event span")
|
||||
if source_root is None or not module_id.startswith("root:"):
|
||||
continue
|
||||
if module_id not in checked_sources:
|
||||
module = modules[module_id]
|
||||
path = (source_root / module["relative_path"]).resolve()
|
||||
if not path.is_relative_to(source_root):
|
||||
raise Invalid("root source path escaped its checkout")
|
||||
data = path.read_bytes()
|
||||
if hashlib.sha256(data).hexdigest() != module["source_digest"]:
|
||||
raise Invalid(f"source digest mismatch for {module['relative_path']}")
|
||||
checked_sources[module_id] = data
|
||||
if span is not None:
|
||||
data = checked_sources[module_id]
|
||||
if span["end"] > len(data):
|
||||
raise Invalid("event span exceeds source length")
|
||||
try:
|
||||
data[span["start"]:span["end"]].decode("utf-8")
|
||||
except UnicodeDecodeError as error:
|
||||
raise Invalid("event span splits UTF-8") from error
|
||||
|
||||
|
||||
def check_chunk(payload):
|
||||
if payload["encoding"] != "base64":
|
||||
raise Invalid("unsupported chunk encoding")
|
||||
try:
|
||||
raw = base64.b64decode(payload["data_base64"], validate=True)
|
||||
except (binascii.Error, ValueError) as error:
|
||||
raise Invalid("invalid base64 chunk") from error
|
||||
if len(raw) != payload["byte_count"]:
|
||||
raise Invalid("chunk byte count mismatch")
|
||||
return len(raw)
|
||||
|
||||
|
||||
def consume(events, snapshot=None, analysis=None, source_root=None):
|
||||
if not isinstance(events, list) or not events:
|
||||
raise Invalid("expected an opening event")
|
||||
first = events[0]
|
||||
if not current_document(first) or first.get("kind") != "stream.opened":
|
||||
raise Invalid("expected current Observation opening event")
|
||||
run_id = first.get("run_id")
|
||||
if not isinstance(run_id, str) or not run_id:
|
||||
raise Invalid("invalid run identity")
|
||||
source = None
|
||||
terminal = None
|
||||
truncation = None
|
||||
chunks = 0
|
||||
stack = []
|
||||
seen = set()
|
||||
for seq, event in enumerate(events):
|
||||
if (
|
||||
not current_document(event)
|
||||
or event.get("run_id") != run_id
|
||||
or type(event.get("seq")) is not int
|
||||
or event["seq"] != seq
|
||||
or event.get("kind") not in KINDS
|
||||
or not isinstance(event.get("payload"), dict)
|
||||
):
|
||||
raise Invalid(f"invalid event envelope at sequence {seq}")
|
||||
kind = event["kind"]
|
||||
payload = event["payload"]
|
||||
if terminal is not None:
|
||||
raise Invalid("event after terminal")
|
||||
if seq == 0:
|
||||
continue
|
||||
if kind == "run.started" and seq == 1:
|
||||
source = payload["source"]
|
||||
if not isinstance(source, dict):
|
||||
raise Invalid("missing source binding")
|
||||
continue
|
||||
if kind == "run.rejected" and seq == 1:
|
||||
terminal = TERMINALS[kind]
|
||||
elif source is None or kind in ("run.started", "stream.opened", "run.rejected"):
|
||||
raise Invalid("invalid run lifecycle")
|
||||
elif kind in TERMINALS:
|
||||
terminal = TERMINALS[kind]
|
||||
elif kind in ("stdout.chunk", "stderr.chunk"):
|
||||
chunks += check_chunk(payload)
|
||||
elif kind == "observation.truncated":
|
||||
if truncation is not None:
|
||||
raise Invalid("duplicate truncation marker")
|
||||
truncation = payload
|
||||
elif truncation is not None:
|
||||
raise Invalid("structural event after truncation")
|
||||
elif kind == "call.enter":
|
||||
frame = payload["frame_id"]
|
||||
if frame in seen or payload["parent_frame_id"] != (stack[-1] if stack else None):
|
||||
raise Invalid("invalid call frame parent or reused frame identity")
|
||||
seen.add(frame)
|
||||
stack.append(frame)
|
||||
elif kind == "call.exit":
|
||||
if not stack or payload["frame_id"] != stack.pop():
|
||||
raise Invalid("mismatched call exit")
|
||||
elif payload.get("frame_id") is not None and (
|
||||
not stack or payload["frame_id"] != stack[-1]
|
||||
):
|
||||
raise Invalid("observation outside its owning frame")
|
||||
if terminal is not None and payload["status"] != terminal:
|
||||
raise Invalid("terminal status mismatch")
|
||||
|
||||
if terminal is not None and truncation is None and stack:
|
||||
raise Invalid("unclosed frame")
|
||||
if snapshot is not None:
|
||||
run = snapshot["run"]
|
||||
capture = snapshot["capture"]
|
||||
if (
|
||||
run["id"] != run_id
|
||||
or run["source"] != source
|
||||
or run["status"] != (terminal or "incomplete")
|
||||
or capture["truncated"] != truncation
|
||||
or {key: value for key, value in capture.items() if key != "truncated"}
|
||||
!= first["payload"]["observation"]
|
||||
):
|
||||
raise Invalid("snapshot metadata disagrees with its events")
|
||||
if analysis is not None:
|
||||
check_source(source, events, analysis, source_root)
|
||||
if terminal is None:
|
||||
return 3, f"incomplete: {len(events)} events, no terminal"
|
||||
return 0, f"{terminal}: {len(events)} events, {chunks} output bytes"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("input", help="path or - for stdin")
|
||||
parser.add_argument("--snapshot", action="store_true", help="read the JSON snapshot root")
|
||||
parser.add_argument("--analysis", type=pathlib.Path)
|
||||
parser.add_argument("--validate-schema", action="store_true")
|
||||
parser.add_argument("--source-root", type=lambda path: pathlib.Path(path).resolve())
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
text = sys.stdin.read() if args.input == "-" else pathlib.Path(args.input).read_text()
|
||||
if args.snapshot:
|
||||
snapshot = json.loads(text)
|
||||
if not current_document(snapshot):
|
||||
raise Invalid("unsupported Observation snapshot")
|
||||
events = snapshot["events"]
|
||||
else:
|
||||
snapshot = None
|
||||
if text and not text.endswith("\n"):
|
||||
print("incomplete: interrupted JSONL record", file=sys.stderr)
|
||||
return 3
|
||||
events = [json.loads(line) for line in text.split("\n")[:-1]]
|
||||
if args.validate_schema:
|
||||
from validate_protocols import require_valid
|
||||
|
||||
if snapshot is not None:
|
||||
require_valid("observation-file.schema.json", snapshot, "snapshot")
|
||||
else:
|
||||
for index, event in enumerate(events):
|
||||
require_valid("observation-event.schema.json", event, f"seq {index}")
|
||||
status, message = consume(events, snapshot, args.analysis, args.source_root)
|
||||
print(message)
|
||||
return status
|
||||
except (Invalid, KeyError, TypeError, ValueError, OSError) as error:
|
||||
print(f"invalid Observation: {error}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,53 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Independent Trace v2 consumer: no Marqdo/Rust imports."""
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
|
||||
if len(sys.argv) != 3:
|
||||
raise SystemExit("usage: trace_consumer.py ANALYSIS.json TRACE.json")
|
||||
|
||||
with open(sys.argv[1], "rb") as handle:
|
||||
analysis_bytes = handle.read()
|
||||
analysis = json.loads(analysis_bytes)
|
||||
with open(sys.argv[2], encoding="utf-8") as handle:
|
||||
trace = json.load(handle)
|
||||
|
||||
if analysis.get("schema") != "marqdo.analysis" or analysis.get("schema_version") != 3:
|
||||
raise SystemExit("unsupported analysis")
|
||||
if trace.get("schema") != "marqdo.trace" or trace.get("schema_version") != 2:
|
||||
raise SystemExit("unsupported trace")
|
||||
|
||||
modules = {module["id"]: module for module in analysis["modules"]}
|
||||
if trace["source"]["root_id"] != analysis["project"]["root_id"]:
|
||||
raise SystemExit("trace/analysis root mismatch")
|
||||
expected = "sha256:" + hashlib.sha256(analysis_bytes).hexdigest()
|
||||
if trace["source"]["analysis_digest"] != expected:
|
||||
raise SystemExit("analysis digest mismatch")
|
||||
|
||||
truncated = trace.get("truncated")
|
||||
if truncated is not None and truncated.get("reason") not in ("event_budget", "byte_budget"):
|
||||
raise SystemExit("bad truncation reason")
|
||||
|
||||
previous = None
|
||||
events = trace["events"]
|
||||
for event in events:
|
||||
seq = event["seq"]
|
||||
if previous is not None and seq <= previous:
|
||||
raise SystemExit("sequence is not increasing")
|
||||
previous = seq
|
||||
span = event.get("span")
|
||||
if span is not None and (span["start"] > span["end"]):
|
||||
raise SystemExit("bad span")
|
||||
module_id = event.get("module_id")
|
||||
if module_id is not None and module_id not in modules:
|
||||
raise SystemExit("event references an unknown module")
|
||||
function_id = event.get("function_id")
|
||||
if function_id is not None:
|
||||
owner = function_id.rsplit("::", 1)[0]
|
||||
if owner not in modules:
|
||||
raise SystemExit("function id references an unknown module")
|
||||
|
||||
if truncated is not None and events and events[-1].get("kind") != "trace.truncated":
|
||||
raise SystemExit("truncated trace has no terminal marker")
|
||||
print("events=" + str(len(events)))
|
||||
@@ -10,6 +10,7 @@ import pathlib
|
||||
import sys
|
||||
|
||||
from jsonschema import Draft202012Validator
|
||||
from referencing import Registry, Resource
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
SCHEMA_DIR = ROOT / "spec" / "schemas"
|
||||
@@ -23,7 +24,9 @@ def load_schema(name):
|
||||
|
||||
|
||||
def validator(schema):
|
||||
return Draft202012Validator(schema)
|
||||
event = load_schema("observation-event.schema.json")
|
||||
registry = Registry().with_resource(event["$id"], Resource.from_contents(event))
|
||||
return Draft202012Validator(schema, registry=registry)
|
||||
|
||||
|
||||
def require_valid(schema_name, document, label):
|
||||
@@ -41,16 +44,16 @@ def require_invalid(schema_name, document, label):
|
||||
def main():
|
||||
if len(sys.argv) != 4:
|
||||
raise SystemExit(
|
||||
"usage: validate_protocols.py ANALYSIS.json TRACE.json TOOL.json"
|
||||
"usage: validate_protocols.py ANALYSIS.json OBSERVATION.json TOOL.json"
|
||||
)
|
||||
analysis_path, trace_path, tool_path = map(pathlib.Path, sys.argv[1:])
|
||||
analysis_path, observation_path, tool_path = map(pathlib.Path, sys.argv[1:])
|
||||
analysis = json.loads(analysis_path.read_text(encoding="utf-8"))
|
||||
trace = json.loads(trace_path.read_text(encoding="utf-8"))
|
||||
observation = json.loads(observation_path.read_text(encoding="utf-8"))
|
||||
tool = json.loads(tool_path.read_text(encoding="utf-8"))
|
||||
|
||||
analysis_schema = "analysis.schema.json"
|
||||
require_valid(analysis_schema, analysis, "analysis")
|
||||
require_valid("trace-v2.schema.json", trace, "trace")
|
||||
require_valid("observation-file.schema.json", observation, "observation")
|
||||
require_valid("cli-tool.schema.json", tool, "tool")
|
||||
|
||||
# Negative mutations: structure, version and traversal must fail closed.
|
||||
@@ -66,13 +69,16 @@ def main():
|
||||
bad["modules"][0]["resources"] = 3
|
||||
require_invalid(analysis_schema, bad, "analysis resources integer")
|
||||
|
||||
bad = copy.deepcopy(trace)
|
||||
bad = copy.deepcopy(observation)
|
||||
bad["events"][0]["seq"] = "zero"
|
||||
require_invalid("trace-v2.schema.json", bad, "trace event sequence type")
|
||||
require_invalid("observation-file.schema.json", bad, "observation event sequence type")
|
||||
|
||||
bad = copy.deepcopy(trace)
|
||||
bad["truncated"] = {"reason": "made_up", "limit": 1, "written": 1}
|
||||
require_invalid("trace-v2.schema.json", bad, "trace truncation reason")
|
||||
bad = copy.deepcopy(observation)
|
||||
bad["events"][0]["schema"] = "marqdo.execution-events"
|
||||
require_invalid("observation-file.schema.json", bad, "retired event format")
|
||||
bad = copy.deepcopy(tool)
|
||||
bad["requires"]["analysis"] = [3]
|
||||
require_invalid("cli-tool.schema.json", bad, "tool version requirement array")
|
||||
|
||||
bad = copy.deepcopy(tool)
|
||||
bad["entrypoint"] = "../outside"
|
||||
@@ -83,8 +89,8 @@ def main():
|
||||
require_invalid("cli-tool.schema.json", bad, "tool invalid version")
|
||||
|
||||
print(
|
||||
"validated analysis/trace/tool artifacts "
|
||||
f"({len(analysis['modules'])} modules, {len(trace['events'])} events)"
|
||||
"validated analysis/observation/tool artifacts "
|
||||
f"({len(analysis['modules'])} modules, {len(observation['events'])} events)"
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user