Skip to content

[ROCm] Add provider lock and execution checks - #622

Merged
Flink-ddd merged 8 commits into
RL-Align:test-qwennextfrom
Anoymoguy:feat/rocm-strict-provider-manifest-draft
Nov 20, 2026
Merged

Flink-ddd merged 8 commits into
RL-Align:test-qwennextfrom
Anoymoguy:feat/rocm-strict-provider-manifest-draft

Conversation

@Anoymoguy

@Anoymoguy Anoymoguy commented Oct 28, 2026 •

Copy link
Copy Markdown

Related to #428.

Adds a provider manifest shared by operator adapters. It pins checkpoint/provider identity, kernel settings and reduction rules, checks each resolved call before launch, and validates worker records against a predeclared run. Operator-specific state layouts stay in their adapters.

Tested on Windows with CPU-only PyTorch:

  • Mock attention, GEMM and MoE calls use the same rollout/replay interface. Three operators can also share one session while keeping separate bindings and call records.
  • A different ROCm architecture, HIP runtime, driver or build identity rejects the worker binding. GPU-profile calls require an explicit completion callback.
  • Unapproved kernel settings or changed dispatch metadata prevent launch; weight updates invalidate old prepared calls.
  • Missing workers/layers, mismatched input/state context, incomplete calls and stale reports reject validation. Checkpoint fingerprints detect changed bytes even with unchanged file size and timestamps.

All 150 manifest tests passed using real files and mocked dispatch/completion. Existing dispatch, registry and attention/logprob tests had 138 passes; one transport test was skipped because it requires a ROCm device and aiter.ops.mha. Ruff and whitespace checks passed.

The earlier layout run had five Windows failures (link flags, symlink permissions, GBK decoding, CRLF hashes) in unchanged files; it was not rerun.

Remaining work: actual ROCm dispatch/load checks and VIME hooks are not connected. CLI enforce rejects execution. GPU numerical parity is untested; graph and full-model acceptance are unsupported. The diff contains implementation and tests only.

@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 53d52d10-74eb-47ab-a853-4c5029e1702d

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Tip

🎯 Customize your risk assessments

Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using Merge Risk Instructions and Security Risk Instructions in your review settings. Security architecture risk assessments require the Advanced plan or above.

✅ Automatic approvals, with your rules

Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable Automatic approvals in review settings, with overrides for teams or file paths.

Remove the serialized CPU output comparator and numerical-policy CLI/schema fields. Bind call evidence to predeclared input/state context and keep numerical and hardware acceptance explicitly unevaluated.

Signed-off-by: Anoymoguy <[email protected]>
@Anoymoguy Anoymoguy changed the title [ROCm] Add strict provider manifest core and GDN candidate observations [ROCm] Add strict provider identity and execution provenance checks Oct 29, 2026
@Anoymoguy Anoymoguy changed the title [ROCm] Add strict provider identity and execution provenance checks [ROCm] Add strict provider manifest core Oct 29, 2026
@Anoymoguy Anoymoguy changed the title [ROCm] Add strict provider manifest core [ROCm] Add provider lock and execution checks Oct 29, 2026
@Anoymoguy
Anoymoguy marked this pull request as ready for review October 30, 2026 01:57
@Flink-ddd Flink-ddd added platform: rocm Specific tasks specific to AMD graphics cards (such as CK, bpreshuffle/FA) qwen labels Oct 30, 2026
@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

🔍 OpenCodeReview found 7 issue(s) in this PR.

  • ✅ Successfully posted inline: 0 comment(s)
  • 📋 Routed to summary by policy: 7 comment(s)

⚠️ 4 warning(s) occurred during review.


bug · medium

📄 rl_engine/integrations/common/provider_observer.py (L146-L148)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity medium · category bug)

wait_completed() treats an absent completion callback as an unconditional synchronous success. The class cannot distinguish an intentionally synchronous adapter from one that simply forgot the callback, and the only external gate (StrictProviderSession.execute) checks completion only for rocm/cuda platform kinds (requires_completion = self.lock.platform["kind"] in ("rocm", "cuda") ...). For async providers on other accelerators (e.g. MUSA/Ascend GPUs) an omitted callback silently reports completed while the launch may still be pending, so downstream consumes incomplete output or frees state early. Require an explicit synchronous declaration instead of inferring it from a missing callback.

💡 Suggested Change

Before:

    def wait_completed(self, output: Any) -> Mapping[str, Any]:
        if self._completion_callback is None:
            return {"kind": "synchronous", "status": "completed"}

