Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions docs/contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ details, inject credentials securely at runtime and review artifacts for leaks.

`image` is optional for the control CLI and required to run PNG quality tests.
Synthetic benchmark scripts belong in `tests/fixtures/`; historical validator
snapshots in `tests/fixtures/legacy/` remain byte-for-byte frozen. Current runnable
examples are the three Qwen scripts under `examples/`.
snapshots in `tests/fixtures/legacy/` remain byte-for-byte frozen. Current model examples are the three Qwen scripts under `examples/`. The
[CPU external-service walkthrough](../examples/external_service_cpu/README.md)
is a runnable integration example, with its verifier under `tests/repository/`;
it does not qualify a model or measure an accelerator.

Run the [Codex Qwen-Image E2E case](e2e-qwen-image-codex.md) on a prepared
Ascend A2 host to optimize the model and independently measure the delivered patch.
Expand Down
5 changes: 5 additions & 0 deletions docs/guides/service-reuse-campaigns.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ The CLI sends typed operations to `inferrsi.harness.manager.run_session`.
Manager owns the campaign lock, frozen plan and session state. Apps reads these
records to present progress and results.

For a model-free, relocatable CPU walkthrough using an installed core wheel, see
the [external-service example](../../examples/external_service_cpu/README.md). It
checks actual configurations, measurement boundaries, precheck refusal and owned
interruption/cleanup without adding another runner.

## Prepare the protocol

Use the Git checkout root and commit the declared project inputs first. The
Expand Down
135 changes: 135 additions & 0 deletions examples/external_service_cpu/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# CPU external-service integration example

This walkthrough exercises InferRSI's existing public Manager and Executor with a
foreground Python standard-library service on loopback. It needs Git and an
installed InferRSI core package. It needs no model, GPU, credentials, external
endpoint or API account. The integer workload demonstrates integration, not a
model benchmark or a statistically supported performance result.

The scripts contain no InferRSI private imports. `prepare.py` only creates a new
example project, its initial Git commit and a protocol. It never runs a campaign.
`protocol.py` implements the existing service/client protocol. Manager owns the
session, stage order, process domain, recovery and cleanup; there is no new runner.

## Run with an installed package outside the checkout

Use the examples and check script from the same InferRSI source revision as the
installed package. Examples are source files, not files bundled in the core wheel.
Copy this directory and `tests/repository/check_external_service_example.py` to a
scratch directory, then change to that directory. Use a new output path:

```text
python -I check_external_service_example.py external_service_cpu example-output
```

The check calls public `inferrsi.harness.manager` requests. It prepares temporary
Git projects, moves a protocol before starting a session, moves it again after
Manager retains it, evaluates A and B, rejects a separate attempt before service
start, then interrupts an owned service and calls `recover` and `status` without
relaunching it. Successful verification prints a JSON summary and retains
`example-output/verification.json` plus the actual session records. The checker
is an integration test driver, not an alternate campaign implementation.

To prepare the files without executing an attempt:

```text
python external_service_cpu/prepare.py another-new-directory
```

The example Git commits use a synthetic identity only inside these new disposable
projects; no user or repository Git identity is changed. A project must retain
its Git commits while a session runs because the service independently compares
its loaded configuration with `git show <bound-revision>:config.json`.

## Public session entry

A host can start the prepared example directly using the following public APIs.
Replace `example-root` with the prepared directory. Keep campaign output outside
the project and protocol. The commands use the default sequential reference
protocol; they do not request AB/BA or establish paired performance evidence.

```python
import sys
from pathlib import Path

from inferrsi.harness.manager import BaselineSession, StartProjectSession, run_session
from inferrsi.knowledge.ranking_policy import managed_ranking_policy

root = Path("example-root").resolve()
ports = {"ranking_policy_for": managed_ranking_policy, "assess_packaged": None}
# Windows virtual-environment redirectors can introduce a different foreground PID.
# This stdlib-only service can use the base interpreter directly.
service_python = getattr(sys, "_base_executable", sys.executable)
run_session(StartProjectSession(
session=root / "session", repo=root / "project", include=["config.json"],
protocol=root / "protocol", instructions=root / "TASK.md",
evaluation_config=root / "evaluation.json", rounds=2, max_minutes=3,
evaluation_timeout_seconds=30, final_reserve_seconds=15,
condition="CPU example integration only", knowledge="off", python=service_python,
), **ports)
run_session(BaselineSession(session=root / "session"), **ports)
```

The installed CLI uses these same lifecycle components. For interactive project
work use the existing [Intake and CLI workflow](../../docs/guides/task-intake.md),
including its actual task approval; this example does not fabricate an Intake
approval. Do not transplant the checker's disposable project identity or toy
thresholds into a real campaign.

## What the records mean

The baseline commits `label=A, algorithm=loop`; the candidate commits
`label=B, algorithm=formula`. Both compute the exact sum of integer squares for
10,000 terms. `observed_config` in each client result comes from the actual loaded
`config.json`, checked against the bound Git revision. Readiness reports the real
foreground PID and resolved execution workspace. A changed source config or
workload fails the check instead of echoing an expected path as proof.

