Protocol convergence for 3.0.0-rc.3 (issue #8) #9

Merged
cflmy merged 17 commits from architecture/issue-8-protocols into master 2026-11-24 19:23:26 +08:00
19 changed files with 93 additions and 500 deletions
Showing only changes of commit 8bfe0c36ee - Show all commits

No files matched your search

+8 -12
View File
@@ -106,26 +106,22 @@ jobs:
run: |
cargo build -p marqdo-cli
./target/debug/marqdo check examples/multi-module/index.mq.md --refs \
--emit /tmp/analysis-v2.json
--emit /tmp/analysis-simple.json
./target/debug/marqdo run examples/multi-module/index.mq.md \
--trace-file /tmp/trace-v2.json
python3 tests/consumers/validate_protocols.py \
/tmp/analysis-v2.json /tmp/trace-v2.json examples/tool-unknown-name/tool.json
python3 tests/consumers/analysis_consumer.py /tmp/analysis-v2.json
/tmp/analysis-simple.json /tmp/trace-v2.json examples/tool-unknown-name/tool.json
python3 tests/consumers/analysis_consumer.py /tmp/analysis-simple.json
python3 tests/consumers/trace_consumer.py \
/tmp/analysis-v2.json /tmp/trace-v2.json
/tmp/analysis-simple.json /tmp/trace-v2.json
./target/debug/marqdo check tests/conformance/semantics/85-nested-loop-control.mq.md \
--emit /tmp/analysis-v3.json
--emit /tmp/analysis-control.json
./target/debug/marqdo run tests/conformance/semantics/85-nested-loop-control.mq.md \
--event-stream jsonl --trace-file /tmp/control-trace-v2.json > /tmp/control-events.jsonl
python3 tests/consumers/validate_protocols.py \
/tmp/analysis-v3.json /tmp/control-trace-v2.json examples/tool-unknown-name/tool.json
python3 tests/consumers/analysis_v3_consumer.py /tmp/analysis-v3.json
if python3 tests/consumers/analysis_consumer.py /tmp/analysis-v3.json; then
echo "Analysis v2 consumer accepted a v3 document" >&2
exit 1
fi
python3 tests/consumers/trace_consumer.py /tmp/analysis-v3.json /tmp/control-trace-v2.json
/tmp/analysis-control.json /tmp/control-trace-v2.json examples/tool-unknown-name/tool.json
python3 tests/consumers/analysis_consumer.py /tmp/analysis-control.json --require-transfers
python3 tests/consumers/trace_consumer.py /tmp/analysis-control.json /tmp/control-trace-v2.json
python3 tests/consumers/execution_events_consumer.py /tmp/control-events.jsonl
cross-platform:
+3 -23
View File
@@ -1,4 +1,4 @@
//! Public Analysis projection (spec/analysis-v2.md and spec/analysis-v3.md).
//! Public Analysis projection (spec/analysis.md).
//!
//! This is deliberately not a serde dump of `marqdo-ir`: the schema and node
//! kinds are the public contract, while internal Rust types may change. The
@@ -17,24 +17,13 @@ use crate::loader::LoadedProject;
/// Schema name and version.
pub const SCHEMA: &str = "marqdo.analysis";
pub const BASE_VERSION: u32 = 2;
/// First schema version with structured loop transfers.
pub const LOOP_CONTROL_VERSION: u32 = 3;
pub const SCHEMA_VERSION: u32 = 3;
/// Build the deterministic public projection.
pub fn build(project: &LoadedProject) -> Value {
let mut modules = Vec::new();
let mut version = BASE_VERSION;
for (module_id, file) in &project.files {
let module = &file.analysis.module;
if version == BASE_VERSION
&& module
.functions
.iter()
.any(|function| has_loop_control(&function.body))
{
version = LOOP_CONTROL_VERSION;
}
modules.push(json!({
"id": module_id.to_string(),
"package_instance_id": module_id.instance,
@@ -60,7 +49,7 @@ pub fn build(project: &LoadedProject) -> Value {
});
json!({
"schema": SCHEMA,
"schema_version": version,
"schema_version": SCHEMA_VERSION,
"producer": {
"name": "marqdo",
"version": env!("CARGO_PKG_VERSION"),
@@ -81,15 +70,6 @@ pub fn build(project: &LoadedProject) -> Value {
})
}
fn has_loop_control(body: &[Stmt]) -> bool {
body.iter().any(|stmt| match stmt {
Stmt::Break { .. } | Stmt::Continue { .. } => true,
Stmt::Branch { arms, .. } => arms.iter().any(|arm| has_loop_control(&arm.body)),
Stmt::Loop { body, .. } => has_loop_control(body),
Stmt::Assign { .. } | Stmt::Eval { .. } | Stmt::Return { .. } => false,
})
}
/// Encode exactly the bytes written by `check --emit`.
fn encode(project: &LoadedProject) -> Result<Vec<u8>, String> {
serde_json::to_vec_pretty(&build(project))
+1 -1
View File
@@ -314,7 +314,7 @@ struct CheckArgs {
/// Declare a plugin manifest for static export-signature checking.
#[arg(long = "plugin", value_name = "PATH")]
plugin: Vec<PathBuf>,
/// Write public Analysis JSON, using v3 for projects with loop transfers.
/// Write the current public Analysis JSON for the checked project.
#[arg(long, value_name = "PATH")]
emit: Option<PathBuf>,
/// Machine readable JSON output.
+1 -4
View File
@@ -31,10 +31,7 @@ struct SupportedProtocols {
const SUPPORTED: SupportedProtocols = SupportedProtocols {
tool: PROTOCOL_VERSION,
analysis: &[
crate::analysis::BASE_VERSION,
crate::analysis::LOOP_CONTROL_VERSION,
],
analysis: &[crate::analysis::SCHEMA_VERSION],
trace: &[2],
};
+8 -8
View File
@@ -1,4 +1,4 @@
//! Public Analysis/Trace v1 black-box contract (spec/analysis-v1.md,
//! Public Analysis and Trace black-box contracts (spec/analysis.md,
//! spec/trace-v1.md).
use std::path::{Path, PathBuf};
@@ -96,7 +96,7 @@ fn analysis_is_deterministic_and_has_stable_semantic_nodes() {
let analysis: serde_json::Value = serde_json::from_slice(&first_bytes).unwrap();
assert_eq!(analysis["schema"], "marqdo.analysis");
assert_eq!(analysis["schema_version"], 2);
assert_eq!(analysis["schema_version"], 3);
let module = &analysis["modules"][0];
assert_eq!(module["id"], "root:default::index.mq.md");
assert_eq!(module["package_instance_id"], "root:default");
@@ -140,7 +140,7 @@ fn analysis_is_deterministic_and_has_stable_semantic_nodes() {
}
#[test]
fn analysis_v2_identity_is_location_independent() {
fn analysis_identity_is_location_independent() {
let first = TempDir::new("analysis-identity-a");
let second = TempDir::new("analysis-identity-b");
let source = "## @exec main\n\n`x = 1`\n\n`return x`\n";
@@ -182,7 +182,7 @@ fn analysis_v2_identity_is_location_independent() {
}
#[test]
fn analysis_v2_projects_memory_place_targets_additively() {
fn analysis_projects_memory_place_targets_additively() {
let dir = TempDir::new("analysis-place");
let source =
"## @exec main\n\n`内存 = memory.new(1, 2)`\n\n`内存[0] = 7`\n\n`return 内存[0]`\n";
@@ -211,7 +211,7 @@ fn analysis_v2_projects_memory_place_targets_additively() {
}
#[test]
fn analysis_v2_projects_addressable_formula_and_code_resources() {
fn analysis_projects_addressable_formula_and_code_resources() {
let dir = TempDir::new("analysis-resources");
let source = r#"## @exec calc
@@ -395,7 +395,7 @@ fn trace_records_calls_effects_and_status_without_secrets() {
}
#[test]
fn multi_arm_branch_preserves_analysis_v2_and_carrier_positions() {
fn multi_arm_branch_preserves_analysis_and_carrier_positions() {
let dir = TempDir::new("else-if");
let source = r#"## @exec 分类
@@ -427,7 +427,7 @@ fn multi_arm_branch_preserves_analysis_v2_and_carrier_positions() {
assert!(output.status.success(), "{output:?}");
let analysis: serde_json::Value =
serde_json::from_slice(&std::fs::read(dir.path().join("analysis.json")).unwrap()).unwrap();
assert_eq!(analysis["schema_version"], 2);
assert_eq!(analysis["schema_version"], 3);
assert_eq!(analysis["producer"]["markdown_profile"], "marqdo.md.v1");
let branch = &analysis["modules"][0]["functions"][0]["body"][0];
assert_eq!(branch["kind"], "branch");
@@ -463,7 +463,7 @@ fn multi_arm_branch_preserves_analysis_v2_and_carrier_positions() {
}
#[test]
fn an_imported_loop_transfer_selects_v3_and_keeps_the_else_if_call_edge() {
fn an_imported_loop_transfer_uses_current_schema_and_keeps_the_else_if_call_edge() {
let dir = TempDir::new("imported-loop");
write(
dir.path(),
+1 -1
View File
@@ -133,7 +133,7 @@ fn unknown_tool_name_installs_and_dispatches() {
#[test]
fn public_schemas_are_valid_json_and_versioned() {
for name in ["analysis-v1", "trace-v1", "tool-v1", "execution-events-v1"] {
for name in ["analysis", "trace-v1", "tool-v1", "execution-events-v1"] {
let path = repo()
.join("spec/schemas")
.join(format!("{name}.schema.json"));
-140
View File
@@ -1,140 +0,0 @@
# Marqdo Analysis v1
Status: **superseded by [Analysis v2](analysis-v2.md); never released, do not
write v1.** Kept as history. This was the M0.6 R4 read-only projection; it is
not a dump of `marqdo-ir`.
## 1. Invariants
`check --emit`:
* never executes the document, loads a plugin shared library, starts a foreign
kernel or imports a module implicitly;
* validates the loaded program first; on a compile error it writes no artifact
and removes a stale file at the target path;
* writes atomically (temporary file + rename) only after a successful check;
* is deterministic: the same source, tool version and project path produce
byte-identical JSON (no timestamps, no random ids);
* exposes no private Rust layout, optimization instruction or host pointer.
## 2. Top-level shape
```json
{
"schema": "marqdo.analysis",
"schema_version": 1,
"producer": {"name": "marqdo", "version": "0.1.0", "markdown_profile": "marqdo.md.v1"},
"project": {"root_id": "sha256:...", "lock_digest": "sha256:..."},
"modules": [],
"diagnostics": []
}
```
* `root_id` is a digest of the normalized project root used for this run.
* `lock_digest` is a digest of `marqdo.lock`, or `""` when absent.
* Modules are sorted by canonical `id`; arrays keep source order.
* `schema_version` is a major version. Additive optional fields are allowed;
removing/renaming fields or changing units/types requires a major bump.
## 3. Modules
```json
{
"id": "root:default::index.mq.md",
"package_instance_id": "root:default",
"relative_path": "index.mq.md",
"source_digest": "<sha256 hex>",
"units": [],
"functions": [],
"imports": [],
"references": [],
"calls": [],
"resources": 0
}
```
Module identity is the package-aware `ModuleId` from
`spec/references.md` §2.1. `source_digest` hashes the exact source bytes.
### 3.1 Units
Each unit has `id`, `kind` (`root`/`namespace`/`function`/`section`), `name`,
`level`, `span` (`{start,end}` byte offsets) and optionally `function`.
### 3.2 Functions and signatures
```json
{
"id": "root:default::index.mq.md::数学.阶乘",
"unit_id": "root:default::index.mq.md#数学/阶乘",
"local_name": "阶乘",
"namespace": "数学",
"span": {"start": 0, "end": 100},
"heading_span": {"start": 0, "end": 10},
"signature": {
"kind": "inferred",
"params": [{"name": "n", "required": true, "type": null, "default": null, "span": {"start": 0, "end": 0}}]
},
"effects": ["unknown"],
"body": []
}
```
`kind` is `explicit` or `inferred`. Inferred signatures only accept named
arguments. `effects` is a **conservative** summary; `unknown` is not a proof of
purity. Dynamic ABI/Foreign targets remain unknown unless a descriptor says
otherwise.
### 3.3 Normalized body nodes
Body nodes use a small stable language, never internal IR serialization:
* `literal` (`type`: `int`/`float`/`text`/`bool`/`none`, `value` when present);
* `variable`, `list`, `record`, `member`, `index`;
* `unary` (`not`/`neg`/`pos`) and `binary` (`or`, `and`, `eq`, `ne`, `lt`,
`le`, `gt`, `ge`, `add`, `sub`, `mul`, `div`, `floor_div`, `mod`, `pow`);
* `call` with `callee` and `args`;
* `assign`, `expression`, `call_site`, `branch` (ordered arms), `loop`,
`return`. (`call_site` existed for the pre-RFC link-form block-quote call and
is not produced by the current language; this document is historical.)
Every node carries a byte `span`. Nodes outside the supported public subset
must be marked `unsupported` (future extension), never silently given invented
semantics.
### 3.4 Imports, references and calls
* `imports[]`: `{alias, target, span, resolved}`; `resolved` is a module id or
null. Imports stay explicit.
* `references[]`: Markdown link edges with `{source, url, span, state,
target_module, target_unit}`. `state` is `resolved`, `unresolved` or
`external`; a failed resolution is never disguised as bound.
* `calls[]`: `{function, span, callee, state, target}` where `state` is
`function`, `builtin`, `plugin` or `unresolved`.
Reference edges never execute anything and grant no capability.
## 4. Diagnostics
`diagnostics[]` uses the same stable codes/JSON shape as `marqdo check --json`.
An analysis emitted after a successful check normally has no error diagnostics
(warnings may remain).
## 5. Consumer contract
An independent consumer (Python/Go/JavaScript, without linking Rust crates)
must be able to:
* find a function by `id` and read its signature/body;
* find recursive/forward calls and `ref` edges;
* map every body node back to `source_digest` + byte span;
* reject `schema_version` it does not understand.
`tests/consumers/analysis_consumer.py` is one such black-box consumer and
`crates/cli/tests/analysis_trace.rs` runs it when Python is available.
## 6. Not included
Internal optimization IR, host pointers, plugin handles, proof status and
execution results are deliberately absent. Analysis does not claim that a
document runs successfully or that any function is proved.
-27
View File
@@ -1,27 +0,0 @@
# Marqdo Analysis v3
Analysis v3 extends the public [Analysis v2](analysis-v2.md) contract with
structured loop control. Its envelope keeps `schema: "marqdo.analysis"` and
sets `schema_version: 3`. The writer emits v3 if any emitted function body
contains either new statement, including inside a nested body or an imported
module. Other projects still emit v2. Multi-arm branches fit both versions.
## Statement additions
```json
{"kind": "break", "span": {"start": 30, "end": 37}}
{"kind": "continue", "span": {"start": 39, "end": 49}}
```
Both spans are half-open UTF-8 byte ranges covering the carrier in the
containing module. Walk the enclosing statement bodies to find the nearest
loop. `break` transfers to the statement after that loop. `continue`
transfers to its condition. There are no operands, labels or call edges.
Call and resource projections retain their v2 shapes.
Consumers check the major version before traversing any function body. A v2
reader rejects v3, while a reader that accepts both versions can share its
v2 decoding and add two statement kinds. Trace v2 binds to the version
automatically emitted for the same input via `source.analysis_digest`.
JSON Schema: [analysis-v3.schema.json](schemas/analysis-v3.schema.json).
+21 -46
View File
@@ -1,8 +1,7 @@
# Marqdo Analysis v2
# Marqdo Analysis
Status: **implemented by `marqdo check --emit <path>` (S2); ADR-0022 adds an
additive index target shape.** Supersedes
Analysis v1. v1 was never released; it is kept as history and is not written.
Current public contract for `marqdo check --emit PATH`. Every project emits
`marqdo.analysis` with `schema_version: 3`.
## 1. Invariants
@@ -22,7 +21,7 @@ Analysis v1. v1 was never released; it is kept as history and is not written.
```json
{
"schema": "marqdo.analysis",
"schema_version": 2,
"schema_version": 3,
"producer": {
"name": "marqdo",
"version": "<crate version>",
@@ -99,7 +98,7 @@ conservative summary, not a purity proof).
(`spec/callable-resolution.md` §6): `state` remains
`function`/`builtin`/`plugin`/`unresolved`, and official stdlib aliases such as
`打印` are reported as `function` targets because that is the implementation
that runs. The private `CallBindingTable` is not serialized; Analysis v2's
that runs. The private `CallBindingTable` is not serialized; Analysis's
schema and version are unchanged.
An `assign` node keeps the v1 string `target` for a local rebinding. Addressable
@@ -181,48 +180,24 @@ location exists.
The `code` value is an open, stable string: the current language revision adds
the `sem.*` family (`spec/mapping.md` §8) and removes the old
`markdown.inert_executable` warning. This is a diagnostic-value change, not an
Analysis schema change; `schema_version` stays 2.
`markdown.inert_executable` warning. Diagnostic codes may be added without changing the structure.
## 6. Compatibility
## 6. Loop transfers
* Writers emit `schema_version: 2`. There is no v1 writer and no
`--emit-version` flag; v1 was experimental.
* Consumers must reject unknown `schema_version` values and unknown resource
kinds rather than silently accepting them.
* Changing `root_id`, resource fields, diagnostic fields or the digest
definition is a protocol break requiring a new version and an ADR.
* JSON Schema: `spec/schemas/analysis-v2.schema.json` (Draft 2020-12).
Schema validation is structural; cross-record checks (span inside source,
call targets, digest verification) remain semantic tests.
Conditional arms appear in source order. Both `break` and `continue` are
statements with a `kind` and the half-open UTF-8 `span` of their carrier.
They have no operands or call edges. Walk the enclosing bodies to find
the nearest loop. `break` transfers past that loop and `continue` transfers
to its condition.
## 7. Tests
## 7. Validation
* `analysis_is_deterministic_and_has_stable_semantic_nodes`
* `analysis_v2_identity_is_location_independent`
* `analysis_v2_projects_addressable_formula_and_code_resources`
* `failed_check_removes_stale_analysis`
* `tests/consumers/analysis_consumer.py` (independent Python consumer)
Require exactly `schema: "marqdo.analysis"` and `schema_version: 3` before
traversing the document. The [JSON Schema](schemas/analysis.schema.json)
validates record shapes. Check source digests, spans, ownership and
reference targets separately. Its full branch and loop structure applies
equally to simple projects and imported modules.
## 8. Versioning and future heading metadata
`units[]` keeps its v2 fields and semantics: `id/kind/name/level/span/function`.
The effective core mode and origin of a `section` unit are deliberately **not**
added to v2, and neither are heading annotations.
The language still has exactly two Core Modes (`@exec`/`@knowledge`); unmarked
headings inherit from the nearest ancestor and the root default is Knowledge
(`spec/mapping.md` §1.2, including the H-06 sibling fix). A future declarative,
metadata-only Heading Annotation index is Proposed under
[ADR-0060](../docs/adr/0060-heading-modes-and-extensible-annotations.md) and is
**not implemented in this build**.
When that work ships (target `3.1.x`), it must use a new protocol version
(Analysis v3) or a separate `heading-annotations.v1` sidecar, bound to both the
source digest and the exact Analysis bytes digest; it must not rewrite v2 `units[]`.
Consumers that only know v2 must keep passing the existing schema/version contract,
and must reject an unknown sidecar/v3 version rather than silently ignoring it.
Projects containing structured loop transfers use [Analysis v3](analysis-v3.md).
A v2 projection never contains those transfer statements. Multiple conditional
arms use the existing ordered `branch.arms` array.
Source digests cover the original bytes. Preserve UTF-8 byte offsets for
BOM, CRLF, CJK and emoji. Observation binds to the SHA-256 of the exact
emitted Analysis JSON bytes.
-52
View File
@@ -1,52 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://marqdo.dev/schemas/analysis-v1.schema.json",
"title": "Marqdo Analysis v1",
"type": "object",
"required": ["schema", "schema_version", "producer", "project", "modules", "diagnostics"],
"properties": {
"schema": {"const": "marqdo.analysis"},
"schema_version": {"const": 1},
"producer": {
"type": "object",
"required": ["name", "version", "markdown_profile"],
"properties": {
"name": {"type": "string"},
"version": {"type": "string"},
"markdown_profile": {"const": "marqdo.md.v1"}
},
"additionalProperties": true
},
"project": {
"type": "object",
"required": ["root_id", "lock_digest"],
"properties": {
"root_id": {"type": "string"},
"lock_digest": {"type": "string"}
},
"additionalProperties": true
},
"modules": {
"type": "array",
"items": {
"type": "object",
"required": ["id", "package_instance_id", "relative_path", "source_digest", "units", "functions", "imports", "references", "calls"],
"properties": {
"id": {"type": "string", "pattern": "::"},
"package_instance_id": {"type": "string"},
"relative_path": {"type": "string"},
"source_digest": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
"units": {"type": "array"},
"functions": {"type": "array"},
"imports": {"type": "array"},
"references": {"type": "array"},
"calls": {"type": "array"},
"resources": {"type": "integer", "minimum": 0}
},
"additionalProperties": true
}
},
"diagnostics": {"type": "array"}
},
"additionalProperties": true
}
-103
View File
@@ -1,103 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://marqdo.dev/schemas/analysis-v2.schema.json",
"title": "Marqdo Analysis v2",
"type": "object",
"required": ["schema", "schema_version", "producer", "project", "modules", "diagnostics"],
"properties": {
"schema": {"const": "marqdo.analysis"},
"schema_version": {"const": 2},
"producer": {
"type": "object",
"required": ["name", "version", "markdown_profile"],
"properties": {
"name": {"type": "string"},
"version": {"type": "string"},
"markdown_profile": {"const": "marqdo.md.v1"}
},
"additionalProperties": true
},
"project": {
"type": "object",
"required": ["root_id", "identity_kind", "lock_digest"],
"properties": {
"root_id": {"type": "string", "minLength": 1, "pattern": "^(root:|sha256:[0-9a-f]{64}$)"},
"identity_kind": {"enum": ["manifest", "workspace_snapshot"]},
"lock_digest": {"type": "string", "pattern": "^(sha256:[0-9a-f]{64})?$"}
},
"additionalProperties": true
},
"modules": {
"type": "array",
"items": {
"type": "object",
"required": ["id", "package_instance_id", "relative_path", "source_digest", "units", "functions", "imports", "references", "calls", "resources"],
"properties": {
"id": {"type": "string", "pattern": "::"},
"package_instance_id": {"type": "string", "minLength": 1},
"relative_path": {"type": "string", "minLength": 1, "pattern": "^(?!/)(?!.*\\.\\.)"},
"source_digest": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
"units": {"type": "array"},
"functions": {"type": "array"},
"imports": {"type": "array"},
"references": {"type": "array"},
"calls": {"type": "array"},
"resources": {
"type": "array",
"items": {
"type": "object",
"required": ["id", "module_id", "unit_id", "kind", "span", "content_digest"],
"properties": {
"id": {"type": "string", "pattern": "#resource:(formula|code)-[0-9]+$"},
"module_id": {"type": "string", "pattern": "::"},
"unit_id": {"type": "string", "minLength": 1},
"kind": {"enum": ["formula", "code"]},
"span": {
"type": "object",
"required": ["start", "end"],
"properties": {
"start": {"type": "integer", "minimum": 0},
"end": {"type": "integer", "minimum": 0}
},
"additionalProperties": true
},
"content_digest": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
"language": {"type": ["string", "null"]},
"display": {"type": "boolean"}
},
"additionalProperties": true
}
}
},
"additionalProperties": true
}
},
"diagnostics": {
"type": "array",
"items": {
"type": "object",
"required": ["module", "relative_path", "severity", "code", "message"],
"properties": {
"module": {"type": "string", "pattern": "::"},
"relative_path": {"type": "string", "minLength": 1},
"span": {
"type": ["object", "null"],
"required": ["start", "end"],
"properties": {
"start": {"type": "integer", "minimum": 0},
"end": {"type": "integer", "minimum": 0}
}
},
"line": {"type": ["integer", "null"], "minimum": 1},
"column": {"type": ["integer", "null"], "minimum": 1},
"severity": {"enum": ["error", "warning"]},
"code": {"type": "string", "minLength": 1},
"message": {"type": "string", "minLength": 1},
"hints": {"type": "array", "items": {"type": "string"}}
},
"additionalProperties": true
}
}
},
"additionalProperties": true
}
@@ -1,7 +1,7 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://marqdo.dev/schemas/analysis-v3.schema.json",
"title": "Marqdo Analysis v3",
"$id": "https://marqdo.dev/schemas/analysis.schema.json",
"title": "Marqdo Analysis",
"type": "object",
"required": [
"schema",
+30 -6
View File
@@ -1,17 +1,36 @@
#!/usr/bin/env python3
"""Independent Analysis v2 consumer: no Marqdo/Rust imports."""
"""Independent Analysis consumer: no Marqdo/Rust imports."""
import json
import sys
if len(sys.argv) != 2:
raise SystemExit("usage: analysis_consumer.py ANALYSIS.json")
def visit(body, loop_span=None):
for statement in body:
kind = statement["kind"]
if kind == "loop":
yield from visit(statement["body"], statement["span"])
elif kind == "branch":
for arm in statement["arms"]:
yield from visit(arm["body"], loop_span)
elif kind in ("break", "continue"):
if loop_span is None:
raise SystemExit(f"{kind} outside a projected loop")
span = statement["span"]
if not 0 <= loop_span["start"] < span["start"] < span["end"]:
raise SystemExit(f"invalid {kind} carrier span")
yield kind, loop_span["start"]
elif kind not in ("assign", "expression", "return"):
raise SystemExit(f"unsupported statement kind {kind}")
if sys.argv[2:] not in ([], ["--require-transfers"]) or len(sys.argv) < 2:
raise SystemExit("usage: analysis_consumer.py ANALYSIS.json [--require-transfers]")
with open(sys.argv[1], encoding="utf-8") as handle:
analysis = json.load(handle)
if analysis.get("schema") != "marqdo.analysis":
raise SystemExit("unexpected schema")
if analysis.get("schema_version") != 2:
if analysis.get("schema_version") != 3:
raise SystemExit("unsupported schema_version")
project = analysis["project"]
@@ -21,6 +40,7 @@ if not isinstance(project.get("root_id"), str) or not project["root_id"]:
raise SystemExit("bad root_id")
functions = []
transfers = []
for module in analysis["modules"]:
module_id = module["id"]
if "::" not in module_id or not module_id.startswith(("root:", "dep:", "std:")):
@@ -45,9 +65,13 @@ for module in analysis["modules"]:
if not isinstance(span.get("start"), int) or not isinstance(span.get("end"), int):
raise SystemExit("bad resource span")
for function in module["functions"]:
body = json.dumps(function["body"], ensure_ascii=False)
functions.append((function["id"], body))
transfers.extend(visit(function["body"]))
functions.append(function["id"])
if not functions:
raise SystemExit("no functions")
print("functions=" + str(len(functions)))
if len(sys.argv) == 3 and not transfers:
raise SystemExit("missing loop transfers")
print(f"transfers={len(transfers)}")
-45
View File
@@ -1,45 +0,0 @@
#!/usr/bin/env python3
"""Read loop transfers from public Analysis JSON using only Python."""
import json
import pathlib
import sys
def visit(body, loop_span=None):
for statement in body:
kind = statement["kind"]
if kind == "loop":
yield from visit(statement["body"], statement["span"])
elif kind == "branch":
for arm in statement["arms"]:
yield from visit(arm["body"], loop_span)
elif kind in ("break", "continue"):
if loop_span is None:
raise SystemExit(f"{kind} outside a projected loop")
span = statement["span"]
if not 0 <= loop_span["start"] < span["start"] < span["end"]:
raise SystemExit(f"invalid {kind} carrier span")
yield kind, loop_span["start"]
elif kind not in ("assign", "expression", "return"):
raise SystemExit(f"unsupported statement kind {kind}")
def main():
if len(sys.argv) != 2:
raise SystemExit("usage: analysis_v3_consumer.py ANALYSIS.json")
analysis = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8"))
if analysis.get("schema") != "marqdo.analysis" or analysis.get("schema_version") != 3:
raise SystemExit("unsupported Analysis schema version")
transfers = [
transfer
for module in analysis["modules"]
for function in module["functions"]
for transfer in visit(function["body"])
]
if not transfers:
raise SystemExit("missing loop transfers")
print(f"transfers={len(transfers)} nearest_loops={len({target for _, target in transfers})}")
if __name__ == "__main__":
main()
+1 -1
View File
@@ -13,7 +13,7 @@ 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") not in (2, 3):
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")
+2 -7
View File
@@ -48,19 +48,14 @@ def main():
trace = json.loads(trace_path.read_text(encoding="utf-8"))
tool = json.loads(tool_path.read_text(encoding="utf-8"))
version = analysis.get("schema_version")
if version not in (2, 3):
raise SystemExit("unsupported Analysis schema version")
analysis_schema = f"analysis-v{version}.schema.json"
analysis_schema = "analysis.schema.json"
require_valid(analysis_schema, analysis, "analysis")
if version == 3:
require_invalid("analysis-v2.schema.json", analysis, "legacy schema rejects v3")
require_valid("trace-v2.schema.json", trace, "trace")
require_valid("tool-v1.schema.json", tool, "tool")
# Negative mutations: structure, version and traversal must fail closed.
bad = copy.deepcopy(analysis)
bad["schema_version"] = 999
bad["schema_version"] = 2
require_invalid(analysis_schema, bad, "analysis unsupported version")
bad = copy.deepcopy(analysis)
+3 -8
View File
@@ -68,14 +68,9 @@ class ReleaseArchiveContractTest(unittest.TestCase):
self.assertIn('"stdlib": stdlib_info', source)
self.assertIn("verify_stdlib()", source)
def test_archive_analysis_metadata_preserves_default_and_declares_each_major(self) -> None:
self.smoke.verify_analysis_metadata({"analysis": 2, "analysis_versions": [2, 3]})
for malformed in (
{"analysis": 3, "analysis_versions": [2, 3]},
{"analysis": 2, "analysis_versions": [2]},
{"analysis": 2, "analysis_versions": [2, 3, 4]},
{"analysis": 2},
):
def test_archive_declares_only_current_analysis_revision(self) -> None:
self.smoke.verify_analysis_metadata({"analysis": 3})
for malformed in ({"analysis": 2}, {"analysis": 3, "analysis_versions": [3]}, {}):
with self.subTest(protocols=malformed), contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit):
self.smoke.verify_analysis_metadata(malformed)
+1 -2
View File
@@ -263,8 +263,7 @@ def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict:
"binaries": binaries,
"stdlib": stdlib_info,
"protocols": {
"analysis": 2,
"analysis_versions": [2, 3],
"analysis": 3,
"trace": 2,
"execution_events": 1,
"tool": 1,
+11 -12
View File
@@ -167,17 +167,16 @@ class Runner:
fail(f"`marqdo {' '.join(args)} --json` is not JSON: {error}\n{result.stdout}")
ANALYSIS_VERSION = 3
ANALYSIS_CASES = {
2: ("examples/multi-module/index.mq.md", "analysis_consumer.py"),
3: ("examples/control-flow.mq.md", "analysis_v3_consumer.py"),
"simple": ("examples/multi-module/index.mq.md", ()),
"control": ("examples/control-flow.mq.md", ("--require-transfers",)),
}
def verify_analysis_metadata(protocols: dict) -> None:
if protocols.get("analysis") != min(ANALYSIS_CASES):
fail("RELEASE_INFO.json does not identify the default Analysis version")
if protocols.get("analysis_versions") != sorted(ANALYSIS_CASES):
fail("RELEASE_INFO.json Analysis versions do not match the archive smoke cases")
if protocols.get("analysis") != ANALYSIS_VERSION or "analysis_versions" in protocols:
fail("RELEASE_INFO.json must identify only the current Analysis revision")
def run_consumer(install: Path, consumer: str, *paths: Path) -> None:
@@ -193,17 +192,17 @@ def run_consumer(install: Path, consumer: str, *paths: Path) -> None:
def verify_analysis_protocols(runner: Runner, install: Path, info: dict) -> None:
protocols = info["protocols"]
verify_analysis_metadata(protocols)
for schema_version, (source, consumer) in ANALYSIS_CASES.items():
analysis = install / f"analysis-v{schema_version}.json"
trace = install / f"trace-for-analysis-v{schema_version}.json"
for case, (source, options) in ANALYSIS_CASES.items():
analysis = install / f"analysis-{case}.json"
trace = install / f"trace-for-analysis-{case}.json"
runner.run(["check", source, "--emit", str(analysis)])
document = json.loads(analysis.read_text(encoding="utf-8"))
if document.get("schema") != "marqdo.analysis" or document.get("schema_version") != schema_version:
fail(f"{source} did not produce Analysis v{schema_version}")
if document.get("schema") != "marqdo.analysis" or document.get("schema_version") != ANALYSIS_VERSION:
fail(f"{source} did not produce Analysis revision {ANALYSIS_VERSION}")
if document.get("producer", {}).get("version") != info["product_version"]:
fail("Analysis producer.version does not match the released product version")
runner.run(["run", source, "--trace-file", str(trace)])
run_consumer(install, consumer, analysis)
run_consumer(install, "analysis_consumer.py", analysis, *options)
run_consumer(install, "trace_consumer.py", analysis, trace)
# CI installs jsonschema. The standalone smoke can use stdlib Python.