After:

    def wait_completed(self, output: Any) -> Mapping[str, Any]:
        if self._completion_callback is None:
            if not self._declared_synchronous:
                raise StrictProviderError(
                    "unobservable_completion",
                    "Provider did not declare synchronous execution or supply a completion check",
                    field="completion",
                    expected="callback_or_declared_synchronous",
                    observed=None,
                )
            return {"kind": "synchronous", "status": "completed"}

maintainability · low

📄 rl_engine/integrations/common/provider_observer.py (L143-L144)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

launch() is not tied to claim() and is not guarded against re-invocation, so the class does not itself enforce the "single-use" dispatch its docstring advertises. A caller that skips claim() or calls launch() twice still dispatches the provider (duplicate side effects / resource use) without any error. The current StrictProviderSession happens to call claim() before launch(), but that sequencing lives entirely in the caller. Gate launch() on a consumed-and-not-yet-launched state so the invariant holds at the object boundary.

💡 Suggested Change

Before:

    def launch(self) -> Any:
        return self._launch_callback()

After:

    def launch(self) -> Any:
        with self._lock:
            if not self._claimed:
                raise StrictProviderError(
                    "unclaimed_call",
                    "Dispatch must be claimed before launch",
                    field="resolved_call.claimed",
                    expected=True,
                    observed=False,
                )
            if self._launched:
                raise StrictProviderError(
                    "call_reused",
                    "Resolved call was already launched",
                    field="resolved_call.launched",
                    expected=False,
                    observed=True,
                )
            self._launched = True
        return self._launch_callback()

bug · medium

📄 rl_engine/validation/common/strict_provider.py (L380-L384)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity medium · category bug)

required indexes ["bindings"][role] for both rollout and replay on every scope node. ProviderLock only requires bindings.keys() == allowed_plans.keys() and does NOT require both roles, and _expected_calls only checks that scope nodes exist in lock["nodes"], not that each role binding is present. A valid lock that declares only one role (e.g. only rollout) for a node therefore reaches this comprehension and raises an unhandled KeyError instead of a stable StrictProviderError. Guard the lookup and reject cleanly.

💡 Suggested Change

Before:

    required = {
        lock.to_dict()["nodes"][node]["bindings"][role]["artifacts_ref"]
        for node in expectation["scope"]["required_nodes"]
        for role in ("rollout", "replay")
    }

After:

    required = set()
    lock_nodes = lock.to_dict()["nodes"]
    for node in expectation["scope"]["required_nodes"]:
        for role in ("rollout", "replay"):
            binding = lock_nodes[node]["bindings"].get(role)
            if binding is None:
                _reject(
                    "missing_artifact_evidence",
                    "Lock lacks a required role binding",
                    f"nodes.{node}.bindings.{role}",
                )
            required.add(binding["artifacts_ref"])

bug · low

📄 rl_engine/validation/common/strict_provider.py (L591-L593)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category bug)

report.get("cases", []) is iterated without validating its type. The artifact is untrusted JSON, so cases can be a dict/int/string; iterating a dict yields string keys and record.get(...) then raises AttributeError, and a scalar raises TypeError. Callers of validate_run (library/Bundle.validate), which expect StrictProviderError, instead receive an unrelated exception instead of a deterministic rejection.

💡 Suggested Change

Before:

        if report.get("schema_version") != CASES_SCHEMA:
            _reject("invalid_case_results", "Unknown case report schema")
        for record in report.get("cases", []):

After:

        if report.get("schema_version") != CASES_SCHEMA:
            _reject("invalid_case_results", "Unknown case report schema")
        records = report.get("cases")
        if not isinstance(records, list):
            _reject("invalid_case_results", "Case report must contain a list of cases")
        for record in records:
            if not isinstance(record, dict):
                _reject("invalid_case_results", "Case report entry must be an object")

bug · medium

📄 rl_engine/runtime/provenance/provider_identity.py (L248-L250)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity medium · category bug)

Refresh evidence is only checked for existence/non-emptiness: the digest returned by read_refreshed_component is recorded in content_digest but never compared against an expected value (unlike expected_shard_digests). A stale or wrong post-refresh cache therefore still yields cache_refresh_complete=True with evidence_kind="worker_load", giving false "refresh verified" assurance to downstream consumers that only look at the completion flags. Consider accepting expected digests for refreshed components (or deriving them from the shard expectations) and raising StrictProviderError("loaded_content_mismatch") on mismatch.


bug · medium

📄 rl_engine/runtime/provenance/provider_identity.py (L161-L163)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity medium · category bug)