The `seconds` objective is server-side compute wall time only. Its receipt states
that startup, HTTP, loading, warmup and quality are excluded.
`client_roundtrip_seconds` is a separate observation and is not substituted for
that objective. InferRSI retains startup/stage/cleanup records independently.
Quality checks exact integer equality on this toy workload only. One repetition
and no warmup are deliberate integration-test choices, not recommended benchmark
sampling. Ignore any toy PASS as evidence about H3, GPU capacity or real service
performance.

`allow=false` is a toy functional precheck rejection. The checker requires
`FAIL` / `functional_check_rejected` and a service stage marked
`skipped` / `precheck_rejected`, with no startup PID, start marker or service
receipt, plus verified cleanup. A crashed precheck or a different prelaunch
failure does not qualify as this rejection. GPU admission and account policy
remain adapter/host responsibilities.

## Interruptions and host limits

On Windows, launch the stdlib service with its base Python executable to avoid
virtual-environment launcher/owner-PID ambiguity. This example does not weaken
readiness verification or change the Executor. Target interpreters requiring
additional packages need their own qualified foreground launcher.

The check injects Python's Ctrl+C equivalent after the service publishes its
endpoint, then requires `INCONCLUSIVE` and verified owned cleanup. An operation
can return normally while recording an interrupted assessment; inspect the
assessment, not just a process exit code. The check verifies `recover` and
`status` create no new attempt requests. It does not test a killed controller,
manual cleanup attestation or cross-version resume. Those remain the existing
[#693 recovery contract](https://github.com/InferMatrixLab/InferRSI/pull/693)
and its own regressions. In current ordinary service sessions, the Manager's
`cancellation` argument is not a general substitute for Ctrl+C; its search-mode
use must not be advertised as broader support.

For the full protocol, source binding, reference policy and cleanup budget, see
[service-reuse campaigns](../../docs/guides/service-reuse-campaigns.md) and the
[public Harness entry points](../../src/inferrsi/harness/README.md).

## Source regression

```text
python -m pytest tests/apps/test_external_service_example.py -q
ruff check examples/external_service_cpu tests/apps/test_external_service_example.py tests/repository/check_external_service_example.py
```

Loopback sockets and Windows Job/process-group access must be available. A host
that denies them cannot establish this integration result; do not replace those
checks with mocked cleanup or claim compatibility for an untested host.
126 changes: 126 additions & 0 deletions examples/external_service_cpu/prepare.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
"""Prepare an isolated CPU example. This script never starts a session or service."""

import argparse
import json
import shutil
import subprocess
from pathlib import Path


def prepare(root):
root = Path(root).resolve()
root.mkdir(parents=True, exist_ok=False)
project, protocol = root / "project", root / "protocol"
project.mkdir()
protocol.mkdir()
shutil.copyfile(Path(__file__).with_name("protocol.py"), protocol / "protocol.py")
(project / "config.json").write_text(
json.dumps(
{
"label": "A",
"algorithm": "loop",
"units": 10000,
"allow": True,
}
),
encoding="utf-8",
)
for args in [
["init", "-q"],
["add", "config.json"],
[
"-c",
"user.name=CPU example",
"-c",
"user.email=example@example.invalid",
"-c",
"commit.gpgsign=false",
"commit",
"-qm",
"Initial CPU example",
],
]:
subprocess.run(["git", "-C", str(project), *args], check=True, capture_output=True)
(root / "TASK.md").write_text(
"CPU integration example only. Compare exact integer implementations. "
"No model quality, hardware qualification or service performance claim.",
encoding="utf-8",
)
settings = {
"schema_version": 1,
"protocol_id": "external-cpu-example-v1",
"conditions": {
"id": "cpu-example",
"workload": "integer-sum-squares",
"model": "none",
"precision": "integers",
"topology": "one-local-process",
"runtime": "python-stdlib",
"timing_scope": "server-compute-seconds",
"effective_config": {"units": 10000},
},
"commands": {
stage: [
"{python}",
"{protocol}/protocol.py",
stage,
"{candidate}",
str(project),
"{attempt_dir}/request.json",
"{service_receipt}",
"{result}",
]
for stage in ("precheck", "service", "ready", "warmup", "measure", "quality", "stop")
},
"sampling": {
"stage_timeout_seconds": 8,
**{
role: {
"repetitions": 1,
"warmups": 0,
"warmup_reason": "CPU integration demonstration, no device state",
}
for role in ("baseline", "candidate", "final")
},
},
"scenarios": [
{"id": "sum", "workload": "integer-sum-squares", "requests": 1, "required_successes": 1}
],
"objectives": [
{
"id": "compute",
"scenario": "sum",
"key": "seconds",
"unit": "s",
"domain": {"min": 0, "max": 1e6},
"direction": "minimize",
"aggregate": "median",
"threshold_type": "relative_percent",
"gain": True,
"gain_threshold": 0,
"parent_regression_limit": 0,
"cumulative_regression_limit": 0,
}
],
"ranking": ["compute"],
"stagnation": {"disabled": True},
"reference_guard": {"max_age_seconds": 600},
"quality": {
"mode": "absolute",
"dataset": "integer-sum-squares-v1",
"scorer": "exact-integer-v1",
"unit": "points",
"samples": 1,
"key": "quality",
"direction": "maximize",
"threshold": 1,
},
}
(root / "evaluation.json").write_text(json.dumps(settings, indent=2), encoding="utf-8")
return root


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("directory", type=Path, help="new directory outside the InferRSI checkout")
print(prepare(parser.parse_args().directory))
Loading
Loading