Skip to content
Open
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
2 changes: 2 additions & 0 deletions .github/workflows/validation-catalog-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ on:
- test_validation_scanner_usage.py
- rustfs-scanner-usage-test.sh
- scripts/validation_scanner_usage/**
- testdata/scanner-usage/**
- docs/scanner-usage-validation.md
- .github/workflows/validation-catalog-tests.yml
push:
Expand Down Expand Up @@ -160,6 +161,7 @@ on:
- test_validation_scanner_usage.py
- rustfs-scanner-usage-test.sh
- scripts/validation_scanner_usage/**
- testdata/scanner-usage/**
- docs/scanner-usage-validation.md
- .github/workflows/validation-catalog-tests.yml

Expand Down
5 changes: 1 addition & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,7 @@ cases use single-disk
deployment. The scanner case uses the storage suite's single-node four-disk
deployment, waits for a post-upload successful scanner cycle, and requires a
complete usage snapshot with exactly 20 objects and 20,690 logical bytes.
The separate `scanner-usage-regressions` module adds USAGE-01 through USAGE-20
without changing that strict smoke test or the 158 source catalog cases.
Run it explicitly with `rustfs-scanner-usage-test.sh` against existing endpoints;
see [the usage regression contracts and evidence requirements](docs/scanner-usage-validation.md).
The `scanner-usage-regressions` module includes endpoint probes, native scanner tests and USAGE-22, which checks Helm checkpoint recovery in a disposable Kubernetes namespace. Select a case with `rustfs-scanner-usage-test.sh`. [Scanner usage cases and prerequisites](docs/scanner-usage-validation.md).
Public observations cannot prove internal ACK ordering or cross-cycle races,
so missing candidate-native hooks remain BLOCKED or UNSUPPORTED.
The endpoint-only usage runner records operator-supplied candidate and binary
Expand Down
27 changes: 21 additions & 6 deletions docs/scanner-usage-validation.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
# Scanner usage regression suite

This suite registers the twenty USAGE acceptance contracts from backlog issue #3178 and the local-drive retirement regression from rustfs/rustfs#9469. It implements public probes and a strict adapter for candidate-native tests. Registration alone is not test implementation or acceptance: each native assertion needs an executable, reviewed candidate binding before the complete case is available.
It runs against **explicitly configured endpoints**. It never installs RustFS,
changes scanner settings, restarts a node, acquires a VM deployment lock, or
deletes system metadata. It creates random `usage-<run-id>-*` buckets and deletes
only buckets that this invocation successfully created. `owned-buckets.json`
This suite registers the twenty USAGE acceptance contracts from backlog issue #3178, the local-drive retirement regression from rustfs/rustfs#9469 and the Helm checkpoint restore regression from rustfs/rustfs#9672. Native assertions require an executable candidate binding. USAGE-22 runs in its own Kubernetes namespace.

The public S3 probes run against **explicitly configured endpoints**. They leave the deployment, scanner settings, nodes, VM locks and system metadata alone. They create random `usage-<run-id>-*` buckets and delete only buckets that this invocation successfully created. `owned-buckets.json`
retains the exact names and create intents if cleanup fails. A separate
`acknowledged-requests.jsonl` appends each acknowledged PUT and DELETE without
rewriting previous requests. An unacknowledged create remains in `unconfirmed_creates` and forces
Expand Down Expand Up @@ -91,6 +89,22 @@ duration and error. That duration includes AWS CLI startup. It is **not** a
saturation benchmark or a matched A/B throughput claim; its comparison/native
assertion remains blocked without the corresponding evidence.

## Helm checkpoint restore (USAGE-22)

Run this case with Helm, kubectl, `rc`, a packaged RustFS chart and an explicitly selected disposable Kubernetes context. The chart's image must match the candidate manifest. The runner checks the SHA-256 of the running binary.

```bash
bash rustfs-scanner-usage-test.sh \
--cases USAGE-22 --helm-chart ./rustfs-1.0.7.tgz --kube-context kind-usage \
--candidate-manifest ./candidate.json --artifacts-dir ./usage-22-results
```

For the four-argument canonical runner, select `scanner.usage-22-helm-checkpoint-restore` and export `RUSTFS_USAGE_HELM_CHART` and `RUSTFS_USAGE_KUBE_CONTEXT`.

The case starts the standalone chart's pod spec in a new namespace. An init container seeds its data volume with a 2,085,052-byte paged checkpoint and one 16-byte object. The checkpoint describes 4,096 old entries and the disk has no published usage snapshot. The RustFS process runs as non-root with a read-only root and the chart's own temporary mounts. The case passes when the Admin API publishes a complete, converged snapshot with exactly one object and 16 bytes at both bucket and cluster level. The runner deletes the test namespace on exit.

The [seed archive](../testdata/scanner-usage/paged-checkpoint-1.0.7.tgz) was written by RustFS 1.0.7. To rebuild it, append the [fixture generator](../testdata/scanner-usage/generate_checkpoint.rs) to `crates/scanner/src/scanner/tests/paged_checkpoint.rs` in a scratch checkout of that tag. Set `USAGE_22_OUTPUT` to a new directory and run `cargo test --locked -p rustfs-scanner --lib -- scanner::tests::paged_checkpoint::seed_helm_checkpoint_restore --exact --nocapture`. From `$USAGE_22_OUTPUT/pool0/disk0`, archive only `.rustfs.sys/format.json`, `.rustfs.sys/pool.bin`, `.rustfs.sys/pool.bin.identity`, `.rustfs.sys/buckets/bucket` and `bucket/item`. Each new fixture has its own disk and bucket identities. When replacing the archive, update its SHA-256 in `scripts/validation_scanner_usage/helm_checkpoint.py` and rerun both charts.

## Native capability adapter

Public APIs cannot prove a scanned frontier, a budget-stop reason, an epoch
Expand Down Expand Up @@ -169,7 +183,7 @@ covers only A01; A02 through A08 still need their own reviewed tests and markers

## Acceptance mapping

The public-probe column identifies executable probes in this repository. The additional-evidence column states the remaining contract, not a claim that a native test already implements it. USAGE-01 and USAGE-20 have complete public probes; every other case requires candidate-native implementation and bindings for all of its native assertions. A missing binding is an implementation/integration gap even when the report correctly records BLOCKED or UNSUPPORTED.
The public-probe column identifies executable probes in this repository. USAGE-01 and USAGE-20 have complete endpoint probes. USAGE-22 uses a disposable Kubernetes context. The other cases need candidate-native bindings for their native assertions. A missing binding leaves the case BLOCKED or UNSUPPORTED.

| Design case | Public probe | Additional native or controlled-fleet evidence |
| --- | --- | --- |
Expand All @@ -194,6 +208,7 @@ The public-probe column identifies executable probes in this repository. The add
| USAGE-19 | None | Quota v1/v2 and legacy fallback decisions |
| USAGE-20 | Object/prefix collision, versions, markers and payloads | Marker-only keys remain an explicit follow-up fixture |
| USAGE-21 | None | Local wrapper identity at distributed startup, recovery after retirement and exact durable totals |
| USAGE-22 | Read the first converged usage after a large checkpoint restore | Standalone Helm pod, read-only root and a seeded data volume |

Bind `USAGE-21-A01` to `scanner_io::tests::local_drive_recovery::issue_9469_recovers_retired_wrapper_before_first_object` in the candidate's `rustfs-scanner` test binary. The test replaces the retired wrapper with one that has the same persisted format identity. It requires two total attempts, reloads a completed bucket cache with three objects and 21 logical bytes, and emits the cleanup milestone after removing its temporary data.

Expand Down
4 changes: 3 additions & 1 deletion scripts/validation_scanner_usage/contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ def design_id(self):
Case(21, "retired-local-drive", "Recover a local drive retired before the first object", None, (
("native", "After the local wrapper retires before the first object, the scanner retries once on the current wrapper with the same format identity and persists a complete cache with exact object and byte totals."),
("native", "Distributed erasure startup keeps the registered local drive's scan token active and retires only a distinct input wrapper that it replaces."))),
Case(22, "helm-checkpoint-restore", "Publish usage after a large checkpoint restore with a read-only root", None, (
("helm", "The chart's non-root container restores a paged checkpoint larger than 1 MiB and publishes a fresh snapshot matching the fixture's one object and 16 logical bytes."),)),
)


Expand All @@ -131,7 +133,7 @@ def catalog_module() -> dict:
"target_environments": ["configured-endpoint", "native-test"],
"required_capabilities": ["explicit-endpoint", "candidate-provenance"],
"cases": [{"id": case.id, "source_status": "procedure-ready", "priority": "P1",
"channels": ["admin-api", "s3-api", "native-test"],
"channels": ["admin-api", "kubernetes"] if case.number == 22 else ["admin-api", "s3-api", "native-test"],
"assertions": [text for _, text in case.assertions],
"probes": {"designCode": case.design_id,
"procedure": "docs/scanner-usage-validation.md",
Expand Down
134 changes: 134 additions & 0 deletions scripts/validation_scanner_usage/helm_checkpoint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
"""Exercise #9672 in a RustFS pod rendered from the chart under test."""

import json
from pathlib import Path
import secrets
import tempfile
import time

from .client import ProbeError, bucket_view, integer, run_command, sha256


FIXTURE = Path(__file__).resolve().parents[2] / "testdata/scanner-usage/paged-checkpoint-1.0.7.tgz"
FIXTURE_SHA256 = "ed05a2399315ae1dfc0b27d93b412f61ebd0bcedf33e869dc8bf4bd40dc2dca6"


def command(args, timeout=30):
result = run_command(args, timeout)
if result["timed_out"]:
raise ProbeError(f"{args[0]} timed out after {timeout}s")
if result["exit_code"] != 0:
raise ProbeError(f"{args[0]} failed: {result['stderr'][-1000:]}")
return result["stdout"]


def check_snapshot(snapshot):
if not isinstance(snapshot, dict):
raise ProbeError("Admin returned an invalid data usage snapshot", "FAIL")
bucket = bucket_view(snapshot, "bucket")
totals = (snapshot.get("objects_total_count"), snapshot.get("objects_total_size"))
return (bool(snapshot.get("last_update")) and integer(snapshot.get("scanner_cycle"))
and bucket["converged"] and (bucket["count"], bucket["size"]) == (1, 16)
and all(integer(value) for value in totals) and totals == (1, 16))


def run(options, provenance, evidence, cleanup):
if options.execution == "native" or not options.helm_chart or not options.kube_context:
raise ProbeError("USAGE-22 requires --helm-chart and --kube-context for a disposable Kubernetes cluster", "BLOCKED")
chart = options.helm_chart.resolve(strict=True)
if not chart.is_file():
raise ProbeError("--helm-chart must name a packaged RustFS chart")
if sha256(FIXTURE) != FIXTURE_SHA256:
raise ProbeError("The seed archive differs from the verified 2,085,052-byte checkpoint fixture")
namespace = "usage-22-" + secrets.token_hex(10)
kube = ["kubectl", "--context", options.kube_context]
namespaced = [*kube, "--namespace", namespace]
evidence.save("fixture-inputs", {
"namespace": namespace, "context": options.kube_context, "chart_sha256": sha256(chart),
"seed_sha256": FIXTURE_SHA256, "checkpoint_bytes": 2085052,
})
cleanup.update(status="FAIL", namespace=namespace, context=options.kube_context, creation_confirmed=False)
command([*kube, "create", "namespace", namespace])
cleanup["creation_confirmed"] = True
try:
with tempfile.TemporaryDirectory() as scratch:
install_pod(namespaced, chart, namespace, Path(scratch))
command([*namespaced, "wait", "--for=condition=Ready", "pod/rustfs", "--timeout=180s"], 190)
pod = json.loads(command([*namespaced, "get", "pod", "rustfs", "-o", "json"]))
app = rustfs_container(pod["spec"])
execute = [*namespaced, "exec", "rustfs", "-c", "rustfs", "--"]
uid = int(command([*execute, "id", "-u"]).strip())
if app.get("securityContext", {}).get("readOnlyRootFilesystem") is not True or uid <= 0:
raise ProbeError("The RustFS container must run as non-root with a read-only root filesystem", "FAIL")
binary = command([*execute, "sha256sum", "/usr/bin/rustfs"]).partition(" ")[0]
if binary != provenance["binary_sha256"]:
raise ProbeError("The running RustFS binary differs from the candidate manifest")
request = ('exec curl --noproxy "*" -fsS --max-time 10 --aws-sigv4 aws:amz:us-east-1:s3 '
'--user "$RUSTFS_ACCESS_KEY:$RUSTFS_SECRET_KEY" http://127.0.0.1:9000/rustfs/admin/v3/datausageinfo')
deadline = time.monotonic() + options.convergence_timeout
while True:
snapshot = json.loads(command([*execute, "sh", "-ec", request]))
logs = command([*namespaced, "logs", "rustfs", "-c", "rustfs", "--tail=150"])
for line in logs.splitlines():
if "Read-only file system" in line and "cache" in line.lower() and "scanner" in line.lower():
evidence.save("restore-error", {"message": line, "snapshot": snapshot})
raise ProbeError("Scanner cache restore failed with a read-only filesystem", "FAIL")
if check_snapshot(snapshot):
return evidence.save("published-usage", {
"image": app["image"], "binary_sha256": binary, "uid": uid,
"read_only_root": True, "snapshot": snapshot,
})
remaining = deadline - time.monotonic()
if remaining <= 0:
evidence.save("last-usage", snapshot)
raise ProbeError("Scanner did not publish the fixture's exact object and byte totals", "FAIL")
time.sleep(min(options.poll_interval, remaining))
finally:
try:
command([*kube, "delete", "namespace", namespace, "--timeout=120s"], 130)
except (OSError, ProbeError) as exc:
raise ProbeError(f"Could not remove fixture namespace {namespace}: {exc}", cleanup_status="FAIL") from exc
cleanup["status"] = "PASS"


def rustfs_container(spec):
for container in spec.get("containers", []):
if container.get("name") == "rustfs":
return container
raise ProbeError("The rendered workload is missing the RustFS container")


def install_pod(kube, chart, namespace, scratch):
# Keep the chart's RustFS command, security context and /tmp wiring. Only
# /data is seeded, before the server starts and before any usage snapshot exists.
data_mount = {"name": "fixture-data", "mountPath": "/data"}
values = {
"mode": {"standalone": {"enabled": True}, "distributed": {"enabled": False}},
"config": {"rustfs": {
"obs_log_directory": "",
"scanner": {"speed": "fastest", "cycle_secs": "2", "start_delay_secs": "1"},
}},
"storageclass": {"dataStorageSize": ""},
"serviceAccount": {"create": False},
"secret": {"rustfs": {"access_key": "usage-fixture", "secret_key": secrets.token_hex(24)}},
"extraVolumes": [{"name": "fixture-data", "emptyDir": {}}],
"extraVolumeMounts": [data_mount],
}
values_file = scratch / "values.json"
values_file.write_text(json.dumps(values))
render = ["helm", "template", "rustfs", str(chart), "--namespace", namespace, "-f", str(values_file)]
manifest = scratch / "rendered.yaml"
manifest.write_text(command([*render, "-s", "templates/configmap.yaml", "-s", "templates/secret.yaml"]))
command([*kube, "create", "-f", str(manifest)])
command([*kube, "create", "configmap", "checkpoint", f"--from-file=disk.tgz={FIXTURE}"])
manifest.write_text(command([*render, "-s", "templates/deployment.yaml"]))
deployment = json.loads(command([*kube, "create", "--dry-run=client", "-f", str(manifest), "-o", "json"]))
spec = deployment["spec"]["template"]["spec"]
app = rustfs_container(spec)
spec["volumes"].append({"name": "checkpoint", "configMap": {"name": "checkpoint"}})
spec.setdefault("initContainers", []).append({
"name": "seed-checkpoint", "image": app["image"], "securityContext": app.get("securityContext", {}),
"command": ["tar", "--no-same-owner", "-xzf", "/seed/disk.tgz", "-C", "/data"],
"volumeMounts": [data_mount, {"name": "checkpoint", "mountPath": "/seed", "readOnly": True}]})
manifest.write_text(json.dumps({"apiVersion": "v1", "kind": "Pod", "metadata": {"name": "rustfs"}, "spec": spec}))
command([*kube, "create", "-f", str(manifest)])
Loading