diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 28e6104..ea7778d 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -170,6 +170,7 @@ jobs: - name: Test command, progress and parser compatibility run: >- python -m pytest -q + src/regshape/tests/test_request_report_cli.py src/regshape/tests/test_request_report.py src/regshape/tests/test_telemetry_log_file.py src/regshape/tests/test_version.py diff --git a/docs/library/telemetry.md b/docs/library/telemetry.md index 3cba7da..fd6e02b 100644 --- a/docs/library/telemetry.md +++ b/docs/library/telemetry.md @@ -80,11 +80,96 @@ The Click-only `telemetry_options` decorator lives in `regshape.cli.telemetry`, not in the library. It maps the existing six [telemetry options](../../specs/telemetry-enhancements.md#8-updated-cli-flags) and root `--log-file` value into a library session. Option names, defaults, -output formats and exit codes are unchanged. The adapter uses +output formats and existing operation exit codes are unchanged. The adapter uses `restore_config=False` so existing outer result/warning scopes retain access to the command configuration after the owned log closes. -## Request-report foundation +### Automatic command-line request reports + +Supported leaves automatically print a plain-text **Pull request report** or +**Push request report** on stderr: `artifact pull`, `config get`, `layer get`, +`blob get`, `manifest get`, `manifest put`, `layout push`, `docker push`, +`blob upload`, and `blob mount`. This is an intentional change from quiet +diagnostics by default, including noninteractive invocations. + +- `--telemetry-verbosity 0` (or `-tv 0`) suppresses collection and output without + acquiring report storage. +- `--telemetry-format json` emits one consolidated, schema-versioned + `request_report` event per library invocation instead of text. It does not + change command-result JSON or raw payloads on stdout. +- `--no-progress`, result `--json`, and nonterminal stderr suppress animation, + **not** reporting. Local-only `layout push --dry-run` reports zero actual + requests without constructing a registry client. Layout push reports include + the library-sanitized supplied source path, matching the library entry point. +- Root `--log-file PATH` appends the report in the selected format. Existing + telemetry closes its log before result/warning delivery; the report adapter + then opens the same path in append mode for report delivery and closes only + that owned handle. A failed telemetry log is not reopened. + Manifest and blob transfers reject logs that alias download outputs or upload + source files (including hard links and symlinks) before opening either file. + Layout pushes (including dry runs) require logs outside the source directory; + existing outside log files must have exactly one hard link. Ambiguous + multiply-linked logs fail closed rather than scanning the entire source graph. + Archive sources use the same file-alias guard as other uploads. +- `--time-methods`, `--time-scenarios`, `--debug-calls`, and `--metrics` remain + independently opt-in. All six common telemetry controls are also available + on `docker push`. + +Storage is acquired lazily at the first explicit library operation scope, so +preflight-only failures retain their command errors without allocating a +collector. The SDK's `request_report_factory` supports the same caller-owned +lazy acquisition; an explicit `request_report_collector` takes precedence. +First acquisition is serialized per configuration, including copied worker +contexts; factory callbacks must not recursively establish reporting scopes. +Secure report storage currently requires native Linux/macOS filesystem +primitives. Other platforms fail explicitly instead of producing an unverified +report; use `-tv 0` for commands otherwise supported there. This does not bypass +separate native-filesystem requirements of artifact and layout operations. + +The SDK records session flush/owned-log close failures in +`TelemetryConfig.cleanup_failed`, including secondary failures suppressed by a +primary operation error. A successful session entry resets that status. The +command adapter uses it to avoid reopening failed logs. Collection errors first +discovered during export also make an otherwise successful command exit nonzero; +spool-read failures do not mark healthy diagnostic sinks as failed. +Nested warning/report coordinators share failed-destination state, including +distinct standard-output/error descriptors that alias the same pipe. The report +coordinator also tracks result writes/flushes for commands without a warning +coordinator. Aliased proxies share failure state immediately, so even scenario +telemetry emitted before the outer command exits cannot retry a failed destination. +Progress cleanup likewise cannot repaint a final failed row on a known failed +terminal; its original exception and resource cleanup are preserved without +further destination writes or flushes. + +Reports follow settled library operations, progress and telemetry finalization, +then command results/errors and deferred download warnings. Authentication, +ordered assets, descriptor occurrences, repeated attempts and redirect hops come +from the library model. Full method names and known digests are retained; terminal +controls are escaped. Durations use seconds with microsecond precision; +unavailable facts say `Unknown`, not zero. Remote activity and whole-operation +elapsed time have different boundaries; cumulative chain times are not sums +of overlapping intervals. + +A sole collection, export or report-cleanup failure exits nonzero, even after a +successful operation. Published downloads and acknowledged pushes are **not +rolled back**: check the operation result and verify uncertain publication before +retrying. A primary operation error or cancellation retains precedence. +An otherwise successful command whose final stdout flush fails also exits +nonzero, with a result-output diagnostic rather than a report-export diagnostic; +available reports still reach healthy stderr and enabled logs. +Failed stdout buffers are guarded against a second flush during process shutdown. +Result tracking preserves Click's encoding adaptation and binary output, including +Unicode results on ASCII process streams; adapted buffer failures share the same +no-retry state. Borrowed text streams and binary buffers are never closed. +Broken report destinations are not retried. Reports contain sanitized diagnostic +metadata, not payloads, headers or raw exception messages; log retention remains +the caller's responsibility. + +This command integration does not close the parent capability's remaining +[integrated validation and default-on readiness gates](../../specs/request-reporting.md#10-performance-and-scale) +or imply release availability. + +## Library request reports `TelemetryConfig.request_report_collector` defaults to `None`. The opt-in `RequestReportCollector` owns sanitized metadata storage, not clients or output @@ -93,8 +178,10 @@ ordinary, legacy and pooled adapter dispatches, including token GET/POST calls, authentication probes, retries and every automatic redirect hop. With the collector configured, `pull_artifact`, `download_config`, `download_layer`, `get_blob`, `get_blobs`, `get_manifest` and `download_manifest` establish operation scopes -automatically. Command-line activation and push attribution remain separate -delivery items in [the approved design](../../specs/request-reporting.md). +automatically. Push entry points also establish scopes: `push_manifest`, +`push_layout`, `execute_layout_push`, `push_image`, blob upload facades and blob +mount facades. Direct Python reporting remains opt-in and never prints by itself. +See [the approved design](../../specs/request-reporting.md). ```python import sys diff --git a/src/regshape/cli/artifact.py b/src/regshape/cli/artifact.py index e578155..da38a13 100644 --- a/src/regshape/cli/artifact.py +++ b/src/regshape/cli/artifact.py @@ -23,6 +23,7 @@ from regshape.cli.options import artifact_option from regshape.cli.progress import ProgressDisplay from regshape.cli.telemetry import telemetry_options +from regshape.cli.request_report import request_reporting from regshape.libs.artifacts import ( ArtifactFormat, ArtifactLimits, @@ -176,6 +177,7 @@ def artifact() -> None: @artifact.command("pull") +@request_reporting @_after_telemetry @telemetry_options @artifact_option(help_text="Complete artifact source (registry/repo:tag or registry/repo@sha256:...).") diff --git a/src/regshape/cli/blob.py b/src/regshape/cli/blob.py index 1e2fc30..f2b15b8 100644 --- a/src/regshape/cli/blob.py +++ b/src/regshape/cli/blob.py @@ -19,10 +19,11 @@ import click import requests -from regshape.cli.downloads import DownloadWarnings, download_options, download_policy +from regshape.cli.downloads import DownloadWarnings, download_options, download_policy, separate_file_log from regshape.cli.formatting import emit_error, emit_json, reference_error_context from regshape.cli.progress import ProgressDisplay from regshape.cli.telemetry import telemetry_options +from regshape.cli.request_report import request_reporting from regshape.libs.blobs import ( delete_blob, get_blob, @@ -116,6 +117,8 @@ def wrapper(*args: Any, **kwargs: Any) -> None: @blob.command("get") +@request_reporting +@separate_file_log("output") @_after_blob_telemetry @telemetry_options @click.option("--no-progress", is_flag=True, default=False, help="Disable interactive transfer progress.") @@ -277,6 +280,8 @@ def blob_delete(ctx, repo, digest): @blob.command("upload") +@request_reporting +@separate_file_log("source_file", source=True) @telemetry_options @click.option("--no-progress", is_flag=True, default=False, help="Disable interactive transfer progress.") @click.option( @@ -370,6 +375,7 @@ def blob_upload(ctx, repo, source_file, digest, media_type, chunked, chunk_size, @blob.command("mount") +@request_reporting @telemetry_options @click.option( "--repo", diff --git a/src/regshape/cli/components.py b/src/regshape/cli/components.py index c3cfa1e..b526bca 100644 --- a/src/regshape/cli/components.py +++ b/src/regshape/cli/components.py @@ -24,6 +24,7 @@ from regshape.cli.options import artifact_option from regshape.cli.progress import ProgressDisplay from regshape.cli.telemetry import telemetry_options +from regshape.cli.request_report import request_reporting from regshape.libs.artifacts import ArtifactLimits from regshape.libs.blobs import DownloadOptions, DownloadStatus from regshape.libs.components import ( @@ -236,6 +237,7 @@ def _operation( def _get_command(component: Component) -> click.Command: """Declare identical resource policy/lifetimes; only layer has a required zero-based index.""" @click.command("get", help=_HELP) + @request_reporting @partial(_after_telemetry, component=component) @telemetry_options @artifact_option( diff --git a/src/regshape/cli/docker.py b/src/regshape/cli/docker.py index 3b2487d..03af1fa 100644 --- a/src/regshape/cli/docker.py +++ b/src/regshape/cli/docker.py @@ -16,6 +16,8 @@ from regshape.cli.formatting import emit_error, emit_json, format_size, short_digest from regshape.cli.progress import ProgressDisplay +from regshape.cli.request_report import request_reporting +from regshape.cli.telemetry import telemetry_options from regshape.libs.docker import export_image, list_images, push_image from regshape.libs.errors import ( ArtifactError, @@ -153,6 +155,8 @@ def export_cmd(ctx, image, output, platform, as_json): @docker.command("push") +@request_reporting +@telemetry_options @click.option("--no-progress", is_flag=True, default=False, help="Disable interactive transfer progress.") @click.option( "--image", "-i", @@ -200,6 +204,8 @@ def push_cmd(ctx, image, dest, platform, force, chunked, chunk_size, as_json, no changing export, upload protocols or the result schema. Invalid destinations and strict local snapshot/native-platform failures produce an error, not success. Summary counts come directly from the same PushResult fields as layout push. + Common telemetry controls select the automatic stderr request report without + adding fields to result JSON or enabling debug/timing/metrics diagnostics. """ insecure = ctx.obj.get("insecure", False) if ctx.obj else False diff --git a/src/regshape/cli/downloads.py b/src/regshape/cli/downloads.py index 41e90ee..5d85136 100644 --- a/src/regshape/cli/downloads.py +++ b/src/regshape/cli/downloads.py @@ -1,4 +1,4 @@ -"""Validate download controls/log separation and defer safe warnings until cleanup. +"""Validate transfer-file/log separation and defer safe download warnings until cleanup. The collector never prints from a status callback. Commands place this scope outside telemetry, progress and result output; it owns neither workers nor sinks. @@ -9,14 +9,16 @@ import os import sys from collections.abc import Callable +from functools import wraps from pathlib import Path from types import TracebackType -from typing import IO, Any, Literal, final +from typing import IO, Any, Literal, TypeVar, final from unicodedata import normalize import click from click.core import ParameterSource +from regshape.cli.formatting import emit_error from regshape.cli.progress import ( ProgressDisplay, _redirect_stderr_handlers, @@ -30,10 +32,11 @@ import msvcrt _DARWIN_PC_CASE_SENSITIVE = 11 # sys/unistd.h; not exposed in Python's pathconf_names. +_R = TypeVar("_R") -def separate_log_output(output: str) -> None: - """Reject equivalent log/output paths before telemetry can create or append to either. +def separate_log_output(output: str, *, source: bool = False) -> None: + """Reject log aliases of transfer files before telemetry creates or appends to either. Resolve parent/symlink spellings and detect existing hard links. On Darwin, query the actual volume's case policy before comparing absent leaf names. @@ -41,6 +44,10 @@ def separate_log_output(output: str) -> None: names fail closed, including canonical Unicode spelling differences. Missing parents are left to SDK output preflight, before telemetry opens. This is a usage check, not a reservation against concurrent namespace changes. + ``source`` identifies an upload input (file or directory), not a download output. + Directory sources reject logs within the source namespace by ancestor + identity. Existing outside logs must have one link: ambiguous hard-linked + logs fail closed without an unbounded walk of the source graph. """ ctx = click.get_current_context() log_path = ctx.obj.get("log_file") if ctx.obj else None @@ -49,6 +56,16 @@ def separate_log_output(output: str) -> None: target, log = Path(output).resolve(), Path(log_path).resolve() target_exists, log_exists = target.exists(), log.exists() aliases = target == log or (target_exists and log_exists and target.samefile(log)) + if source and target.is_dir(): + if any(parent.exists() and parent.samefile(target) for parent in (log, *log.parents)): + raise click.BadParameter( + "Telemetry log must be outside the source layout.", param_hint="--log-file", + ) + if log_exists and log.stat().st_nlink != 1: + raise click.BadParameter( + "Cannot prove source/log separation for a non-unique log file; " + "choose a new log path outside the source layout.", param_hint="--log-file", + ) target_name, log_name = normalize("NFD", target.name), normalize("NFD", log.name) if ( not aliases and not (target_exists or log_exists) @@ -67,11 +84,32 @@ def separate_log_output(output: str) -> None: "choose names differing beyond case.", param_hint="--log-file", ) if aliases: + role = "upload source" if source else "download output" raise click.BadParameter( - "Telemetry log and download output must name different paths.", param_hint="--log-file", + f"Telemetry log and {role} must name different paths.", param_hint="--log-file", ) +def separate_file_log( + parameter: str, *, source: bool = False, +) -> Callable[[Callable[..., _R]], Callable[..., _R]]: + """Guard an optional parsed transfer path before telemetry or command acquisition.""" + def decorate(function: Callable[..., _R]) -> Callable[..., _R]: + """Retain Click option metadata and the command's original return contract.""" + @wraps(function) + def wrapper(*args: Any, **kwargs: Any) -> _R: + """Use shared path, symlink, hard-link and volume-case usage checks.""" + path = kwargs.get(parameter) + if path is not None: + try: + separate_log_output(path, source=source) + except (OSError, RuntimeError) as error: + emit_error("--log-file", f"Cannot inspect log/output separation: {error}") + return function(*args, **kwargs) + return wrapper + return decorate + + def download_options(function: Callable[..., Any]) -> Callable[..., Any]: """Attach shared pooled/range/legacy controls without resolving credentials or opening files.""" for option in reversed(( @@ -125,39 +163,81 @@ def download_policy( class _DownloadOutput(io.TextIOBase, IO[str]): """Track diagnostic failures throughout one command without owning its stderr. - Existing display cleanup keeps its repaint behavior; the outer warning - collector uses the persistent flag to avoid any additional diagnostics. + Failed destinations reject subsequent I/O, including display/telemetry cleanup. + Aliased proxies share their first failure immediately, before any outer exit. ``failure`` retains the first exact sink exception for operation boundaries that must distinguish diagnostic I/O from acquisition I/O. + Known failures propagate through nested coordinating proxies without I/O. """ - def __init__(self, stream: IO[str]) -> None: - """Borrow a text sink before telemetry setup or progress suppression is decided.""" + def __init__(self, stream: IO[str], *, failure_owner: "_DownloadOutput | None" = None) -> None: + """Borrow a text sink, optionally sharing failure state with a known aliased proxy.""" super().__init__() self.stream = stream - self.failed = False - self.failure: BaseException | None = None + self._failure_owner: _DownloadOutput = self if failure_owner is None else failure_owner._failure_owner + self._failed = False + self._failure: BaseException | None = None + self._buffer: _DownloadBinaryOutput | None = None + + @property + def failed(self) -> bool: + """Expose the immediate failure state shared by every known alias.""" + return self._failure_owner._failed + + @failed.setter + def failed(self, value: bool) -> None: + """Update the canonical failure state rather than one proxy's private copy.""" + self._failure_owner._failed = value + + @property + def failure(self) -> BaseException | None: + """Expose the exact first exception retained for the shared destination.""" + return self._failure_owner._failure + + @failure.setter + def failure(self, error: BaseException | None) -> None: + """Store the destination exception for all aliases; mark_failed retains the first.""" + self._failure_owner._failure = error + + def mark_failed(self, error: BaseException | None = None) -> None: + """Share a known failed destination with outer proxies, retaining the first exact error.""" + self.failed = True + if self.failure is None: + self.failure = error + if isinstance(self.stream, _DownloadOutput): + self.stream.mark_failed(error) + + def _verify_healthy(self) -> None: + """Reject known failures without I/O, retaining ordinary exception identity. + + Cancellation is not re-raised by an encoding-wrapper destructor; the + command boundary already retains it as the primary error or exit cause. + """ + if self.failed: + if isinstance(self.failure, Exception): + raise self.failure + raise OSError("Output destination already failed") from self.failure def write(self, text: str) -> int: - """Record a real text-write failure, excluding Click's empty binary probes.""" + """Record actual text writes; Click's empty probes perform no destination I/O.""" if not isinstance(text, str): raise TypeError("Download diagnostics require text") + if not text: + return 0 + self._verify_healthy() try: return self.stream.write(text) except BaseException as error: - self.failed = True - if self.failure is None: - self.failure = error + self.mark_failed(error) raise def flush(self) -> None: """Record flush failures without changing their exception identity.""" + self._verify_healthy() try: self.stream.flush() except BaseException as error: - self.failed = True - if self.failure is None: - self.failure = error + self.mark_failed(error) raise def writable(self) -> bool: @@ -177,6 +257,17 @@ def encoding(self) -> str | None: # type: ignore[override] # TextIOBase's runt """Preserve the borrowed sink's codec for encoding-safe progress glyph selection.""" return getattr(self.stream, "encoding", None) + @property + def buffer(self) -> "_DownloadBinaryOutput": + """Expose a tracked binary buffer for Click's encoding adaptation and binary echo. + + Streams without a binary buffer retain their usual AttributeError. + The borrowed buffer shares text failure state and is never closed. + """ + if self._buffer is None: + self._buffer = _DownloadBinaryOutput(getattr(self.stream, "buffer"), self) + return self._buffer + @property def closed(self) -> bool: """Expose borrowed-sink closure so deferred telemetry never flushes a closed destination.""" @@ -186,6 +277,80 @@ def close(self) -> None: """Never close or flush the borrowed sink, including during adapter destruction.""" +class _DownloadBinaryOutput(io.BufferedIOBase): + """Borrow a binary buffer while sharing text-proxy failure and ownership state.""" + + def __init__(self, stream: IO[bytes], owner: _DownloadOutput) -> None: + """Retain the underlying buffer only for Click's result encoding/binary writes.""" + self.stream, self.owner = stream, owner + + def write(self, data) -> int: + """Track encoded/binary writes without forwarding Click's empty buffer probes.""" + if data == b"": + return 0 + self.owner._verify_healthy() + try: + return self.stream.write(data) + except BaseException as error: + self.owner.mark_failed(error) + raise + + def flush(self) -> None: + """Track encoding-wrapper flush failures and never retry a known failed buffer.""" + self.owner._verify_healthy() + try: + self.stream.flush() + except BaseException as error: + self.owner.mark_failed(error) + raise + + def writable(self) -> bool: + """Expose the borrowed destination's binary-output capability.""" + return self.stream.writable() + + def fileno(self) -> int: + """Preserve the actual process destination for Click's platform handling.""" + return self.stream.fileno() + + def isatty(self) -> bool: + """Keep terminal detection tied to the borrowed buffer.""" + return self.stream.isatty() + + @property + def closed(self) -> bool: + """Reflect borrowed-buffer closure without transferring ownership.""" + return self.stream.closed + + def close(self) -> None: + """Never close or flush the borrowed buffer during encoding-wrapper destruction.""" + + +def _same_output_sink(output: IO[str], error: IO[str]) -> bool: + """Recognize borrowed stream aliases without I/O, including duplicated pipe descriptors. + + Unavailable descriptor identities establish no sharing beyond object identity. + Windows pipes require kernel-handle comparison because their stat identity is zero. + """ + if output is error: + return True + try: + output_fd, error_fd = output.fileno(), error.fileno() + if output_fd == error_fd: + return True + if sys.platform == "win32": + compare = getattr(ctypes.WinDLL("kernelbase"), "CompareObjectHandles", None) + if compare is not None: + compare.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + compare.restype = ctypes.c_int + return bool(compare( + msvcrt.get_osfhandle(output_fd), msvcrt.get_osfhandle(error_fd), + )) + output_stat, error_stat = os.fstat(output_fd), os.fstat(error_fd) + return output_stat.st_ino != 0 and os.path.samestat(output_stat, error_stat) + except (AttributeError, OSError, ValueError): + return False + + def _raise_silent_exit(exc: BaseException | None) -> None: """Convert Click-reportable errors to silent exits, leaving other primary errors alone.""" if isinstance(exc, (KeyboardInterrupt, EOFError, click.Abort)): @@ -234,37 +399,15 @@ def observe(self, event: DownloadStatus) -> None: self._affected.add(event.digest) def result_failed(self) -> None: - """Do not diagnose through stderr when it aliases a failed final-result destination.""" + """Share failed-result alias state with outer coordinators, without retrying any sink.""" if self._output is not None and self._shares_result_sink(): - self._output.failed = True + self._output.mark_failed() def _shares_result_sink(self) -> bool: - """Recognize shared objects or OS destinations without writing to either stream. - - If descriptors or destination identities are unavailable, only object - identity can establish sharing; unrelated healthy stderr remains usable. - """ - if sys.stdout is self._stderr or sys.stdout is sys.stderr: - return True - if self._stderr is None: - return False - try: - output_fd, error_fd = sys.stdout.fileno(), self._stderr.fileno() - if output_fd == error_fd: - return True - if sys.platform == "win32": - # Windows pipes have zero stat identities; compare kernel handles instead. - compare = getattr(ctypes.WinDLL("kernelbase"), "CompareObjectHandles", None) - if compare is not None: - compare.argtypes = [ctypes.c_void_p, ctypes.c_void_p] - compare.restype = ctypes.c_int - return bool(compare( - msvcrt.get_osfhandle(output_fd), msvcrt.get_osfhandle(error_fd), - )) - output_stat, error_stat = os.fstat(output_fd), os.fstat(error_fd) - return output_stat.st_ino != 0 and os.path.samestat(output_stat, error_stat) - except (AttributeError, OSError, ValueError): - return False + """Use shared destination detection while retaining current stderr object aliases.""" + return sys.stdout is sys.stderr or ( + self._stderr is not None and _same_output_sink(sys.stdout, self._stderr) + ) def __exit__( self, exc_type: type[BaseException] | None, exc: BaseException | None, @@ -309,6 +452,8 @@ def _finish(self, exc: BaseException | None) -> Literal[False]: sys.stdout.flush() except BaseException as flush_error: if self._shares_result_sink(): + if self._output is not None: + self._output.mark_failed(flush_error) _raise_silent_exit(flush_error) raise primary = flush_error diff --git a/src/regshape/cli/layout.py b/src/regshape/cli/layout.py index 2d48c0a..1609a59 100644 --- a/src/regshape/cli/layout.py +++ b/src/regshape/cli/layout.py @@ -24,6 +24,7 @@ import click import requests +from regshape.cli.downloads import separate_file_log from regshape.cli.formatting import emit_error, emit_json, progress_status from regshape.cli.layout_inspect import ( bind_inspection_telemetry, @@ -32,6 +33,8 @@ ) from regshape.cli.progress import ProgressDisplay from regshape.cli.telemetry import telemetry_options +from regshape.cli.request_report import request_reporting +from regshape.libs.decorators import request_report_scope from regshape.libs.artifacts.models import ArtifactLimits from regshape.libs.decorators.scenario import track_scenario from regshape.libs.errors import ( @@ -769,6 +772,8 @@ def _format_size(size: int) -> str: @layout.command("push") +@request_reporting +@separate_file_log("layout_path", source=True) @telemetry_options @click.option("--no-progress", is_flag=True, default=False, help="Disable interactive transfer progress.") @click.option("--max-manifest-bytes", type=click.IntRange(min=1), default=None) @@ -821,6 +826,11 @@ def push_cmd( Dry-run uses that same snapshot/plan and constructs no client. Interactive progress retains one row per unique blob; JSON/--no-progress suppress it. Native safe snapshots require Linux/Darwin; Windows fails closed. + A library scope includes local planning and dry runs; only actual registry + calls enter its remote history. Its source is the supplied layout path, + matching the library entry point. The automatic report follows final output. + Logs must be outside directory sources with a unique link; archive/log aliases + are rejected before telemetry acquisition, including in dry-run mode. """ try: registry, repo, tag_override = parse_push_destination(dest) @@ -837,7 +847,10 @@ def push_cmd( if tag_override: dest_display += f":{tag_override}" try: - with LayoutPushPlan(layout_path, tag_override, limits=limits) as plan: + with request_report_scope( + "layout push", "push", source=str(layout_path), destination=dest_display, + ), \ + LayoutPushPlan(layout_path, tag_override, limits=limits) as plan: if dry_run: _push_dry_run(plan, registry, repo, as_json) return diff --git a/src/regshape/cli/manifest.py b/src/regshape/cli/manifest.py index c37e3b0..3c3b7b9 100644 --- a/src/regshape/cli/manifest.py +++ b/src/regshape/cli/manifest.py @@ -21,6 +21,7 @@ import click import requests +from regshape.cli.downloads import separate_file_log from regshape.cli.formatting import ( emit_error, emit_json, @@ -31,6 +32,7 @@ from regshape.cli.options import artifact_option from regshape.cli.progress import ProgressDisplay from regshape.cli.telemetry import telemetry_options +from regshape.cli.request_report import request_reporting from regshape.libs.decorators.output import flush_telemetry from regshape.libs.decorators.scenario import track_scenario from regshape.libs.errors import ( @@ -79,6 +81,8 @@ def manifest(): # =========================================================================== @manifest.command("get") +@request_reporting +@separate_file_log("output") @telemetry_options @click.option("--no-progress", is_flag=True, default=False, help="Disable interactive transfer progress.") @artifact_option( @@ -316,6 +320,8 @@ def descriptor(ctx, image_ref, accept): # =========================================================================== @manifest.command("put") +@request_reporting +@separate_file_log("manifest_file", source=True) @telemetry_options @artifact_option( help_text="Artifact reference — registry must be embedded (registry/repo:tag or registry/repo@sha256:...).", diff --git a/src/regshape/cli/request_report.py b/src/regshape/cli/request_report.py new file mode 100644 index 0000000..b0e78bf --- /dev/null +++ b/src/regshape/cli/request_report.py @@ -0,0 +1,448 @@ +"""Render library request reports after command results, warnings and diagnostics. + +The invocation adapter owns diagnostic resources and borrows tracked output +streams. Library operations choose scope boundaries and supply every identity, +count, timing and sanitized value. +Rendering streams grouped records without retaining the request history in RAM. +""" + +import json +import logging +import sys +from collections.abc import Callable +from contextvars import ContextVar, Token +from functools import wraps +from types import TracebackType +from typing import IO, Any, Literal, TextIO, TypeVar + +import click + +from regshape.cli.downloads import _DownloadOutput, _same_output_sink +from regshape.cli.layout_inspect import _FailedFlushStream +from regshape.cli.progress import _redirect_stderr_handlers, _restore_stderr_handlers +from regshape.libs._http import report_secondary_failure +from regshape.libs.decorators import TelemetryConfig +from regshape.libs.decorators.request_report import ( + Call, + Failure, + Request, + RequestReport, + RequestReportCollector, +) +from regshape.libs.decorators.streams import TextOutput +from regshape.libs.errors import RequestReportError + +_R = TypeVar("_R") +_active: ContextVar["_CommandReport | None"] = ContextVar("cli_request_report", default=None) + + +def _text(value: object) -> str: + """Escape controls, bidi and non-ASCII text for any terminal encoding, without redacting again.""" + return "Unknown" if value is None else json.dumps(str(value), ensure_ascii=True)[1:-1] + + +def _duration(seconds: float | None) -> str: + """Display library-rounded seconds without losing its microsecond precision or nulls.""" + return "Unknown" if seconds is None else f"{seconds:.6f} s" + + +def _line(output: TextOutput, text: str = "") -> None: + """Write one complete text line; treat short writes as export failures without retrying.""" + text += "\n" + if output.write(text) != len(text): + raise RequestReportError("report_export", "export") + + +def _request(output: TextOutput, request: Request) -> None: + """Render one physical attempt/hop, including incomplete bodies and rejected redirects.""" + _line(output, f" #{request.sequence} {_text(request.method)} {_text(request.endpoint)}") + status = "Not received" if request.status is None else str(request.status) + _line(output, f" Status: {status}") + _line(output, f" Time to headers: {_duration(request.headers_s)}") + if request.full_response_s is not None: + _line(output, f" Time to full response: {_duration(request.full_response_s)}") + elif request.body_state in {"incomplete", "not_received"}: + _line(output, f" Full response: Incomplete after {_duration(request.elapsed_s)}") + else: + _line(output, " Time to full response: Unknown") + _line(output, f" Body state: {_text(request.body_state)}") + _line(output, f" Elapsed: {_duration(request.elapsed_s)}") + if request.failure is not None: + _line(output, f" Failure: {_text(request.failure.code)} ({_text(request.failure.stage)})") + if request.failure.publication_uncertain: + _line(output, " Publication: Uncertain") + if request.redirect_target is not None: + _line(output, f" Redirect target: {_text(request.redirect_target)}") + if request.redirect_to_sequence is not None: + _line(output, f" Redirects to #{request.redirect_to_sequence}") + + +def _call(output: TextOutput, call: Call) -> None: + """Present retained call metadata, never inferring final endpoints or retry causes.""" + _line(output, f" Call {_text(call.id)}, attempt {call.attempt} ({_text(call.reason)})") + if call.related_call_id is not None: + _line(output, f" Following call {_text(call.related_call_id)}, attempt {call.related_call_attempt}") + if call.range is not None: + end = "open" if call.range.end is None else str(call.range.end) + _line(output, f" Range: {call.range.start}-{end} (inclusive)") + if call.upload_id is not None: + _line(output, f" Upload: {_text(call.upload_id)}") + if call.chunk_index is not None: + _line(output, f" Chunk: {call.chunk_index} (zero-based)") + _line(output, f" Original: {_text(call.original_endpoint)}") + if call.final_endpoint is not None: + _line(output, f" Final: {_text(call.final_endpoint)}") + elif call.last_endpoint is not None: + _line(output, f" Last observed endpoint: {_text(call.last_endpoint)}") + _line(output, f" Chain state: {_text(call.chain_state)}") + if call.chain_state == "blocked": + _line(output, " Not followed: blocked by policy") + annotations = { + "already_present": "Already present; upload skipped", + "missing_blob": "Missing blob; upload follows", + "mounted": "Mounted; upload skipped", + "mount_not_accepted": "Mount not accepted", + } + if call.annotation is not None: + _line(output, f" {annotations[call.annotation]}") + + +def render_text(report: RequestReport, output: TextOutput) -> None: + """Stream the library's group/call/hop order and exact summary to a borrowed text sink. + + All descriptor occurrences are shown, including shared roles and zero-based + ordinals. Nullable facts remain Unknown. Sink/storage errors propagate; the + caller owns flushing and failure precedence. + """ + operation = report.operation + summary = report.summary + collection = report.collection + suffix = "" if operation.outcome == "succeeded" else f" - {operation.outcome.upper()}" + if not collection.complete: + suffix += " - COLLECTION INCOMPLETE" + _line(output, f"{operation.direction.title()} request report{suffix}") + if operation.failure is not None and operation.failure.publication_uncertain: + _line(output, "Publication is uncertain. Verify the destination before retrying. No rollback was performed.") + if summary.request_attempt_count == 0: + _line(output, " No remote requests were made.") + calls = iter(report.iter_calls()) + requests = iter(report.iter_requests()) + call = next(calls, None) + request = next(requests, None) + for group in report.iter_groups(): + _line(output) + digest = "" if group.digest is None else f" - {_text(group.digest)}" + _line(output, f"Group: {_text(group.name)}{digest}") + if group.digest is not None: + _line(output, f" Digest source: {_text(group.digest_source)}; verified: {group.verified}") + for reference in report.iter_references(group.id): + _line( + output, + f" Reference: {_text(reference.role)}; ordinal: {_text(reference.ordinal)}; " + f"parent: {_text(reference.parent_group_id)}; platform: {_text(reference.platform)}", + ) + if group.category == "authentication" and (call is None or call.group_id != group.id): + _line(output, " No authentication endpoints accessed.") + while call is not None and call.group_id == group.id: + _call(output, call) + while request is not None and (request.call_id, request.attempt) == (call.id, call.attempt): + _request(output, request) + request = next(requests, None) + _line(output, f" Redirect responses: {_duration(call.redirect_response_s)}") + _line(output, f" Original request to final headers: {_duration(call.chain_headers_s)}") + _line(output, f" Complete request chain: {_duration(call.chain_elapsed_s)}") + call = next(calls, None) + _line(output) + _line(output, "Summary") + rows = ( + ("Outcome", operation.outcome.title()), + ("Remote activity elapsed", _duration(summary.remote_elapsed_s)), + ("Whole-operation elapsed", _duration(summary.operation_elapsed_s)), + ("Logical calls", summary.logical_call_count), + ("Requests attempted", summary.request_attempt_count), + ("Unique endpoints", summary.unique_endpoint_count), + ("Authentication requests", summary.authentication_request_count), + ("Redirect hops followed", summary.redirect_hop_count), + ("Assets uploaded", summary.assets_uploaded), + ("Assets already present", summary.assets_already_present), + ("Verified download bytes", summary.verified_download_bytes), + ("Acknowledged upload bytes", summary.acknowledged_upload_bytes), + ("Sent body bytes", summary.sent_body_bytes), + ("Received body bytes", summary.received_body_bytes), + ("Report collection", "Complete" if collection.complete else "Incomplete"), + ("Missing request records", collection.missing_request_count), + ) + for label, value in rows: + _line(output, f" {label}: {_text(value)}") + if collection.failure is not None: + _line(output, f" Collection failure: {_text(collection.failure.code)}") + + +class _CommandReport: + """Keep reports alive through command output, appending after the telemetry log closes.""" + + def __init__(self) -> None: + """Defer acquisition until the first library scope, after command-specific preflight.""" + self.collector: RequestReportCollector | None = None + self.config: TelemetryConfig | None = None + self.token: Token[_CommandReport | None] + self.stderr: TextIO + self.stdout: TextIO + self.shared_stdout = False + self.output: _DownloadOutput + self.result_output: _DownloadOutput + self.log_output: _DownloadOutput | None = None + self.report_log: TextIO | None = None + self.telemetry_failed = False + self.log_streams: list[tuple[logging.StreamHandler, IO[str]]] = [] + + def __enter__(self) -> "_CommandReport": # noqa: PYI034 - Python 3.10, no typing_extensions dependency. + """Track borrowed result/diagnostic sinks and make this invocation the activation target.""" + self.token = _active.set(self) + self.stderr = sys.stderr + self.stdout = sys.stdout + self.output = _DownloadOutput(self.stderr) + self.shared_stdout = _same_output_sink(self.stdout, self.stderr) + self.result_output = self.output if self.stdout is self.stderr else _DownloadOutput( + self.stdout, failure_owner=self.output if self.shared_stdout else None, + ) + sys.stdout = self.result_output + sys.stderr = self.output + try: + _redirect_stderr_handlers( + self.stderr, self.output, self.log_streams, include_last_resort=True, + ) + except BaseException: + sys.stderr = self.stderr + sys.stdout = self.stdout + _restore_stderr_handlers(self.output, self.log_streams) + _active.reset(self.token) + raise + return self + + def activate(self, config: TelemetryConfig) -> None: + """Defer acquisition to the first library scope, preserving command preflight errors.""" + if self.config is not None: + raise RuntimeError("Command request reporting is already active") + self.config = config + config.request_report_factory = self.acquire + + def acquire(self) -> RequestReportCollector: + """Acquire only the library collector, surfacing safe errors before remote side effects.""" + try: + self.collector = RequestReportCollector() + except (RequestReportError, OSError, ValueError) as error: + code = Failure.from_exception(error, "collection").code + raise click.ClickException( + f"Request report initialization failed ({code}). " + "Secure report storage is unsupported or unavailable; " + "use --telemetry-verbosity 0 to disable request reporting." + ) from error + return self.collector + + def __exit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, + traceback: TracebackType | None, + ) -> Literal[False]: + """Render last on every exit and preserve primary errors over reporting failures. + + Click normally prints usage/cancellation outside the callback. Print those + once here, before the report, and retain their exit status with a silent + Exit. Other operation exceptions retain identity, including cancellation + types not translated by Click. Failed report sinks are never retried. + Collection failures discovered during rendering also make reporting fail. + A failed final result flush is diagnosed separately before available + reports; its exception remains the cause of a sole-failure exit. + Result failures propagate across shared destinations before diagnostics; + failed stdout buffers are guarded against shutdown flush retries. + """ + primary = exc + translated: click.exceptions.Exit | None = None + failure: BaseException | None = None + failure_diagnosed = False + try: + if self.shared_stdout and self.result_output.failed: + self.output.mark_failed(self.result_output.failure) + if self.collector is None or self.config is None: + return False + config = self.config + # Deferred warning/display adapters have restored the invocation's stderr. + config.output = self.output + try: + if isinstance(exc, (KeyboardInterrupt, EOFError, click.Abort)): + translated = click.exceptions.Exit(1) + if not self.output.failed: + click.echo("\nAborted!", err=True) + elif isinstance(exc, click.ClickException): + translated = click.exceptions.Exit(exc.exit_code) + if not self.output.failed: + exc.show() + elif ( + exc is not None and not isinstance(exc, (SystemExit, click.exceptions.Exit)) + and not self.output.failed + ): + code = Failure.from_exception(exc, "operation").code + click.echo(f"Error: Operation did not complete ({code}).", err=True) + if exc is None: + try: + sys.stdout.flush() + except BaseException as error: # noqa: BLE001 - retain result failure while delivering healthy reports. + failure = error + if self.shared_stdout: + self.output.mark_failed(error) + if not self.output.failed: + click.echo( + "Error: Command result output flush failed. " + "Published output or acknowledged pushes were not rolled back.", + err=True, + ) + failure_diagnosed = True + except BaseException as error: # noqa: BLE001 - retain cancellation while delivering available reports. + if failure is None: + failure = error + if ( + config.log_file_path and not self.telemetry_failed + and (self.log_output is None or not self.log_output.failed) + ): + try: + self.report_log = open(config.log_file_path, "a") # noqa: SIM115 - closed below without masking primary. + self.log_output = _DownloadOutput(self.report_log) + except BaseException as error: # noqa: BLE001 - a diagnostic cannot replace the primary error. + failure = error if failure is None else failure + self.log_output = None + else: + self.log_output = None + for report in self.collector.iter_reports(): + collection = report.collection + if collection.failure is not None and failure is None: + failure = RequestReportError(collection.failure.code, collection.failure.stage) + if not self.output.failed: + try: + click.echo( + f"Error: Request report collection failed ({collection.failure.code}). " + "Published output or acknowledged pushes were not rolled back.", + err=True, + ) + failure_diagnosed = True + if primary is not None: + report_secondary_failure(primary, failure, "Request-report collection") + except BaseException as diagnostic_error: # noqa: BLE001 - restoration must survive a failed diagnostic. + if failure is None: + failure = diagnostic_error + for sink in (self.output, self.log_output): + if sink is None or sink.failed: + continue + try: + if config.output_format == "json": + report.write_json(sink) + _line(sink) + else: + render_text(report, sink) + sink.flush() + except BaseException as error: # noqa: BLE001 - retain sink/cancellation identity and try only healthy sinks. + if failure is None: + failure = error + if isinstance(error, RequestReportError) and error.code == "report_export": + sink.mark_failed(error) + collection = report.collection + if collection.failure is not None and failure is None: + failure = RequestReportError(collection.failure.code, collection.failure.stage) + if failure is not None and not self.output.failed and not failure_diagnosed: + click.echo( + "Error: Request report export failed. " + "Published output or acknowledged pushes were not rolled back.", + err=True, + ) + failure_diagnosed = True + except BaseException as error: # noqa: BLE001 - cleanup and original exception take precedence over export. + if failure is None: + failure = error + finally: + cleanup_primary = primary if primary is not None else failure + for resource in (self.collector, self.report_log): + if resource is None: + continue + try: + if resource is self.collector: + self.collector.close() + else: + resource.close() + except BaseException as error: # noqa: BLE001 - close all owned resources on cancellation too. + if failure is None: + failure = error + if cleanup_primary is None: + cleanup_primary = error + elif error is not cleanup_primary and not self.output.failed: + try: + report_secondary_failure(cleanup_primary, error, "Request-report cleanup") + except BaseException as diagnostic_error: # noqa: BLE001 - restore stream/context bindings even if logging fails. + if failure is None: + failure = diagnostic_error + if failure is not None and not failure_diagnosed and not self.output.failed: + try: + click.echo( + "Error: Request reporting failed. " + "Published output or acknowledged pushes were not rolled back.", + err=True, + ) + except BaseException as diagnostic_error: # noqa: BLE001 - restoration must survive a failed diagnostic. + if failure is None: + failure = diagnostic_error + _restore_stderr_handlers(self.output, self.log_streams) + if self.config is not None and self.config.output is self.output: + self.config.output = self.stderr + if self.config is not None and self.config.request_report_collector is self.collector: + self.config.request_report_collector = None + if self.config is not None and self.config.request_report_factory == self.acquire: + self.config.request_report_factory = None + if sys.stderr is self.output: + sys.stderr = _FailedFlushStream(self.stderr) if self.output.failed else self.stderr + if sys.stdout is self.result_output: + stdout_failed = self.result_output.failed or (self.shared_stdout and self.output.failed) + sys.stdout = _FailedFlushStream(self.stdout) if stdout_failed else self.stdout + _active.reset(self.token) + if failure is not None: + if primary is not None: + if self.output.failed: + if translated is not None: + raise translated from primary + raise primary from failure + if not failure_diagnosed: + report_secondary_failure(primary, failure, "Request reporting") + else: + raise click.exceptions.Exit(1) from failure + if translated is not None: + raise translated from exc + return False + + +def activate_reporting(config: TelemetryConfig) -> None: + """Enable only a marked command with nonzero existing telemetry verbosity.""" + reporting = _active.get() + if reporting is not None and config.verbosity > 0: + reporting.activate(config) + + +def bind_reporting_log(config: TelemetryConfig) -> None: + """Track enabled-log failures without changing library session ownership or close timing.""" + reporting = _active.get() + if reporting is not None and reporting.config is config and config.log_file is not None: + reporting.log_output = _DownloadOutput(config.log_file) + config.log_file = reporting.log_output + + +def reporting_telemetry_failed() -> None: + """Do not reopen an append log whose telemetry finalization already failed.""" + reporting = _active.get() + if reporting is not None: + reporting.telemetry_failed = True + + +def request_reporting(function: Callable[..., _R]) -> Callable[..., _R]: + """Wrap outside telemetry and deferred result/warning decorators; add no command options.""" + @wraps(function) + def wrapper(*args: Any, **kwargs: Any) -> _R: + """Run one supported leaf with invocation-local diagnostic ownership.""" + with _CommandReport(): + return function(*args, **kwargs) + return wrapper diff --git a/src/regshape/cli/telemetry.py b/src/regshape/cli/telemetry.py index 2524c12..c9c9a54 100644 --- a/src/regshape/cli/telemetry.py +++ b/src/regshape/cli/telemetry.py @@ -6,6 +6,11 @@ import click +from regshape.cli.request_report import ( + activate_reporting, + bind_reporting_log, + reporting_telemetry_failed, +) from regshape.libs.decorators import TelemetryConfig, telemetry_session _R = TypeVar("_R") @@ -18,6 +23,8 @@ def telemetry_options(func: Callable[..., _R]) -> Callable[..., _R]: execute the callback in a library-owned telemetry session. Verbosity zero disables all four feature flags without forwarding them to the callback. Keep the command configuration active for outer result/warning cleanup. + Marked request-report commands retain a collector outside result/warning + cleanup; telemetry log ownership and pre-result finalization are unchanged. :param func: Command callback, which need not accept telemetry options. :returns: Callback with the unchanged option names, defaults and help text. @@ -70,7 +77,7 @@ def wrapper( telemetry_verbosity: int = 1, **kwargs: Any, ) -> _R: - """Map parsed flags into one managed library configuration and run the callback.""" + """Map flags into a managed config and expose suppressed cleanup failures to reports.""" ctx = click.get_current_context() enabled = telemetry_verbosity > 0 config = TelemetryConfig( @@ -82,7 +89,22 @@ def wrapper( output_format=telemetry_format, log_file_path=ctx.obj.get("log_file") if ctx.obj else None, ) - with telemetry_session(config, restore_config=False): - return func(*args, **kwargs) + activate_reporting(config) + callback_error: BaseException | None = None + try: + with telemetry_session(config, restore_config=False): + bind_reporting_log(config) + try: + return func(*args, **kwargs) + except BaseException as error: + callback_error = error + raise + except BaseException as error: + if error is not callback_error: + reporting_telemetry_failed() + raise + finally: + if config.cleanup_failed: + reporting_telemetry_failed() return wrapper diff --git a/src/regshape/libs/_pull_report.py b/src/regshape/libs/_pull_report.py index d17fe38..5112e32 100644 --- a/src/regshape/libs/_pull_report.py +++ b/src/regshape/libs/_pull_report.py @@ -83,10 +83,11 @@ def __init__( self.provenance: DigestSource = "requested" def __enter__(self) -> "PullReport": - """Bind a nested asset with redacted labels without changing the transport selector.""" + """Bind an enabled or lazily acquired report asset without changing the transport selector.""" self.stack = ExitStack() try: - if (get_telemetry_config().request_report_collector is None + config = get_telemetry_config() + if (config.request_report_collector is None and config.request_report_factory is None and current_report_scope() is None): return self self.requested = known_digest(self.reference) diff --git a/src/regshape/libs/_push_report.py b/src/regshape/libs/_push_report.py index 65f96f5..6a6731f 100644 --- a/src/regshape/libs/_push_report.py +++ b/src/regshape/libs/_push_report.py @@ -39,10 +39,11 @@ def __init__(self, name: str, *, destination: str | Callable[[], str], source: s self._blob_root = False def __enter__(self) -> "PushReport": - """Begin before local preparation, initializing only this root's push totals.""" + """Begin an enabled or lazily acquired report before preparation; initialize root totals.""" self.stack = ExitStack() try: - if (get_telemetry_config().request_report_collector is None + config = get_telemetry_config() + if (config.request_report_collector is None and config.request_report_factory is None and current_report_scope() is None): return self self.scope = self.stack.enter_context(request_report_scope( diff --git a/src/regshape/libs/decorators/__init__.py b/src/regshape/libs/decorators/__init__.py index 908e91c..65af386 100644 --- a/src/regshape/libs/decorators/__init__.py +++ b/src/regshape/libs/decorators/__init__.py @@ -17,9 +17,12 @@ """ import sys +from _thread import LockType +from collections.abc import Callable from contextlib import AbstractContextManager from contextvars import ContextVar from dataclasses import dataclass, field +from threading import Lock from types import TracebackType from typing import IO, Literal, Optional @@ -64,6 +67,15 @@ class TelemetryConfig: :param request_report_collector: Optional caller-owned request-report store. Defaults to None. Operations explicitly establish reporting scopes; telemetry-session exit neither finalizes reports nor closes the collector. + :param request_report_factory: Optional caller-owned lazy acquisition callback. + The first explicit operation scope installs its returned collector only + when no collector is present. Preflight-only invocations acquire nothing. + The caller retains cleanup ownership and acquisition errors propagate. + Acquisition is serialized per configuration, including copied contexts; + the callback must not recursively establish reporting scopes. + :ivar cleanup_failed: Session-owned flush/owned-log cleanup status, reset on + successful entry. True even when an operation error suppresses a cleanup + exception; outer coordinators must not retry a failed diagnostic log. """ time_methods_enabled: bool = False time_scenarios_enabled: bool = False @@ -77,6 +89,9 @@ class TelemetryConfig: method_timings: list[tuple[str, float]] = field(default_factory=list) metrics: PerformanceMetrics = field(default_factory=PerformanceMetrics) request_report_collector: RequestReportCollector | None = field(default=None, repr=False) + request_report_factory: Callable[[], RequestReportCollector] | None = field(default=None, repr=False) + _request_report_lock: LockType = field(default_factory=Lock, init=False, repr=False, compare=False) + cleanup_failed: bool = field(default=False, init=False, repr=False) _telemetry_config: ContextVar[TelemetryConfig] = ContextVar( @@ -119,7 +134,7 @@ def __init__(self, config: TelemetryConfig, restore_config: bool) -> None: self._owned_log_file: IO | None = None def __enter__(self) -> TelemetryConfig: - """Reject a closed log before opening files or activating the configuration.""" + """Reject closed logs, acquire the owned log and reset this scope's cleanup status.""" if self.config.log_file is not None and self.config.log_file.closed: raise ValueError( "Telemetry log stream is closed; supply an open log_file or set " @@ -129,6 +144,7 @@ def __enter__(self) -> TelemetryConfig: if self.config.log_file_path and self.config.log_file is None: self._owned_log_file = open(self.config.log_file_path, "a") self.config.log_file = self._owned_log_file + self.config.cleanup_failed = False configure_telemetry(self.config) return self.config @@ -138,7 +154,7 @@ def __exit__( exc: BaseException | None, traceback: TracebackType | None, ) -> Literal[False]: - """Flush this scope's data and close its log, preserving errors and retained config.""" + """Record flush/close failures independently of the preserved primary exception.""" primary_error = exc token = _telemetry_config.set(self.config) try: @@ -146,6 +162,7 @@ def __exit__( try: flush_telemetry() except BaseException as diagnostic_error: + self.config.cleanup_failed = True if primary_error is None: primary_error = diagnostic_error raise @@ -155,6 +172,7 @@ def __exit__( try: self._owned_log_file.close() except BaseException as close_error: + self.config.cleanup_failed = True if primary_error is None: raise report_secondary_failure(primary_error, close_error, "Telemetry log cleanup") @@ -181,6 +199,8 @@ def telemetry_session( scope retained another active configuration. A closed ``log_file`` is rejected on entry, before the operation runs. Reset it to None to reopen ``log_file_path`` in a new session. + ``config.cleanup_failed`` records flush/owned-close errors even when a primary + exception takes precedence; each successful session entry resets that status. :param config: Configuration to activate; yielded unchanged on entry. :param restore_config: Restore the previous active configuration on exit. diff --git a/src/regshape/libs/decorators/request_report.py b/src/regshape/libs/decorators/request_report.py index 5f12afa..0c6036b 100644 --- a/src/regshape/libs/decorators/request_report.py +++ b/src/regshape/libs/decorators/request_report.py @@ -23,7 +23,7 @@ import sqlite3 import time from types import TracebackType -from typing import Literal, TextIO, TypeVar +from typing import Literal, TypeVar from urllib.parse import urlsplit import requests @@ -33,6 +33,7 @@ from regshape.libs.decorators.sanitization import ( sanitize_report_location, sanitize_report_text, sanitize_report_url, ) +from regshape.libs.decorators.streams import TextOutput from regshape.libs.errors import ArtifactError, RegShapeError, RequestReportError Direction = Literal["pull", "push"] @@ -328,7 +329,7 @@ class _Array: items: Iterator[object] -def _write_json(output: TextIO, value: object, indent: int | None, depth: int = 0) -> None: +def _write_json(output: TextOutput, value: object, indent: int | None, depth: int = 0) -> None: """Write bounded primitives or lazy arrays; propagate the original sink exception.""" if is_dataclass(value) and not isinstance(value, (type, _Array)): value = _plain(value) @@ -358,7 +359,7 @@ def _write_json(output: TextIO, value: object, indent: int | None, depth: int = _emit(output, closing) -def _emit(output: TextIO, text: str) -> None: +def _emit(output: TextOutput, text: str) -> None: """Detect short writes without flushing, closing or retrying a borrowed sink.""" if output.write(text) != len(text): raise RequestReportError("report_export", "export") @@ -1325,9 +1326,10 @@ def _groups_json(self) -> Iterator[dict]: "references": _Array(self.iter_references(group.id)), } - def write_json(self, output: TextIO, *, indent: int | None = None) -> None: + def write_json(self, output: TextOutput, *, indent: int | None = None) -> None: """Stream a complete schema-v1 document, borrowing the output without flush/close. + Accept the shared writable-text protocol, including coordinating proxies. Export can be repeated until collector close. Sink exceptions propagate unchanged; short writes raise RequestReportError. Failed sinks are never retried. ``indent`` must be None or an integer in [0, 8]. @@ -1443,11 +1445,22 @@ def request_report_scope( """Enable an operation from TelemetryConfig, acquiring nothing when reporting is disabled. Operations, not telemetry-session exit, choose their reporting boundaries. + If configured without an existing collector, a caller-owned factory acquires + one at the first scope, after command preflight. Acquisition is serialized + per configuration; failures propagate without installing a collector. This helper does not automatically instrument legacy operations or emit text. """ from regshape.libs.decorators import get_telemetry_config - collector = get_telemetry_config().request_report_collector + config = get_telemetry_config() + collector = config.request_report_collector + if collector is None and config.request_report_factory is not None: + with config._request_report_lock: + collector = config.request_report_collector + factory = config.request_report_factory + if collector is None and factory is not None: + collector = factory() + config.request_report_collector = collector if collector is None: parent = current_report_scope() collector = parent._inv.collector if parent is not None else None diff --git a/src/regshape/tests/test_artifact_cli.py b/src/regshape/tests/test_artifact_cli.py index bd24b91..10d3809 100644 --- a/src/regshape/tests/test_artifact_cli.py +++ b/src/regshape/tests/test_artifact_cli.py @@ -1,6 +1,5 @@ """Production artifact-option parity through real command/library paths and mocked HTTP.""" -import io import json from collections.abc import Iterator from itertools import product @@ -105,7 +104,7 @@ def _response(method: str, url: str, **kwargs: object) -> requests.Response: @pytest.fixture def network() -> Iterator[tuple[MagicMock, MagicMock]]: - """Mock only credential lookup and the HTTP boundary, keeping production operations real.""" + """Mock credentials and both plain/report-owned HTTP boundaries, keeping operations real.""" with ( patch( "regshape.libs.transport.client.resolve_credentials", @@ -115,6 +114,7 @@ def network() -> Iterator[tuple[MagicMock, MagicMock]]: "regshape.libs.decorators.call_details.requests.request", side_effect=_response, ) as http, + patch("requests.Session.request", side_effect=http), ): yield credentials, http @@ -146,7 +146,12 @@ def test_command_aliases_preserve_results_and_requests( ) assert result.exit_code == 0, result.output assert result.stdout == baseline.stdout - assert result.stderr == baseline.stderr == "" + if command in (("manifest", "get"), ("manifest", "put")): + direction = "Pull" if command[1] == "get" else "Push" + assert result.stderr.startswith(f"{direction} request report\n") + assert baseline.stderr.startswith(f"{direction} request report\n") + else: + assert result.stderr == baseline.stderr == "" assert http.call_args_list == original_requests assert credentials.call_args_list == original_credentials method, url = http.call_args.args @@ -204,7 +209,10 @@ def test_identical_mixed_aliases_execute_once( input=ARTIFACT, ) assert result.exit_code == 0, result.output - assert result.stderr == "" + if command in (("manifest", "get"), ("manifest", "put")): + assert "request report\n" in result.stderr + else: + assert result.stderr == "" assert credentials.call_count == http.call_count == 1 @@ -351,34 +359,25 @@ def test_manifest_file_and_structured_telemetry_stay_separate( _, http = network output, log = tmp_path / "manifest.json", tmp_path / "telemetry.log" - def configure_capture(config: TelemetryConfig) -> None: - """Avoid Click 8.1's unflushed stderr capture while retaining real telemetry writes.""" - assert isinstance(config.output, io.TextIOWrapper) - config.output.reconfigure(write_through=True) - configure_telemetry(config) - - with patch( - "regshape.libs.decorators.configure_telemetry", side_effect=configure_capture - ): - result = runner.invoke( - regshape, - [ - "--log-file", - str(log), - "manifest", - "get", - alias, - BASE + ":v1", - "--output", - str(output), - "--accept", - OCI_IMAGE_MANIFEST, - "--time-scenarios", - "--telemetry-format", - "json", - *extra, - ], - ) + result = runner.invoke( + regshape, + [ + "--log-file", + str(log), + "manifest", + "get", + alias, + BASE + ":v1", + "--output", + str(output), + "--accept", + OCI_IMAGE_MANIFEST, + "--time-scenarios", + "--telemetry-format", + "json", + *extra, + ], + ) assert result.exit_code == 0, result.output assert result.stdout == "" and http.call_count == 1 document = json.loads(output.read_text()) @@ -470,7 +469,8 @@ def test_operational_errors_are_identical_for_new_and_legacy_aliases( new = runner.invoke(regshape, _arguments(command, "-a"), input=ARTIFACT) assert old.exit_code == new.exit_code == 1 assert old.stdout == new.stdout == "" - assert old.stderr == new.stderr and "Error" in new.stderr + assert old.stderr.splitlines()[0] == new.stderr.splitlines()[0] + assert new.stderr.startswith("Error") assert http.call_count == 1 diff --git a/src/regshape/tests/test_artifact_download.py b/src/regshape/tests/test_artifact_download.py index 9a55068..da57d9e 100644 --- a/src/regshape/tests/test_artifact_download.py +++ b/src/regshape/tests/test_artifact_download.py @@ -499,20 +499,21 @@ def get(client, path, **kwargs): ) assert result.exit_code == int(fail), result.exception warning = f"Warning: ETag changed for {affected} blobs;" + before_report = result.stderr.split("Pull request report", 1)[0] assert ( result.stderr.count("Warning:") == 1 - and warning in result.stderr.splitlines()[-1] + and warning in before_report.splitlines()[-1] ) if fail: assert not result.stdout - assert "did not complete" in result.stderr.splitlines()[-1] + assert "did not complete" in before_report.splitlines()[-1] assert not list(tmp_path.iterdir()) else: if suppressed == "--json": assert json.loads(result.stdout)["blobs"] == affected else: assert result.stdout.startswith("Downloaded complete artifact.") - assert "verified their digests" in result.stderr.splitlines()[-1] + assert "verified their digests" in before_report.splitlines()[-1] assert set(tmp_path.iterdir()) == {tmp_path / "out"} for _, _, responses in receivers.values(): assert all(response.close_calls == 1 for response in responses) diff --git a/src/regshape/tests/test_artifact_pull_cli.py b/src/regshape/tests/test_artifact_pull_cli.py index 3575fb1..c2790a8 100644 --- a/src/regshape/tests/test_artifact_pull_cli.py +++ b/src/regshape/tests/test_artifact_pull_cli.py @@ -236,7 +236,7 @@ def test_four_roots_exact_results_and_push_roundtrip( "downloaded_objects": len(objects), "embedded_objects": 0, "reused_references": 0, "bytes_downloaded": sum(map(len, objects.values())), "bytes_stored": sum(map(len, objects.values())), } - assert not console.err.text + assert console.err.text.startswith("Pull request report\n") else: assert console.out.text == ( "Downloaded complete artifact.\n" @@ -257,6 +257,7 @@ def test_four_roots_exact_results_and_push_roundtrip( ): pushed = runner.invoke(regshape, [ "layout", "push", "--path", str(output), "--dest", "registry.example/dest:copy", "--json", + "--telemetry-verbosity", "0", ]) assert pushed.exit_code == 0, pushed.exception assert registry.references["copy"] == address(root) @@ -446,12 +447,15 @@ def test_artifact_rows_preserve_state_on_reflow(width: int) -> None: def test_all_object_kinds_respect_suppression( runner: CliRunner, tmp_path: Path, options: list[str], interactive: bool, ) -> None: - """Nonterminal/structured/disabled modes stream the same graph with no progress controls or phase text.""" + """Suppressed animation retains the report without progress controls or local phase text.""" root, objects = _graph("nested", "sha256") registry, console = ObjectRegistry(root, objects), ArtifactConsole(interactive=interactive) result, _ = _invoke(runner, console, registry, tmp_path / "out", options) assert result.exit_code == 0, result.exception - assert console.err.text == "" + assert "request_report" in console.err.text if "--telemetry-format" in options else ( + console.err.text.startswith("Pull request report\n") + ) + assert "\x1b" not in console.err.text assert len(registry.calls) == len(objects) assert "\x1b" not in console.out.text @@ -801,14 +805,18 @@ def test_command_forwards_each_budget_to_the_real_operation( def test_network_cancel_and_terminal_failures_preserve_error_and_cleanup( runner: CliRunner, tmp_path: Path, fault: str, ) -> None: - """Cancellation aborts, actual transport failures report nonzero, and terminal exceptions retain identity.""" + """Healthy sinks show failed/cancelled rows; failed terminals retain errors without cleanup retries.""" root, objects = _graph("simple", "sha256") console, registry = ArtifactConsole(), ObjectRegistry(root, objects) original = registry.respond primary = OSError("synthetic terminal sink fault") + failed_sink_calls: list[tuple[int, int]] = [] if fault == "terminal": console.err.failure = primary console.err.failure_when = lambda text: "Downloading" in text + console.err.before_failure = lambda: failed_sink_calls.append( + (len(console.err.writes), terminal_flush.call_count) + ) def respond(method: str, url: str, **kwargs: Any) -> StreamResponse: """Fail after a root was stored, so completed rows and an active blob exercise different states.""" @@ -820,16 +828,23 @@ def respond(method: str, url: str, **kwargs: Any) -> StreamResponse: return registry.response(429) return original(method, url, **kwargs) - with patch.object(registry, "respond", side_effect=respond): + with ( + patch.object(registry, "respond", side_effect=respond), + patch.object(console.err, "flush", wraps=console.err.flush) as terminal_flush, + ): result, _ = _invoke(runner, console, registry, tmp_path / "out") assert result.exit_code == 1 if fault == "terminal": assert result.exception is primary + assert len(failed_sink_calls) == 1 + assert (len(console.err.writes), terminal_flush.call_count) == failed_sink_calls[0] + else: + assert any(("Cancelled" if fault == "cancel" else "Failed") in row for row in _rows(console)) if fault == "cancel": assert isinstance(result.exception, SystemExit) assert "Aborted!" in console.err.text - assert any(("Cancelled" if fault == "cancel" else "Failed") in row for row in _rows(console)) assert console.out.text == "" and not list(tmp_path.iterdir()) + assert not console.out.closed and not console.err.closed assert all(response.close_calls == 1 for response in registry.responses) @@ -1009,6 +1024,7 @@ def registry_request(request: requests.PreparedRequest) -> WireResponse: with ( _console_streams(runner, console), patch("regshape.libs.transport.client.resolve_credentials", return_value=("synthetic-user", "synthetic-pass")), + patch("regshape.cli.telemetry.activate_reporting"), # Legacy BaseAdapter fixture cannot observe reports. patch("regshape.cli.artifact.ProgressDisplay", side_effect=console.artifact_display), ): result = runner.invoke(regshape, ["artifact", "pull", "-a", _SOURCE, "-o", str(output)]) @@ -1220,7 +1236,7 @@ def write(text: str) -> int: assert "\x1b" not in console.out.text and "ETag" not in console.out.text if outcome == "success": assert result.exit_code == 0, result.exception - assert console.err.text.endswith( + assert console.err.text.split("Pull request report", 1)[0].endswith( "Warning: ETag changed for 2 blobs; restarted them as full-stream downloads " "and verified their digests.\n" ) @@ -1229,7 +1245,7 @@ def write(text: str) -> int: else: assert result.exit_code == 1 and not console.out.text assert "verified their digests" not in console.err.text - assert console.err.text.endswith( + assert console.err.text.split("Pull request report", 1)[0].endswith( "Warning: ETag changed for 2 blobs; full-stream fallbacks were attempted, " "but the operation did not complete.\n" ) @@ -1246,7 +1262,10 @@ def test_partial_summary_error_preserves_bytes_and_complete_artifact( primary = OSError("synthetic partial stdout failure") console.out.failure, console.out.partial = primary, 12 output = tmp_path / "out" - result, _ = _invoke(runner, console, registry, output, ["--json"] if structured else []) + result, _ = _invoke( + runner, console, registry, output, + [*(["--json"] if structured else []), "--telemetry-verbosity", "0"], + ) assert result.exception is primary and result.exit_code == 1 assert len(console.out.text) == 12 and "\x1b" not in console.out.text assert console.terminal.rows[-1].endswith(console.out.text.split("\n")[-1]) @@ -1374,6 +1393,7 @@ def failed_connection(request: requests.PreparedRequest) -> WireResponse: with ( _console_streams(runner, console), patch("regshape.libs.transport.client.resolve_credentials", return_value=(None, None)), + patch("regshape.cli.telemetry.activate_reporting"), # Keep timing/security checks on the legacy BaseAdapter. patch("regshape.cli.artifact.ProgressDisplay", side_effect=console.artifact_display), ): result = runner.invoke(regshape, [ diff --git a/src/regshape/tests/test_artifact_push.py b/src/regshape/tests/test_artifact_push.py index 2599570..0da7d19 100644 --- a/src/regshape/tests/test_artifact_push.py +++ b/src/regshape/tests/test_artifact_push.py @@ -203,7 +203,7 @@ def test_pull_push_command_round_trip( assert len(registry.calls) == calls_before_dry_run result = _runner().invoke(regshape, command) assert result.exit_code == 0, (result.output, result.exception) - actual, planned = json.loads(result.output), json.loads(dry.output) + actual, planned = json.loads(result.stdout), json.loads(dry.stdout) assert [(item["digest"], item["reference"]) for item in actual["manifests"]] == [ (item["digest"], item["reference"]) for item in planned["manifests"] ] @@ -500,6 +500,7 @@ def test_unsupported_platform_guard(tmp_path: Path) -> None: for dry in (False, True): result = _runner().invoke(regshape, [ "layout", "push", "--path", str(source), "--dest", "registry.example/dest", + "--telemetry-verbosity", "0", *(["--dry-run"] if dry else []), ]) assert result.exit_code == 1 and "unsupported" in result.stderr @@ -637,7 +638,8 @@ def test_docker_command_real_conversion_and_push(chunked: bool, tag: str | None) with ( patch("regshape.libs.docker.operations.docker_sdk") as docker, patch("regshape.libs.transport.client.resolve_credentials", return_value=(None, None)), - patch("regshape.libs.decorators.call_details.requests.request", side_effect=registry.respond), + patch("regshape.libs.decorators.call_details.requests.request", side_effect=registry.respond) as http, + patch("requests.Session.request", side_effect=http), ): docker.from_env.return_value.images.get.return_value.save.return_value = iter([tar_bytes]) result = _runner().invoke(regshape, [ @@ -646,7 +648,7 @@ def test_docker_command_real_conversion_and_push(chunked: bool, tag: str | None) "--json", *(["--chunked", "--chunk-size", "13"] if chunked else []), ]) assert result.exit_code == 0, (result.output, result.exception) - assert json.loads(result.output)["manifests_pushed"] == 1 + assert json.loads(result.stdout)["manifests_pushed"] == 1 assert registry.documents[-1][0] == (tag or "latest") assert all(response.close_calls == 1 for response in registry.responses) diff --git a/src/regshape/tests/test_blob_ranges.py b/src/regshape/tests/test_blob_ranges.py index 048ad01..0f4fa2e 100644 --- a/src/regshape/tests/test_blob_ranges.py +++ b/src/regshape/tests/test_blob_ranges.py @@ -1094,6 +1094,7 @@ def test_cli_retry_override_reaches_real_http_429(runner, tmp_path, range_server "--insecure", "blob", "get", "--repo", f"{authority}/repo", "--digest", address(PAYLOAD), "--ranges-per-blob", "3", "--range-size", str(R), "--download-retries", str(retries), "--scratch-dir", str(tmp_path), "--no-progress", + "--telemetry-verbosity", "0", ]) assert state["throttle_calls"] == min(retries + 1, 3) assert len(waits) == retries diff --git a/src/regshape/tests/test_component_cli.py b/src/regshape/tests/test_component_cli.py index 0a11ef7..f23ccb4 100644 --- a/src/regshape/tests/test_component_cli.py +++ b/src/regshape/tests/test_component_cli.py @@ -224,7 +224,7 @@ def test_exact_bytes_and_completed_eight_field_results(runner, tmp_path, compone "component": component, "layer_index": index, "digest": address(payload), "size": len(payload), "media_type": f"application/example.{component}", "output_path": str(output), } - assert console.err.text == "" + assert console.err.text.startswith("Pull request report\n") else: selected = "config" if component == "config" else f"layer {index}" assert console.out.text == ( @@ -285,7 +285,7 @@ def test_layer_selection_errors_are_actionable_and_do_not_acquire_blobs(runner, runner, console, registry, tmp_path / "out", component="layer", index=index, options=("--no-progress",), ) assert result.exit_code == 1 and console.out.text == "" - assert console.err.text == f"Error [{_SOURCE}]: {message}\n" + assert console.err.text.startswith(f"Error [{_SOURCE}]: {message}\nPull request report - FAILED\n") assert len(registry.calls) == 1 assert not list(tmp_path.iterdir()) diff --git a/src/regshape/tests/test_image_progress.py b/src/regshape/tests/test_image_progress.py index fd45b0d..4bec17b 100644 --- a/src/regshape/tests/test_image_progress.py +++ b/src/regshape/tests/test_image_progress.py @@ -331,15 +331,13 @@ def export(image: str, output: Path, *, platform: str | None) -> None: if mode == "disabled": args.append("--no-progress") if mode == "structured": - if command == "layout": - args.extend(["--telemetry-format", "json", "--time-scenarios"]) - else: - configure_telemetry(TelemetryConfig(output_format="json", time_scenarios_enabled=True)) + args.extend(["--telemetry-format", "json", "--time-scenarios"]) with ( patch(f"regshape.cli.{command}.ProgressDisplay", side_effect=display), patch("regshape.libs.docker.operations.export_image", side_effect=export), patch("regshape.libs.transport.client.resolve_credentials", return_value=(None, None)), - patch("regshape.libs.decorators.call_details.requests.request", side_effect=registry.respond), + patch("regshape.libs.decorators.call_details.requests.request", side_effect=registry.respond) as http, + patch("requests.Session.request", side_effect=http), ): result = _runner().invoke(regshape, args) assert result.exit_code == 0, result.output @@ -352,7 +350,7 @@ def export(image: str, output: Path, *, platform: str | None) -> None: assert all(not output.parent.exists() for output in exported) if mode == "json": document = json.loads(result.stdout) - assert result.stderr == "" + assert result.stderr.startswith("Push request report\n") if command == "layout": assert set(document) == {"layout_path", "destination", "manifests", "summary"} assert document["summary"]["blobs_uploaded"] == 1 and document["summary"]["blobs_skipped"] == 3 @@ -401,7 +399,8 @@ def export(image: str, output: Path, *, platform: str | None) -> None: patch("regshape.cli.docker.ProgressDisplay", side_effect=display), patch("regshape.libs.docker.operations.export_image", side_effect=export), patch("regshape.libs.transport.client.resolve_credentials", return_value=(None, None)), - patch("regshape.libs.decorators.call_details.requests.request", side_effect=registry.respond), + patch("regshape.libs.decorators.call_details.requests.request", side_effect=registry.respond) as http, + patch("requests.Session.request", side_effect=http), ): result = _runner().invoke(regshape, [ "docker", "push", "--image", "example:latest", "--dest", "registry.example.invalid/repo", diff --git a/src/regshape/tests/test_layout_push.py b/src/regshape/tests/test_layout_push.py index baa329a..c4caf44 100644 --- a/src/regshape/tests/test_layout_push.py +++ b/src/regshape/tests/test_layout_push.py @@ -389,7 +389,7 @@ def test_push_json_output(self, mock_push, mock_client_cls, tmp_path): "--json", ]) assert result.exit_code == 0, result.output - data = json.loads(result.output) + data = json.loads(result.stdout) assert data["summary"]["manifests_pushed"] == 1 assert data["manifests"][0]["status"] == "pushed" @@ -429,7 +429,7 @@ def test_push_dry_run_json(self, tmp_path): "--json", ]) assert result.exit_code == 0, result.output - data = json.loads(result.output) + data = json.loads(result.stdout) assert data["dry_run"] is True assert len(data["manifests"]) == 1 assert len(data["manifests"][0]["blobs"]) >= 1 diff --git a/src/regshape/tests/test_manifest_cli.py b/src/regshape/tests/test_manifest_cli.py index 5607c92..6f4989d 100644 --- a/src/regshape/tests/test_manifest_cli.py +++ b/src/regshape/tests/test_manifest_cli.py @@ -82,14 +82,10 @@ def test_registry_constructor_auth_faults_use_command_boundaries( original_exit = ProgressDisplay.__exit__ def fail_resolution(*args, **kwargs): - """Capture any command-owned log, then fail before registry I/O. - - Docker push delegates without telemetry_options, so it has no owned log. - """ + """Capture every command's owned log, then fail before registry I/O.""" config = get_telemetry_config() - if arguments[0] != "docker": - assert config.log_file is not None and not config.log_file.closed - logs.append(config.log_file) + assert config.log_file is not None and not config.log_file.closed + logs.append(config.log_file) raise error def exit_display(self, *args): @@ -119,7 +115,7 @@ def exit_display(self, *args): request.assert_not_called() session_request.assert_not_called() execute.assert_not_called() - assert bool(logs) is (arguments[0] != "docker") + assert logs assert all(log.closed for log in logs) assert bool(exits) is has_progress assert not output.exists() diff --git a/src/regshape/tests/test_manifest_cli_progress.py b/src/regshape/tests/test_manifest_cli_progress.py index 46cd6ae..40c7c67 100644 --- a/src/regshape/tests/test_manifest_cli_progress.py +++ b/src/regshape/tests/test_manifest_cli_progress.py @@ -204,13 +204,14 @@ def invoke( *, reference: str = REFERENCE, ) -> tuple[Result, MagicMock]: - """Execute the actual command, library and transport with only HTTP/credentials mocked.""" + """Execute real command/SDK with both ordinary and report-owned Session I/O mocked.""" with ( patch( "regshape.libs.transport.client.resolve_credentials", return_value=(None, None), ), patch("requests.request", return_value=response) as send, + patch("requests.Session.request", side_effect=send), patch("regshape.cli.manifest.ProgressDisplay", side_effect=console.display), ): result = runner.invoke( @@ -771,7 +772,8 @@ def chunks(chunk_size: int = 1, decode_unicode: bool = False) -> Iterator[bytes] "regshape.libs.transport.client.resolve_credentials", return_value=(None, None), ), - patch("requests.request", return_value=response), + patch("requests.request", return_value=response) as send, + patch("requests.Session.request", side_effect=send), patch.object(response, "iter_content", side_effect=chunks), patch("regshape.cli.manifest.ProgressDisplay", side_effect=console.display), ): @@ -892,7 +894,8 @@ def test_log_file_closes_even_when_flush_and_command_fail(runner: CliRunner) -> "regshape.libs.transport.client.resolve_credentials", return_value=(None, None), ), - patch("requests.request", return_value=StreamResponse(b"payload")), + patch("requests.request", return_value=StreamResponse(b"payload")) as send, + patch("requests.Session.request", side_effect=send), patch("regshape.cli.manifest.ProgressDisplay", side_effect=console.display), ): result = runner.invoke( diff --git a/src/regshape/tests/test_progress_display.py b/src/regshape/tests/test_progress_display.py index b391f43..4bc5e21 100644 --- a/src/regshape/tests/test_progress_display.py +++ b/src/regshape/tests/test_progress_display.py @@ -484,7 +484,8 @@ def respond(method: str, url: str, **kwargs: object) -> requests.Response: patch.object(terminal, "flush", side_effect=flush), patch("regshape.cli.blob.ProgressDisplay", side_effect=display), patch("regshape.libs.transport.client.resolve_credentials", return_value=(None, None)), - patch("regshape.libs.decorators.call_details.requests.request", side_effect=respond), + patch("regshape.libs.decorators.call_details.requests.request", side_effect=respond) as http, + patch("requests.Session.request", side_effect=http), ): result = runner.invoke(regshape, args) assert result.exit_code != 0 and result.stdout == "" and failed @@ -1229,11 +1230,14 @@ def test_blob_upload_real_library_consumption( terminal, now = Terminal(), [0.0] observe = ProgressDisplay.observe original_stat = os.fstat + source_stat = upload_source.stat() def stat_source(descriptor: int) -> os.stat_result: """Model virtual-file size hints while retaining an actual file-backed reader.""" result = original_stat(descriptor) - if source_kind.startswith("virtual-"): + if source_kind.startswith("virtual-") and ( + result.st_dev, result.st_ino + ) == (source_stat.st_dev, source_stat.st_ino): fields = list(result) fields[stat.ST_SIZE] = { "virtual-zero": 0, "virtual-oversized": 4096, "virtual-undersized": 2, @@ -1291,7 +1295,8 @@ def respond(method: str, url: str, **kwargs: object) -> requests.Response: patch.object(ProgressDisplay, "observe", record), patch("regshape.libs.blobs.operations.os.fstat", side_effect=stat_source), patch("regshape.libs.transport.client.resolve_credentials", return_value=(None, None)), - patch("regshape.libs.decorators.call_details.requests.request", side_effect=respond), + patch("regshape.libs.decorators.call_details.requests.request", side_effect=respond) as http, + patch("requests.Session.request", side_effect=http), ): result = runner.invoke(regshape, args) assert result.exit_code == 0, result.output @@ -1307,7 +1312,10 @@ def respond(method: str, url: str, **kwargs: object) -> requests.Response: e.total_bytes == (len(data) if known_size else None) for e in observations if e.phase != TransferPhase.PREPARING ) - assert observations[-1].phase == TransferPhase.COMPLETED and result.stderr == "" + assert observations[-1].phase == TransferPhase.COMPLETED + assert ("request_report" in result.stderr if mode == "structured" else ( + result.stderr.startswith("Push request report\n") + )) if mode == "tty": if data: assert any("Uploading 2 B" in row for frame in frames for row in frame) @@ -1408,5 +1416,5 @@ def display(*, disabled: bool) -> ProgressDisplay: result = runner.invoke(regshape, args) assert result.exit_code == 0, result.output assert json.loads(result.stdout)["digest"] == digest - assert result.stderr == "" and http.call_count == 1 + assert result.stderr.startswith("Pull request report\n") and http.call_count == 1 assert ("Downloaded" in terminal.getvalue()) is not disabled diff --git a/src/regshape/tests/test_request_report.py b/src/regshape/tests/test_request_report.py index 4ca31b5..c0fc40e 100644 --- a/src/regshape/tests/test_request_report.py +++ b/src/regshape/tests/test_request_report.py @@ -10,6 +10,7 @@ import sqlite3 import subprocess import sys +from threading import Event import pytest import requests @@ -36,6 +37,67 @@ def reports(tmp_path): yield collector +@pytest.mark.parametrize("explicit", [False, True]) +def test_lazy_factory_acquires_once_only_when_no_explicit_collector(reports, explicit): + """Caller-owned factories wait for a scope; a supplied collector always takes precedence.""" + acquired = [] + + def acquire(): + """Return the caller's live collector only when no explicit collector was configured.""" + assert not explicit + acquired.append(reports) + return reports + + config = TelemetryConfig( + request_report_collector=reports if explicit else None, + request_report_factory=acquire, + ) + with telemetry_session(config): + assert not acquired + for _ in range(2): + with request_report_scope("test", "pull") as scope: + assert scope is not None + assert config.request_report_collector is reports + assert len(acquired) == int(not explicit) + assert len(list(reports.iter_reports())) == 2 + + +def test_lazy_factory_is_shared_across_copied_worker_contexts(reports): + """Concurrent first scopes must share one acquired collector, without orphaned stores.""" + first_entered, second_entered, release, second_started = Event(), Event(), Event(), Event() + acquired = [] + + def acquire(): + """Hold the first acquisition while another copied context enters a root scope.""" + acquired.append(reports) + (first_entered if len(acquired) == 1 else second_entered).set() + assert release.wait(5) + return reports + + config = TelemetryConfig(request_report_factory=acquire) + + def operation(*, second=False): + """Establish independent worker scopes against the same caller-owned configuration.""" + if second: + second_started.set() + with request_report_scope("test", "pull") as scope: + assert scope is not None + + with telemetry_session(config), ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(copy_context().run, operation) + assert first_entered.wait(5) + second = pool.submit(copy_context().run, lambda: operation(second=True)) + try: + assert second_started.wait(5) + assert not second_entered.wait(0.1) + finally: + release.set() + first.result(timeout=5) + second.result(timeout=5) + assert acquired == [reports] + assert len(list(reports.iter_reports())) == 2 + + def _request(scope, group, url=URL, *, attempt=1, call_id=None, hop=0, size=7): """Observe one complete synthetic dispatch without performing network/body I/O.""" call = scope.start_call(group, url, attempt=attempt, call_id=call_id, diff --git a/src/regshape/tests/test_request_report_cli.py b/src/regshape/tests/test_request_report_cli.py new file mode 100644 index 0000000..982fcc7 --- /dev/null +++ b/src/regshape/tests/test_request_report_cli.py @@ -0,0 +1,978 @@ +"""Verify automatic CLI reports against real library models and physical dispatches. + +Network fixtures replace only adapter I/O; commands retain SDK validation, +streaming, workers, publication, telemetry and result/error lifetimes. +""" + +import io +import json +import os +import sys +from concurrent.futures import CancelledError +from contextlib import contextmanager, nullcontext + +import click +import pytest + +from regshape.cli.downloads import DownloadWarnings +from regshape.cli.main import regshape +from regshape.cli.request_report import render_text, request_reporting +from regshape.cli.telemetry import telemetry_options +from regshape.libs.blobs import DownloadStats, DownloadStatus +from regshape.libs.decorators import ( + RequestReportCollector, + TelemetryConfig, + configure_telemetry, + get_telemetry_config, + request_report_scope, + track_scenario, + track_time, +) +from regshape.libs.decorators._request_report_store import ReportStore +from regshape.libs.decorators.request_report import Reference, RequestReport +from regshape.libs.decorators.sanitization import sanitize_report_location +from regshape.libs.errors import RequestReportError +from regshape.libs.models.blob import BlobInfo +from regshape.libs.models.mediatype import OCI_IMAGE_CONFIG, OCI_IMAGE_MANIFEST +from regshape.tests.artifact_fixtures import address, document, edge, write_layout +from regshape.tests.test_artifact_options import runner as runner # noqa: PLC0414 - minimum Click fixture. +from regshape.tests.test_pull_request_report import _registry +from regshape.tests.test_push_request_report import _Registry +from regshape.tests.test_request_observation import _ImmutableError +from regshape.tests.test_request_observation import network as network # noqa: PLC0414 - physical dispatch fixture. + +pytestmark = pytest.mark.skipif(sys.platform not in {"darwin", "linux"}, + reason="Request report storage requires native private namespaces") +SOURCE = "registry.example/repo:moving" +URL = "https://registry.example/v2/repo/manifests/moving" +DIGEST = "sha256:" + "a" * 64 + + +@pytest.fixture(autouse=True) +def isolated_telemetry(monkeypatch): + """Keep retained CLI configs and credential resolution local to each test.""" + previous = get_telemetry_config() + monkeypatch.setattr("regshape.libs.transport.client.resolve_credentials", lambda *a: (None, None)) + configure_telemetry(TelemetryConfig()) + yield + configure_telemetry(previous) + + +def _payloads(): + """Build a simple valid artifact with ordered config/layer descriptors and exact digests.""" + config, layer = b'{"architecture":"amd64","os":"linux"}', b"synthetic-layer" + root = document(config=edge(config, OCI_IMAGE_CONFIG), layers=[edge(layer)]) + return root, {address(root): root, address(config): config, address(layer): layer}, config, layer + + +@pytest.mark.parametrize("command", ["artifact", "config", "layer", "blob", "manifest"]) +@pytest.mark.parametrize("format_", ["text", "json"]) +def test_pull_leaves_keep_stdout_and_report_actual_requests( + tmp_path, monkeypatch, network, runner, command, format_, +): + """Every supported pull leaf reports exact dispatches despite JSON results and --no-progress.""" + root, objects, config, layer = _payloads() + _registry(monkeypatch, network, root, objects) + output = tmp_path / "output" + if command == "artifact": + args = ["artifact", "pull", "-a", SOURCE, "-o", str(output), "--json", "--sequential"] + elif command in {"config", "layer"}: + args = [command, "get", "-a", SOURCE, "-o", str(output), "--json", "--sequential"] + if command == "layer": + args += ["--index", "0"] + elif command == "blob": + args = ["blob", "get", "--repo", "registry.example/repo", "-d", address(layer), + "-o", str(output), "--sequential"] + else: + args = ["manifest", "get", "-a", SOURCE, "--raw"] + args += ["--no-progress"] + result = runner.invoke(regshape, [*args, "--telemetry-format", format_]) + assert result.exit_code == 0, (result.stderr, result.exception) + if command == "manifest": + assert result.stdout == root.decode() + "\n" + else: + data = json.loads(result.stdout) + assert "request_report" not in data and "report" not in data + if command in {"config", "layer"}: + assert len(data) == 8 + assert output.read_bytes() == (config if command == "config" else layer) + elif command == "blob": + assert output.read_bytes() == layer + assert network.ledger + if format_ == "json": + [report] = map(json.loads, result.stderr.splitlines()) + assert report["type"] == "request_report" + assert report["summary"]["request_attempt_count"] == len(network.ledger) + assert sorted(row["sequence"] for row in report["requests"]) == list(range(1, len(network.ledger) + 1)) + assert all(row["method"] == "GET" for row in report["requests"]) + assert report["collection"]["complete"] + else: + assert result.stderr.startswith("Pull request report\n") + for sequence in range(1, len(network.ledger) + 1): + assert f"#{sequence} GET " in result.stderr + assert f"Requests attempted: {len(network.ledger)}\n" in result.stderr + assert "Time to full response: 8.000000 s" in result.stderr + assert "Authentication" in result.stderr and "\x1b" not in result.stderr + + +@pytest.mark.parametrize("command", ["manifest", "blob", "chunked", "mount", "layout", "docker"]) +def test_push_leaves_log_equivalent_report_without_changing_results( + tmp_path, monkeypatch, network, runner, command, +): + """All push leaves expose actual methods; root append logs mirror one consolidated event.""" + registry = _Registry(monkeypatch, network) + root, objects, _, layer = _payloads() + source = tmp_path / "source" + source.write_bytes(root if command == "manifest" else layer) + if command == "manifest": + args = ["manifest", "put", "-a", SOURCE, "-f", str(source)] + elif command in {"blob", "chunked"}: + args = ["blob", "upload", "--repo", "registry.example/repo", "-d", address(layer), + "-f", str(source), "--no-progress"] + if command == "chunked": + args += ["--chunked", "--chunk-size", "3"] + elif command == "mount": + args = ["blob", "mount", "--repo", "registry.example/repo", "-d", address(layer), "--from-repo", "source"] + elif command == "layout": + layout = tmp_path / "layout" + write_layout(layout, root, objects, root_type=OCI_IMAGE_MANIFEST) + args = ["layout", "push", "--path", str(layout), "--dest", SOURCE, "--json", "--no-progress"] + else: + def export(image, output, **kwargs): + """Replace only the local Docker export, leaving registry push entirely real.""" + network.now += 13 + write_layout(output, root, objects, root_type=OCI_IMAGE_MANIFEST) + monkeypatch.setattr("regshape.libs.docker.operations.export_image", export) + args = ["docker", "push", "-i", "local:latest", "--dest", SOURCE, "--json", "--no-progress"] + log = tmp_path / "requests.log" + log.write_text("existing\n") + result = runner.invoke(regshape, ["--log-file", str(log), *args, "--telemetry-format", "json"]) + assert result.exit_code == 0, (result.stderr, result.exception) + [report] = map(json.loads, result.stderr.splitlines()) + assert report["operation"]["direction"] == "push" + assert log.read_text() == "existing\n" + result.stderr + assert report["summary"]["request_attempt_count"] == len(network.ledger) + assert [row["method"] for row in sorted(report["requests"], key=lambda r: r["sequence"])] == [ + method for method, _ in network.ledger + ] + assert report["summary"]["assets_uploaded"] == (0 if command == "mount" else + 3 if command in {"layout", "docker"} else 1) + assert report["collection"]["complete"] + if command == "layout": + assert report["operation"]["source"] == sanitize_report_location(str(layout)) + assert "private-session" not in result.stderr and "private-query" not in result.stderr + if command == "manifest": + assert result.stdout == f"Pushed: {address(root)}\n" + else: + data = json.loads(result.stdout) + assert "request_report" not in data and "report" not in data + assert registry.publications or command in {"blob", "chunked", "mount"} + + +def test_suppression_acquires_nothing_and_debug_flags_remain_opt_in(tmp_path, monkeypatch, network, runner): + """Verbosity zero keeps the old quiet execution path and never creates a report spool.""" + root, objects, _, _ = _payloads() + _registry(monkeypatch, network, root, objects) + + def forbidden(): + """Fail if a disabled command attempts collector acquisition.""" + raise AssertionError("disabled reporting allocated a collector") + + monkeypatch.setattr("regshape.cli.request_report.RequestReportCollector", forbidden) + result = runner.invoke(regshape, [ + "manifest", "get", "-a", SOURCE, "--raw", "--no-progress", "-tv", "0", + "--metrics", "--debug-calls", "--time-methods", "--time-scenarios", + ]) + assert result.exit_code == 0 and result.stderr == "" + assert result.stdout == root.decode() + "\n" + + +def test_dry_run_gets_library_owned_empty_report_without_a_client(tmp_path, monkeypatch, runner): + """A local plan is not a registry upload and issues neither probes nor credential lookups.""" + root, objects, _, _ = _payloads() + layout = tmp_path / "layout" + write_layout(layout, root, objects, root_type=OCI_IMAGE_MANIFEST) + + def forbidden(*args, **kwargs): + """Reject client construction on a local-only execution path.""" + raise AssertionError("dry run constructed a registry client") + + monkeypatch.setattr("regshape.cli.layout.RegistryClient", forbidden) + result = runner.invoke(regshape, [ + "layout", "push", "--path", str(layout), "--dest", SOURCE, "--dry-run", + "--json", "--telemetry-format", "json", + ]) + assert result.exit_code == 0, result.stderr + assert json.loads(result.stdout)["dry_run"] + report = json.loads(result.stderr) + assert report["operation"]["source"] == sanitize_report_location(str(layout)) + assert report["requests"] == report["calls"] == [] + assert report["summary"]["request_attempt_count"] == report["summary"]["remote_elapsed_s"] == 0 + assert report["summary"]["assets_uploaded"] is None + + +def _observe(scope, group, url=URL, *, attempt=1, call_id=None, hops=1): + """Record deterministic physical facts through public APIs without network or clock inference.""" + call_id = scope.start_call( + group, url, attempt=attempt, call_id=call_id, + reason="initial" if attempt == 1 else "authentication", registry_path=True, + ) + for hop in range(hops): + sequence = scope.start_request( + call_id, url, "CUSTOM-METHOD", attempt=attempt, hop=hop, registry_path=True, + ) + scope.record_headers(sequence, 307 if hop + 1 < hops else 200) + scope.finish_request( + sequence, body_state="complete", sent_body_bytes=0, received_body_bytes=3, + redirect_to_sequence=sequence + 1 if hop + 1 < hops else None, + redirect_target=url if hop + 1 < hops else None, registry_path=True, + ) + scope.finish_call( + call_id, attempt, state="complete", final_url=url, last_url=url, + redirect_response_s=0.1, chain_headers_s=0.2, chain_elapsed_s=0.3, registry_path=True, + ) + return call_id + + +def test_text_json_same_model_preserves_attempts_hops_order_and_untrusted_labels(tmp_path): + """Text projects all stored rows and exact library totals without terminal injection or truncation.""" + with RequestReportCollector(spool_dir=tmp_path) as collector: + with collector.operation("fixture", "pull") as scope: + group = scope.add_group("Layer 0\x1b[2J\u202e", kind="layer", digest=DIGEST, + digest_source="descriptor") + scope.add_reference(group, Reference(None, 0, "layer", "linux/amd64")) + scope.add_reference(group, Reference(None, 2, "content", None)) + _observe(scope, "authentication", "https://auth.example/token?secret=canary") + call = _observe(scope, group, hops=3) + _observe(scope, group, call_id=call, attempt=2) + [report] = collector.iter_reports() + text, json_output = io.StringIO(), io.StringIO() + render_text(report, text) + report.write_json(json_output) + data, rendered = json.loads(json_output.getvalue()), text.getvalue() + assert rendered.index("Group: Authentication") < rendered.index("Group: Layer 0") + for row in data["requests"]: + assert f'#{row["sequence"]} {row["method"]} {row["endpoint"]}' in rendered + assert f'Time to full response: {row["full_response_s"]:.6f} s' in rendered + assert rendered.count(" Call ") == len(data["calls"]) == 3 + assert "attempt 2 (authentication)" in rendered + assert "Redirects to #3" in rendered and "Redirects to #4" in rendered + assert "Redirect responses: 0.100000 s" in rendered + assert "Original request to final headers: 0.200000 s" in rendered + assert "Complete request chain: 0.300000 s" in rendered + assert f'Requests attempted: {data["summary"]["request_attempt_count"]}' in rendered + assert "ordinal: 0" in rendered and "ordinal: 2" in rendered + assert DIGEST in rendered and "\x1b" not in rendered and "\u202e" not in rendered + assert "canary" not in rendered and "canary" not in json_output.getvalue() + + +@pytest.mark.parametrize("primary", [ + None, click.ClickException("expected failure"), KeyboardInterrupt(), + CancelledError(), RuntimeError("private-message"), +]) +def test_results_diagnostics_warnings_and_primary_errors_precede_report(runner, primary): + """The outer handoff renders last and preserves unexpected/immutable error identity.""" + @click.command() + @request_reporting + @telemetry_options + @track_time + def command(): + """Finalize one library operation, then emit the command's result or error.""" + with request_report_scope("test", "pull"): + if primary is not None: + raise primary + click.echo('{"result":"unchanged"}') + click.echo("Warning: deferred", err=True) + + result = runner.invoke(command, ["--time-methods"]) + assert result.exit_code == (0 if primary is None else 1) + assert result.stderr.index("telemetry") < result.stderr.index("Pull request report") + assert result.stderr.endswith(" Missing request records: 0\n") + if primary is None: + assert json.loads(result.stdout) == {"result": "unchanged"} + assert result.stderr.index("Warning: deferred") < result.stderr.index("Pull request report") + else: + assert not result.stdout + if isinstance(primary, (CancelledError, RuntimeError)): + assert result.exception is primary + if isinstance(primary, KeyboardInterrupt): + assert result.stderr.count("Aborted!") == 1 + assert result.stderr.index("Aborted!") < result.stderr.index("Pull request report - CANCELLED") + assert "private-message" not in result.stderr + + +def test_collection_failure_follows_result_and_precedes_incomplete_report(monkeypatch, runner): + """Spool exhaustion changes diagnostic exit status, never the successful operation outcome.""" + def limited(): + """Allocate valid storage, then exhaust its detail budget before operation entry.""" + collector = RequestReportCollector() + collector._store.budget = 1 + return collector + + monkeypatch.setattr("regshape.cli.request_report.RequestReportCollector", limited) + + @click.command() + @request_reporting + @telemetry_options + def command(): + """Complete a no-network operation whose metadata budget is exhausted.""" + with request_report_scope("local", "push"): + pass + click.echo("Acknowledged push") + + result = runner.invoke(command, []) + assert result.exit_code == 1 and result.stdout == "Acknowledged push\n" + assert result.stderr.index("collection failed") < result.stderr.index("Push request report") + assert "COLLECTION INCOMPLETE" in result.stderr and "Outcome: Succeeded" in result.stderr + assert "not rolled back" in result.stderr + + +class _FailingSink(io.StringIO): + """Fail a selected write/flush once and count forbidden retries to that borrowed sink.""" + + def __init__(self, *, fail_flush=False): + """Start healthy and fail only after report output begins.""" + super().__init__() + self.fail_flush = fail_flush + self.started = False + self.failures = 0 + self.after_failure = 0 + self.error = BrokenPipeError("private-sink-message") + + def write(self, text): + """Reject a report write, or all writes after the first known failure.""" + if self.failures: + self.after_failure += 1 + raise self.error + self.started |= "request report" in text + if self.started and not self.fail_flush: + self.failures += 1 + raise self.error + return super().write(text) + + def flush(self): + """Fail report flushing without closing the caller's sink.""" + if self.started and self.fail_flush: + if self.failures: + self.after_failure += 1 + self.failures += 1 + raise self.error + return super().flush() + + +@pytest.mark.parametrize("fail_flush", [False, True]) +@pytest.mark.parametrize("primary", [None, RuntimeError("primary")]) +def test_stderr_failure_is_not_retried_and_log_report_survives( + tmp_path, monkeypatch, runner, fail_flush, primary, +): + """A failed stderr remains borrowed; a healthy append log still receives the full report.""" + sink = _FailingSink(fail_flush=fail_flush) + original = runner.isolation + + @contextmanager + def isolation(*args, **kwargs): + """Substitute only diagnostic stderr for the complete invocation lifetime.""" + with original(*args, **kwargs) as streams: + monkeypatch.setattr(sys, "stderr", sink) + yield streams + + monkeypatch.setattr(runner, "isolation", isolation) + + @click.command() + @request_reporting + @telemetry_options + def command(): + """Create a settled report before the destination fails during rendering.""" + with request_report_scope("test", "push"): + if primary is not None: + raise primary + click.echo("Pushed") + + log = tmp_path / "report.log" + result = runner.invoke(command, [], obj={"log_file": str(log)}) + assert result.exit_code == 1 + assert sink.failures == 1 and sink.after_failure == 0 + assert not sink.closed + assert "Push request report" in log.read_text() + assert log.read_text().endswith("Missing request records: 0\n") + if primary is not None: + assert result.exception is primary + + +def test_real_deferred_download_warning_precedes_report(monkeypatch, runner): + """The report outlives the real warning context, not merely an inline diagnostic.""" + def download(*, download_status_callback, **kwargs): + """Complete a library scope and notify the existing warning collector of a fallback.""" + with request_report_scope("test", "pull"): + download_status_callback(DownloadStatus( + "blob", DIGEST, "fallback", "full", "etag_changed", None, 2, DownloadStats(), + )) + return BlobInfo(digest=DIGEST, content_type="application/octet-stream", size=3) + + monkeypatch.setattr("regshape.cli.blob.get_blob", download) + result = runner.invoke(regshape, [ + "blob", "get", "--repo", "registry.example/repo", "-d", DIGEST, "--no-progress", + ]) + assert result.exit_code == 0, result.stderr + assert json.loads(result.stdout)["digest"] == DIGEST + assert result.stderr.count("Warning: ETag changed") == 1 + assert result.stderr.index("Warning: ETag changed") < result.stderr.index("Pull request report") + + +def test_collector_initialization_failure_is_sanitized(monkeypatch, runner): + """A storage-acquisition failure is visible without raw exception content or a false result.""" + def unavailable(): + """Reject spool acquisition with a sensitive-looking diagnostic.""" + raise OSError("private-canary") + + monkeypatch.setattr("regshape.cli.request_report.RequestReportCollector", unavailable) + + @click.command() + @request_reporting + @telemetry_options + def command(): + """Never acknowledge an operation when diagnostic initialization fails.""" + with request_report_scope("test", "pull"): + pass + click.echo("unexpected") + + result = runner.invoke(command, []) + assert result.exit_code == 1 and not result.stdout + assert "Request report initialization failed (OSError)" in result.stderr + assert "private-canary" not in result.stderr + + +@pytest.mark.parametrize("command", ["layout", "docker"]) +def test_invalid_destination_precedes_unavailable_report_storage(monkeypatch, runner, tmp_path, command): + """Portable semantic preflight retains its error even when secure storage is unavailable.""" + def unavailable(): + """Reject any collector acquisition before a valid library operation starts.""" + raise AssertionError("invalid input acquired report storage") + + monkeypatch.setattr("regshape.cli.request_report.RequestReportCollector", unavailable) + args = [command, "push", "--dest", "registry.example:/repo"] + args += ["--path", str(tmp_path)] if command == "layout" else ["--image", "unused"] + result = runner.invoke(regshape, args) + assert result.exit_code == (2 if command == "layout" else 1) + assert "Invalid push destination" in result.stderr + assert get_telemetry_config().request_report_factory is None + + +@pytest.mark.parametrize("alias", ["same", "symlink", "hardlink"]) +@pytest.mark.parametrize("command", ["manifest", "blob", "manifest_put", "blob_upload"]) +def test_transfer_files_cannot_alias_diagnostic_log(monkeypatch, runner, tmp_path, alias, command): + """Reject aliases before log acquisition, HTTP or any overwrite of the existing payload.""" + output = tmp_path / "manifest.json" + output.write_text('{"keep":"unchanged"}') + log = tmp_path / "report.log" + if alias == "same": + log = output + elif alias == "symlink": + log.symlink_to(output) + else: + log.hardlink_to(output) + + def forbidden(*args, **kwargs): + """Prohibit telemetry acquisition and credential access during alias preflight.""" + raise AssertionError("alias preflight acquired a resource") + + monkeypatch.setattr("regshape.libs.decorators.open", forbidden, raising=False) + monkeypatch.setattr("regshape.libs.transport.client.resolve_credentials", forbidden) + if command == "manifest_put": + args = ["manifest", "put", "-a", SOURCE, "--file", str(output)] + elif command == "blob_upload": + args = ["blob", "upload", "--repo", "registry.example/repo", "-d", DIGEST, + "--file", str(output)] + else: + args = ["manifest", "get", "-a", SOURCE] if command == "manifest" else [ + "blob", "get", "--repo", "registry.example/repo", "-d", DIGEST, + ] + args += ["--output", str(output), "--no-progress"] + result = runner.invoke(regshape, ["--log-file", str(log), *args]) + assert result.exit_code == 2 and not result.stdout + assert "must name different paths" in result.stderr + assert output.read_text() == log.read_text() == '{"keep":"unchanged"}' + + +@pytest.mark.parametrize("kind", ["index", "blob", "archive"]) +@pytest.mark.parametrize("alias", ["same", "symlink", "hardlink"]) +def test_layout_source_cannot_alias_diagnostic_log(monkeypatch, runner, tmp_path, kind, alias): + """Reject directory content and archive aliases before dry-run telemetry or source acquisition.""" + root, objects, _, layer = _payloads() + layout = tmp_path / "layout" + write_layout(layout, root, objects, root_type=OCI_IMAGE_MANIFEST) + if kind == "archive": + source = tmp_path / "source.tar.gz" + source.write_bytes(b"must-not-be-opened") + layout = source + elif kind == "index": + source = layout / "index.json" + else: + source = layout / "blobs" / "sha256" / address(layer).split(":")[1] + original = source.read_bytes() + log = tmp_path / "report.log" + if alias == "same": + log = source + elif alias == "symlink": + log.symlink_to(source) + else: + log.hardlink_to(source) + + def forbidden(*args, **kwargs): + """Prohibit telemetry log, report storage and credential acquisition before separation.""" + raise AssertionError("source alias preflight acquired a resource") + + monkeypatch.setattr("regshape.libs.decorators.open", forbidden, raising=False) + monkeypatch.setattr("regshape.cli.request_report.RequestReportCollector", forbidden) + monkeypatch.setattr("regshape.libs.transport.client.resolve_credentials", forbidden) + result = runner.invoke(regshape, [ + "--log-file", str(log), "layout", "push", "--path", str(layout), + "--dest", SOURCE, "--dry-run", "--json", + ]) + assert result.exit_code == 2 and not result.stdout + assert "--log-file" in result.stderr + assert source.read_bytes() == log.read_bytes() == original + + +@pytest.mark.parametrize("format_", ["text", "json"]) +def test_late_collection_failure_changes_diagnostic_exit(monkeypatch, runner, format_): + """Endpoint-summary storage failure during export cannot acknowledge complete reporting.""" + def unavailable(*args): + """Fail only the late endpoint-count read, after the operation is complete.""" + raise RequestReportError("spool_read") + + monkeypatch.setattr(ReportStore, "count_endpoints", unavailable) + + @click.command() + @request_reporting + @telemetry_options + def command(): + """Keep an acknowledged push independent of late reporting failure.""" + with request_report_scope("test", "push"): + pass + click.echo("Acknowledged push") + + result = runner.invoke(command, ["--telemetry-format", format_]) + assert result.exit_code == 1 and result.stdout == "Acknowledged push\n" + assert "were not rolled back" in result.stderr + if format_ == "json": + report = json.loads(result.stderr.splitlines()[0]) + assert not report["collection"]["complete"] + assert report["operation"]["outcome"] == "succeeded" + else: + assert "COLLECTION INCOMPLETE" in result.stderr and "Outcome: Succeeded" in result.stderr + + +@pytest.mark.parametrize("format_", ["text", "json"]) +@pytest.mark.parametrize("primary", [None, RuntimeError("private-operation")]) +def test_spool_iterator_failure_keeps_stderr_healthy(monkeypatch, runner, format_, primary): + """A detail-read error must not suppress healthy diagnostics or replace the operation error.""" + def unavailable(*args): + """Reject spool iteration without failing any output sink.""" + raise RequestReportError("spool_read") + + monkeypatch.setattr(RequestReport, "iter_groups", unavailable) + + @click.command() + @request_reporting + @telemetry_options + def command(): + """Fail rendering only after the operation has settled.""" + with request_report_scope("test", "pull"): + if primary is not None: + raise primary + click.echo("Downloaded") + + result = runner.invoke(command, ["--telemetry-format", format_]) + assert result.exit_code == 1 + assert "Request report export failed" in result.stderr + assert "private-operation" not in result.stderr + if primary is not None: + assert result.exception is primary + else: + assert result.stdout == "Downloaded\n" + + +def test_primary_error_does_not_reopen_failed_telemetry_log(monkeypatch, runner, tmp_path): + """An owned log's suppressed close error remains visible to outer report coordination.""" + primary = RuntimeError("private-operation") + reopened = [] + + class Log(io.StringIO): + """Close the real owned handle before surfacing its cleanup failure.""" + + def close(self): + """Release storage even though the close boundary fails.""" + super().close() + raise OSError("private-close") + + def append(*args): + """Record any forbidden reacquisition of the already failed telemetry destination.""" + reopened.append(args) + return io.StringIO() + + log = Log() + monkeypatch.setattr("regshape.libs.decorators.open", lambda *args: log, raising=False) + monkeypatch.setattr("regshape.cli.request_report.open", append, raising=False) + + @click.command() + @request_reporting + @telemetry_options + def command(): + """Retain the exact operation error while telemetry log cleanup also fails.""" + with request_report_scope("test", "pull"): + raise primary + + result = runner.invoke( + command, [], obj={"log_file": str(tmp_path / "report.log")}, + ) + assert result.exception is primary and log.closed + assert not reopened + assert "Pull request report - FAILED" in result.stderr + assert "private-operation" not in result.stderr and "private-close" not in result.stderr + + +@pytest.mark.parametrize("boundary,warnings_enabled,timed_scenario", [ + ("write", True, False), ("flush", True, False), ("deferred_flush", True, False), + ("write", False, False), ("flush", False, False), + ("write", False, True), ("flush", False, True), +]) +def test_aliased_result_failure_reaches_outer_report_scope( + monkeypatch, tmp_path, boundary, warnings_enabled, timed_scenario, +): + """Distinct wrappers/descriptors for one pipe must not retry a failed result destination.""" + primary = BrokenPipeError("private-pipe") + read_fd, output_fd = os.pipe() + error_fd = os.dup(output_fd) + failed = False + retries = 0 + + class PipeSink(io.StringIO): + """Expose real duplicated pipe identities with deterministic shared sink failure.""" + + def __init__(self, fd, *, result=False): + """Borrow the descriptor without writing to or closing the kernel pipe.""" + super().__init__() + self.fd, self.result = fd, result + + def fileno(self): + """Allow the shared destination detector to compare actual kernel identities.""" + return self.fd + + def write(self, text): + """Fail once on result output and reject any later diagnostic retry.""" + nonlocal failed, retries + if not isinstance(text, str) or not text: + return super().write(text) + if failed: + retries += 1 + raise primary + if self.result and boundary == "write": + failed = True + raise primary + return super().write(text) + + def flush(self): + """Model a final-result flush failure shared by both pipe descriptors.""" + nonlocal failed, retries + if failed: + retries += 1 + raise primary + if self.result and boundary in {"flush", "deferred_flush"} and self.getvalue(): + failed = True + raise primary + + @click.command() + @request_reporting + def command(): + """Place result delivery outside telemetry, with or without a warning coordinator.""" + with DownloadWarnings() if warnings_enabled else nullcontext() as warnings: + def deliver_result(): + """Fail result delivery while retaining warning coordination where present.""" + try: + if boundary == "deferred_flush": + assert warnings is not None + warnings.observe(DownloadStatus( + "blob", DIGEST, "fallback", "full", "etag_changed", None, 2, DownloadStats(), + )) + sys.stdout.write("Published") + else: + click.echo("Published") + except BaseException: + if warnings is not None: + warnings.result_failed() + raise + + @telemetry_options + @track_scenario("test") + def operation(): + """Optionally deliver inside a timed scenario before telemetry log finalization.""" + with request_report_scope("test", "pull"): + pass + if timed_scenario: + deliver_result() + + operation(time_scenarios=timed_scenario) + if not timed_scenario: + deliver_result() + + output, error = PipeSink(output_fd, result=True), PipeSink(error_fd) + log = tmp_path / "report.log" + try: + with monkeypatch.context() as streams: + streams.setattr(sys, "stdout", output) + streams.setattr(sys, "stderr", error) + with ( + click.Context(command, obj={"log_file": str(log)}), + pytest.raises(BrokenPipeError) as caught, + ): + command.callback() + assert caught.value is primary + sys.stdout.flush() + sys.stderr.flush() + assert failed and retries == 0 + assert "Pull request report" in log.read_text() + assert not output.closed and not error.closed + finally: + os.close(read_fd) + os.close(output_fd) + os.close(error_fd) + + +@pytest.mark.parametrize("boundary", ["open", "short_write", "flush", "close"]) +def test_report_log_failure_preserves_result_and_healthy_stderr( + boundary, network, monkeypatch, tmp_path, runner, +): + """Final append/export failures close owned handles and never roll back a completed download.""" + root, objects, _, _ = _payloads() + _registry(monkeypatch, network, root, objects) + closed = 0 + failed = False + + class Log(io.StringIO): + """Fail at one report-only boundary while tracking retry and close ownership.""" + + def write(self, text): + """Reject a short write exactly once without permitting a retry.""" + nonlocal failed + assert not failed + if boundary == "short_write": + failed = True + return 0 + return super().write(text) + + def flush(self): + """Fail final delivery after all report text has been accepted.""" + nonlocal failed + assert not failed + if boundary == "flush": + failed = True + raise OSError("private-canary") + return super().flush() + + def close(self): + """Release storage even when the close boundary itself fails.""" + nonlocal closed + closed += 1 + super().close() + if boundary == "close": + raise OSError("private-canary") + + log = Log() + + def append(path, mode): + """Replace only the final report's append acquisition; initial telemetry stays real.""" + assert mode == "a" + if boundary == "open": + raise OSError("private-canary") + return log + + monkeypatch.setattr("regshape.cli.request_report.open", append, raising=False) + result = runner.invoke(regshape, [ + "--log-file", str(tmp_path / "report.log"), "manifest", "get", + "-a", SOURCE, "--raw", "--no-progress", + ]) + assert result.exit_code == 1 + assert result.stdout == root.decode() + "\n" + assert result.stderr.count("Pull request report") == 1 + assert "were not rolled back" in result.stderr and "private-canary" not in result.stderr + assert closed == int(boundary != "open") + if boundary == "open": + log.close() + assert get_telemetry_config().request_report_collector is None + + +@pytest.mark.parametrize("format_", ["text", "json"]) +def test_result_stdout_flush_failure_is_not_report_export_failure(monkeypatch, tmp_path, format_): + """Diagnose a failed result flush before healthy reports, preserving its exact cause.""" + failure = BrokenPipeError("private-result-flush") + flushes = 0 + + class Result(io.StringIO): + """Borrow a result sink that accepts output but fails its final flush.""" + + def flush(self): + """Record the one failed result flush without closing the borrowed stream.""" + nonlocal flushes + flushes += 1 + raise failure + + @click.command() + @request_reporting + @telemetry_options + def command(): + """Settle the operation and write result bytes without an intermediate flush.""" + with request_report_scope("test", "push"): + pass + sys.stdout.write("Acknowledged push\n") + + output, error = Result(), io.StringIO() + log = tmp_path / "report.log" + with monkeypatch.context() as streams: + streams.setattr(sys, "stdout", output) + streams.setattr(sys, "stderr", error) + with ( + click.Context(command, obj={"log_file": str(log)}), + pytest.raises(click.exceptions.Exit) as caught, + ): + command.callback(telemetry_format=format_) + assert caught.value.exit_code == 1 and caught.value.__cause__ is failure + sys.stdout.flush() + assert flushes == 1 and output.getvalue() == "Acknowledged push\n" + diagnostic, report = error.getvalue().split("\n", 1) + assert diagnostic.startswith("Error: Command result output flush failed.") + assert "were not rolled back" in diagnostic + assert "Request report export failed" not in error.getvalue() + assert "private-result-flush" not in error.getvalue() + assert report == log.read_text() + if format_ == "json": + assert json.loads(report)["operation"]["outcome"] == "succeeded" + else: + assert report.startswith("Push request report\n") and "Outcome: Succeeded" in report + assert not output.closed and not error.closed + assert get_telemetry_config().request_report_collector is None + + +@pytest.mark.parametrize("verbosity", [0, 1]) +@pytest.mark.parametrize("shared", [False, True]) +def test_ascii_stdout_keeps_click_text_and_binary_adaptation(monkeypatch, verbosity, shared): + """Borrowing stdout must preserve Click's Unicode fallback and binary echo, even when quiet.""" + buffer = io.BytesIO() + output = io.TextIOWrapper(buffer, encoding="ascii") + error = output if shared else io.StringIO() + + @click.command() + @request_reporting + @telemetry_options + def command(): + """Emit Unicode and binary results through Click rather than changing the process codec.""" + with request_report_scope("test", "pull"): + pass + click.echo("caf\u00e9") + click.echo(b"binary") + + with monkeypatch.context() as streams: + streams.setattr(sys, "stdout", output) + streams.setattr(sys, "stderr", error) + with click.Context(command): + command.callback(telemetry_verbosity=verbosity) + assert sys.stdout is output and sys.stderr is error + output.flush() + assert buffer.getvalue().startswith("caf\u00e9\nbinary\n".encode()) + if shared: + assert (b"Pull request report" in buffer.getvalue()) == bool(verbosity) + else: + assert buffer.getvalue() == "caf\u00e9\nbinary\n".encode() + assert ("Pull request report" in error.getvalue()) == bool(verbosity) + assert not buffer.closed and not output.closed and not error.closed + output.detach() + + +@pytest.mark.parametrize("cancelled", [False, True]) +def test_ascii_stdout_binary_failure_stays_tracked(monkeypatch, tmp_path, cancelled): + """Click's encoding fallback must not bypass sink tracking or retry during wrapper cleanup.""" + failure = KeyboardInterrupt("private-binary-output") if cancelled else BrokenPipeError("private-binary-output") + writes = 0 + + class Buffer(io.BytesIO): + """Accept Click's empty probes, but reject one actual encoded result write.""" + + def write(self, data): + """Count actual destination writes so shutdown/adapter cleanup retries are visible.""" + nonlocal writes + if data: + writes += 1 + raise failure + return super().write(data) + + buffer = Buffer() + output, error = io.TextIOWrapper(buffer, encoding="ascii"), io.StringIO() + log = tmp_path / "report.log" + + @click.command() + @request_reporting + @telemetry_options + def command(): + """Fail only the encoded result write after completing the library operation.""" + with request_report_scope("test", "pull"): + pass + click.echo("caf\u00e9") + + with monkeypatch.context() as streams: + streams.setattr(sys, "stdout", output) + streams.setattr(sys, "stderr", error) + with ( + click.Context(command, obj={"log_file": str(log)}), + pytest.raises(click.exceptions.Exit if cancelled else BrokenPipeError) as caught, + ): + command.callback() + if cancelled: + assert caught.value.exit_code == 1 and caught.value.__cause__ is failure + else: + assert caught.value is failure + sys.stdout.flush() + assert writes == 1 and "Pull request report" in error.getvalue() + assert "Pull request report" in log.read_text() + assert "private-binary-output" not in error.getvalue() + assert not output.closed and not buffer.closed + output.detach() + + +def test_immutable_primary_survives_collector_cleanup_failure(monkeypatch, capsys): + """Neither cleanup nor Click error translation mutates an immutable operation exception.""" + primary = _ImmutableError("private-canary") + original_close = RequestReportCollector.close + closed = [] + + def close(collector): + """Release real spool resources before simulating a final cleanup error.""" + original_close(collector) + closed.append(collector) + raise OSError("cleanup-canary") + + monkeypatch.setattr(RequestReportCollector, "close", close) + + @click.command() + @request_reporting + @telemetry_options + def command(): + """Fail inside a library scope without exposing the raw operation message.""" + with request_report_scope("test", "pull"): + raise primary + + context = click.Context(command) + context.__enter__() + try: + try: + command.callback() + except _ImmutableError as error: + assert error is primary + else: + pytest.fail("operation error was hidden") + finally: + context.__exit__(None, None, None) + assert len(closed) == 1 and get_telemetry_config().request_report_collector is None + stderr = capsys.readouterr().err + assert "Pull request report - FAILED" in stderr + assert "were not rolled back" in stderr + assert "private-canary" not in stderr and "cleanup-canary" not in stderr