resolve(strict=True) is called outside any try/except here (and similarly Path(root).resolve(strict=True) at the start of file_inventory and checkpoint_identity). If the extension artifact has been deleted/evicted or the root does not exist, these raise a raw FileNotFoundError/OSError instead of the documented StrictProviderError (identity_unavailable / unsafe_artifact_path). Strict-mode callers that only catch StrictProviderError will miss it and lose the structured error code, so the resolution should be wrapped and re-raised as StrictProviderError, matching _relative_file's behavior.


bug · low

📄 rl_engine/runtime/provenance/provider_identity.py (L81-L84)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category bug)

size is taken from a fresh resolved.stat() after hash_file returns, i.e. outside the concurrent-change guard inside hash_file (which compares st_dev/st_ino/st_size/st_mtime_ns before and after reading). A file replaced between the hash and this stat produces an inventory record whose size does not correspond to the hashed bytes, making the entry internally inconsistent. Consider having hash_file return the verified size (captured from the guarded fstat) and use it here.


⚠️ Warnings:

  • rl_engine/integrations/common/provider_observer.py,tests/integrations/common/test_strict_provider_observer.py (review_limit_reached): reached the aggregate token budget before finishing; the grace round completed the task
  • tools/validation/strict_provider_manifest.py (token_budget_reached): stopped dispatch: used 620587 tokens + group estimate 74528 = projected 695115 exceeds budget 500000
  • rl_engine/contracts/strict_provider.py,rl_engine/runtime/strict_provider.py,rl_engine/validation/common/strict_provider.py,tests/contracts/test_strict_provider.py,tests/helpers/strict_provider.py,tests/runtime/test_strict_provider.py,tests/validation/common/test_strict_provider.py (review_limit_reached): reached the aggregate token budget before finishing; the grace round did not complete the task
  • rl_engine/runtime/provenance/provider_identity.py,tests/runtime/test_provider_identity.py (review_limit_reached): reached the aggregate token budget before finishing; the grace round did not complete the task

Comment on lines +68 to +72
for index, value in enumerate(argv):
if value.startswith(option + "="):
output = Path(value.split("=", 1)[1])
elif value == option and index + 1 < len(argv):
output = Path(argv[index + 1])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
This pre-parse scan matches only the exact option spelling but argparse accepts unique prefixes (--in, --out, etc.) with the default allow_abbrev=True. Any abbreviated --input/--output defeats both the same-file guard and the pre-run invalidation, allowing the input file to be overwritten or a stale passed result to persist. Either set allow_abbrev=False on the parser (preferred, so the early scan and argparse agree) or make the scan resolve abbreviations consistently.

"hardware_validation": "not_evaluated",
},
)
parser = _Parser(description=__doc__)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
argparse defaults to allow_abbrev=True, but _early_path only recognizes the full --input/--output spellings. Two concrete data-loss/false-pass triggers result:

  1. --in foo.json --output foo.json: the early scan finds --output but not the abbreviated --input, so early_input is None and the same-file guard is skipped. _write_atomic(output, {..."incomplete"...}) then overwrites the user's input evidence with a placeholder before parsing. The post-parse equality check fires afterwards, but the input is already destroyed (contradicting test_same_input_and_output_is_rejected_without_destroying_input).
  2. --input foo.json --out foo.json: the early scan misses --out, so no invalidation happens; after parsing, output = args.output equals the input, the equality check raises, and the failure handler writes a failed result over the input file.

Similarly, --out result.json skips the early "incomplete" invalidation entirely, so a prior manifest_enforcement:"passed" result survives a killed run and can be falsely accepted downstream.

Disabling abbreviation fixes both the destruction and staleness paths.

Suggestion:

Suggested change
parser = _Parser(description=__doc__)
parser = _Parser(description=__doc__, allow_abbrev=False)

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

@Anoymoguy The automated OCR review has completed.

Please review and address all automated review bot findings, then push your updates. Maintainers will begin manual review after the bot findings have been addressed.

@Flink-ddd Flink-ddd left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also fix the failing lint check.

def main(argv: list[str] | None = None) -> int:
argv = list(sys.argv[1:] if argv is None else argv)
output = _early_path(argv, "--output")
try:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please validate the input and output paths before any write. --in evidence.json --output evidence.json overwrites the input, even with allow_abbrev=False. Please add a regression test for this case.

@maxiaosong1124 maxiaosong1124 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

platform: rocm Specific tasks specific to AMD graphics cards (such as CK, bpreshuffle/FA) qwen

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants