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
44 changes: 31 additions & 13 deletions src/inference_endpoint/commands/benchmark/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@
)
from inference_endpoint.metrics.report import Report
from inference_endpoint.openai.types import requests_multiple_choices
from inference_endpoint.utils.hashing import sha256_file

if TYPE_CHECKING:
from inference_endpoint.async_utils.event_publisher import EventPublisherService
Expand Down Expand Up @@ -1206,14 +1207,28 @@ def _salvage_tmpfs(report_dir: Path, tmpfs_dir: Path) -> None:
logger.debug(f"Copied {src_events} -> {dst_events}")


def _hash_events_log(report_dir: Path) -> str | None:
"""Best-effort SHA-256 of the salvaged events.jsonl.

The digest is optional metadata: an unreadable or missing log is logged and
recorded as None so it can never cost the run its report.
"""
events_path = report_dir / "events.jsonl"
try:
return sha256_file(events_path)
except OSError as e:
logger.warning("Could not fingerprint %s: %s", events_path, e)
return None


def _write_report_artifacts(
ctx: BenchmarkContext, report: Report, profiling: dict[str, Any] | None
) -> None:
"""Display the report and write result_summary.json + report.txt.

result_summary.json is the self-complete machine-readable report (carries
qps/tps/seeds/accuracy via Report.to_json); report.txt is the full
human-readable dump; the console log shows the summary.
qps/tps/seeds and the events.jsonl SHA-256 via Report.to_json); report.txt
is the full human-readable dump; the console log shows the summary.
"""
report.display(fn=lambda s: logger.info(s), summary_only=True)
performance_dir = ctx.report_dir / "performance"
Expand Down Expand Up @@ -1289,21 +1304,23 @@ def finalize_benchmark(ctx: BenchmarkContext, bench: BenchmarkResult) -> None:
report = msgspec.structs.replace(report, complete=False, state="interrupted")
bench.report = report

# Write scoring artifacts + copy event log from tmpfs to disk (scorers read
# sample_idx_map.json + events.jsonl from here).
_write_scoring_artifacts(ctx, result, bench.tmpfs_dir)

# Full-run OSL over every turn, including those issued after the performance
# window closed, plus accuracy scoring. Both run inside the try/finally so a
# Ctrl-C during the (large) event-log scan still writes an interrupted report
# instead of losing it. Skipped on abort: a partial tail would report as
# complete.
# Everything that copies or reads the (possibly large) event log runs inside
# the try/finally, so a Ctrl-C there still writes an interrupted report:
# copying sample_idx_map.json + events.jsonl to report_dir (scorers and the
# full-run OSL read them from there), the log's fingerprint, full-run OSL
# over every turn (including those issued after the performance window
# closed), and accuracy scoring. All but the copy are skipped on abort: a
# partial tail would report as complete, and after the first Ctrl-C the
# next one force-exits, so another full read would only widen that window.
events_sha256: str | None = None
full_run_osl: dict[str, Any] | None = None
accuracy_scores: list[dict[str, Any]] = []
try:
_write_scoring_artifacts(ctx, result, bench.tmpfs_dir)
if aborted:
logger.warning("Run aborted — skipping accuracy scoring on partial data")
else:
events_sha256 = _hash_events_log(ctx.report_dir)
full_run_osl = full_run_osl_for_report(
ctx.report_dir,
ctx.tokenizer_name,
Expand All @@ -1318,13 +1335,14 @@ def finalize_benchmark(ctx: BenchmarkContext, bench: BenchmarkResult) -> None:
bench.report = report
raise
finally:
# Attach the per-dataset accuracy list so result_summary.json, the
# console summary, and report.txt all carry it.
# Build the final report once, so bench.report and every artifact
# written from it carry the same post-hoc fields.
if report is not None:
final_report = msgspec.structs.replace(
report,
accuracy=accuracy_scores,
output_sequence_lengths_full_run=full_run_osl,
events_sha256=events_sha256,
)
_write_report_artifacts(ctx, final_report, bench.profiling)
report = final_report
Expand Down
7 changes: 7 additions & 0 deletions src/inference_endpoint/metrics/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,13 @@ class Report(msgspec.Struct, frozen=True, kw_only=True): # type: ignore[call-ar
# which can differ per audit phase — are deferred to a follow-up.)
run_config: dict[str, Any] | None = None

# SHA-256 (hex) over the bytes of the run's events.jsonl, attached in
# finalize_benchmark after the log is salvaged to report_dir. Content-only,
# so copying or renaming the log does not change it. None on an aborted run
# (not hashed), when the salvaged log could not be read (missing or I/O
# error), or when a Ctrl-C interrupted the hash.
events_sha256: str | None = None

# Per-dataset accuracy entries (one per scored dataset), attached after
# scoring in finalize_benchmark. Accuracy is not in the metrics snapshot, so
# from_snapshot leaves this empty; runs without configured scoring keep it
Expand Down
33 changes: 33 additions & 0 deletions src/inference_endpoint/utils/hashing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Content hashing for run artifacts (e.g. fingerprinting events.jsonl)."""

from __future__ import annotations

import hashlib
from pathlib import Path


def sha256_file(path: Path) -> str:
"""Hex SHA-256 over the bytes of ``path``.

Streamed (``hashlib.file_digest``), so a large file is not read into memory
at once. The digest covers file contents only — never the name or metadata —
so copying or renaming the file leaves it unchanged. Raises ``OSError``
(including ``FileNotFoundError``) if the file cannot be read.
"""
with path.open("rb") as f:
return hashlib.file_digest(f, "sha256").hexdigest()
127 changes: 127 additions & 0 deletions tests/unit/commands/test_benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import asyncio
import dataclasses
import hashlib
import io
import json
import logging
Expand Down Expand Up @@ -3092,6 +3093,132 @@ def test_full_run_osl_gets_the_effective_token_basis(

full_run.assert_called_once_with(tmp_path, None, token_count_source=source)

@pytest.mark.unit
def test_events_sha256_lands_in_summary_and_in_memory_report(self, tmp_path):
"""The digest of the salvaged events.jsonl is on result_summary.json and
on bench.report, so in-memory consumers (run_audit) see the same value."""
content = b'{"event": "COMPLETE"}\n' * 3
config = OfflineConfig(**_OFFLINE_KWARGS)
ctx = _make_benchmark_context(config=config, report_dir=tmp_path)
bench = _make_benchmark_result(tmp_path)
bench.report = self._make_report(state="complete")
tmpfs_events = bench.tmpfs_dir / "events" / "events.jsonl"
tmpfs_events.parent.mkdir(parents=True)
tmpfs_events.write_bytes(content)

finalize_benchmark(ctx, bench)

expected = hashlib.sha256(content).hexdigest()
summary = json.loads(
(tmp_path / "performance" / "result_summary.json").read_text()
)
assert summary["events_sha256"] == expected
assert bench.report is not None
assert bench.report.events_sha256 == expected

@pytest.mark.unit
def test_sigint_during_events_hash_still_writes_report(self, tmp_path, monkeypatch):
"""^C while fingerprinting a large events.jsonl must not lose the
report: the interrupt propagates, and the report lands as interrupted
with no digest."""
config = OfflineConfig(**_OFFLINE_KWARGS)
ctx = _make_benchmark_context(config=config, report_dir=tmp_path)
bench = _make_benchmark_result(tmp_path)
bench.report = self._make_report(state="complete")
monkeypatch.setattr(
execute_mod, "sha256_file", MagicMock(side_effect=KeyboardInterrupt)
)

with pytest.raises(KeyboardInterrupt):
finalize_benchmark(ctx, bench)

summary = json.loads(
(tmp_path / "performance" / "result_summary.json").read_text()
)
assert summary["complete"] is False
assert summary["state"] == "interrupted"
assert summary["events_sha256"] is None
assert (tmp_path / "report.txt").exists()

@pytest.mark.unit
def test_events_hash_oserror_keeps_completed_report(
self, tmp_path, monkeypatch, caplog
):
"""The digest is best-effort metadata: an I/O error while hashing is
logged and recorded as null, and never costs the run its report."""
config = OfflineConfig(**_OFFLINE_KWARGS)
ctx = _make_benchmark_context(config=config, report_dir=tmp_path)
bench = _make_benchmark_result(tmp_path)
bench.report = self._make_report(state="complete")
monkeypatch.setattr(
execute_mod, "sha256_file", MagicMock(side_effect=OSError("EIO"))
)

with caplog.at_level(logging.WARNING):
finalize_benchmark(ctx, bench)

summary = json.loads(
(tmp_path / "performance" / "result_summary.json").read_text()
)
assert summary["state"] == "complete"
assert summary["events_sha256"] is None
assert any(
r.levelno == logging.WARNING
and "Could not fingerprint" in r.getMessage()
and "EIO" in r.getMessage()
for r in caplog.records
)

@pytest.mark.unit
def test_aborted_run_never_fingerprints_the_event_log(self, tmp_path):
"""An aborted run skips the fingerprint, as it skips OSL and scoring:
after the first ^C the next one force-exits the process group, so a
full read of a large log here would widen the window in which a second
^C loses the report. The log itself is still salvaged."""
config = OfflineConfig(**_OFFLINE_KWARGS)
ctx = _make_benchmark_context(config=config, report_dir=tmp_path)
bench = _make_benchmark_result(tmp_path)
bench.report = self._make_report(state="complete")
bench.user_interrupted = True
tmpfs_events = bench.tmpfs_dir / "events" / "events.jsonl"
tmpfs_events.parent.mkdir(parents=True)
tmpfs_events.write_bytes(b'{"event": "COMPLETE"}\n')

finalize_benchmark(ctx, bench)

summary = json.loads(
(tmp_path / "performance" / "result_summary.json").read_text()
)
assert summary["state"] == "interrupted"
assert summary["events_sha256"] is None
assert (tmp_path / "events.jsonl").read_bytes() == tmpfs_events.read_bytes()

@pytest.mark.unit
def test_sigint_during_event_log_salvage_still_writes_report(
self, tmp_path, monkeypatch
):
"""^C while copying a large events.jsonl off tmpfs must not lose the
report: the interrupt propagates, and the report lands as interrupted
with no digest of a partially copied log."""
config = OfflineConfig(**_OFFLINE_KWARGS)
ctx = _make_benchmark_context(config=config, report_dir=tmp_path)
bench = _make_benchmark_result(tmp_path)
bench.report = self._make_report(state="complete")
monkeypatch.setattr(
execute_mod, "_salvage_tmpfs", MagicMock(side_effect=KeyboardInterrupt)
)

with pytest.raises(KeyboardInterrupt):
finalize_benchmark(ctx, bench)

summary = json.loads(
(tmp_path / "performance" / "result_summary.json").read_text()
)
assert summary["complete"] is False
assert summary["state"] == "interrupted"
assert summary["events_sha256"] is None
assert (tmp_path / "report.txt").exists()

@staticmethod
def _make_report(state: str) -> Report:
return Report.from_snapshot(
Expand Down
10 changes: 10 additions & 0 deletions tests/unit/metrics/test_report_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,16 @@ def test_to_json_and_display_carry_run_config(self):
report = Report.from_snapshot(snap, token_count_source=DEFAULT_SOURCE)
assert json.loads(report.to_json())["run_config"] is None

def test_to_json_carries_events_sha256(self):
"""result_summary.json fingerprints the run's events.jsonl. The digest is
attached post-hoc (like accuracy), so from_snapshot leaves it null and it
serializes as null until set."""
report = _build_report(_make_registry(n_samples=5))
assert json.loads(report.to_json())["events_sha256"] is None

stamped = msgspec.structs.replace(report, events_sha256="deadbeef")
assert json.loads(stamped.to_json())["events_sha256"] == "deadbeef"

def test_to_json_save(self, tmp_path: Path):
registry = _make_registry(n_samples=5)
report = _build_report(registry)
Expand Down
62 changes: 62 additions & 0 deletions tests/unit/utils/test_hashing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tests for the content-only file SHA-256 helper."""

from __future__ import annotations

import hashlib
from pathlib import Path

import pytest
from inference_endpoint.utils.hashing import sha256_file


@pytest.mark.unit
class TestSha256File:
"""Content-only SHA-256 of a file (used to fingerprint events.jsonl)."""

def test_hashes_contents_only(self, tmp_path: Path):
"""The digest is over file bytes alone, so the same content under a
different name (a copy/rename) hashes identically and matches a plain
hashlib digest of those bytes."""
content = b'{"event": "COMPLETE"}\n' * 4
a = tmp_path / "events.jsonl"
b = tmp_path / "events_renamed.jsonl"
a.write_bytes(content)
b.write_bytes(content)

expected = hashlib.sha256(content).hexdigest()
assert sha256_file(a) == expected
assert sha256_file(b) == expected

def test_differs_when_content_differs(self, tmp_path: Path):
a = tmp_path / "a.jsonl"
b = tmp_path / "b.jsonl"
a.write_bytes(b"one")
b.write_bytes(b"two")
assert sha256_file(a) != sha256_file(b)

def test_missing_file_raises(self, tmp_path: Path):
"""A missing file is an error the caller decides how to handle, not a
sentinel the helper picks for every caller."""
with pytest.raises(FileNotFoundError):
sha256_file(tmp_path / "nope.jsonl")

def test_empty_file_has_a_digest(self, tmp_path: Path):
"""An empty log is distinct from no log: it hashes to the empty digest."""
path = tmp_path / "empty.jsonl"
path.write_bytes(b"")
assert sha256_file(path) == hashlib.sha256(b"").hexdigest()
Loading