From d6feb7756c497ebdbb390d679c223b261a32a913 Mon Sep 17 00:00:00 2001 From: Toddy Mladenov Date: Fri, 4 Dec 2026 15:56:36 -0800 Subject: [PATCH 01/12] feat: render automatic CLI request reports Enable library-backed reports through existing telemetry controls for supported pull and push commands. Preserve result channels, deferred diagnostics, error precedence, and diagnostic log ownership. Add focused physical-dispatch and sink-failure coverage for #261. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/tests.yml | 1 + docs/library/telemetry.md | 55 +- src/regshape/cli/artifact.py | 2 + src/regshape/cli/blob.py | 4 + src/regshape/cli/components.py | 2 + src/regshape/cli/docker.py | 6 + src/regshape/cli/layout.py | 8 +- src/regshape/cli/manifest.py | 3 + src/regshape/cli/request_report.py | 408 +++++++++++++ src/regshape/cli/telemetry.py | 23 +- .../libs/decorators/request_report.py | 10 +- src/regshape/tests/test_artifact_cli.py | 66 +-- src/regshape/tests/test_artifact_download.py | 7 +- src/regshape/tests/test_artifact_pull_cli.py | 21 +- src/regshape/tests/test_artifact_push.py | 8 +- src/regshape/tests/test_component_cli.py | 4 +- src/regshape/tests/test_image_progress.py | 13 +- src/regshape/tests/test_manifest_cli.py | 12 +- .../tests/test_manifest_cli_progress.py | 9 +- src/regshape/tests/test_progress_display.py | 18 +- src/regshape/tests/test_request_report_cli.py | 534 ++++++++++++++++++ 21 files changed, 1133 insertions(+), 81 deletions(-) create mode 100644 src/regshape/cli/request_report.py create mode 100644 src/regshape/tests/test_request_report_cli.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 28e61043..ea7778d9 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 3cba7da5..37c75048 100644 --- a/docs/library/telemetry.md +++ b/docs/library/telemetry.md @@ -80,11 +80,56 @@ 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. +- 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. +- `--time-methods`, `--time-scenarios`, `--debug-calls`, and `--metrics` remain + independently opt-in. All six common telemetry controls are also available + on `docker push`. + +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. +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 +138,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 e578155d..da38a139 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 1e2fc303..662d1354 100644 --- a/src/regshape/cli/blob.py +++ b/src/regshape/cli/blob.py @@ -23,6 +23,7 @@ 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,7 @@ def wrapper(*args: Any, **kwargs: Any) -> None: @blob.command("get") +@request_reporting @_after_blob_telemetry @telemetry_options @click.option("--no-progress", is_flag=True, default=False, help="Disable interactive transfer progress.") @@ -277,6 +279,7 @@ def blob_delete(ctx, repo, digest): @blob.command("upload") +@request_reporting @telemetry_options @click.option("--no-progress", is_flag=True, default=False, help="Disable interactive transfer progress.") @click.option( @@ -370,6 +373,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 c3cfa1ef..b526bca5 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 3b2487d9..03af1faf 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/layout.py b/src/regshape/cli/layout.py index 2d48c0af..5f088239 100644 --- a/src/regshape/cli/layout.py +++ b/src/regshape/cli/layout.py @@ -32,6 +32,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 +771,7 @@ def _format_size(size: int) -> str: @layout.command("push") +@request_reporting @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 +824,8 @@ 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. The automatic report follows final output. """ try: registry, repo, tag_override = parse_push_destination(dest) @@ -837,7 +842,8 @@ 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", 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 c37e3b09..b6722919 100644 --- a/src/regshape/cli/manifest.py +++ b/src/regshape/cli/manifest.py @@ -31,6 +31,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 +80,7 @@ def manifest(): # =========================================================================== @manifest.command("get") +@request_reporting @telemetry_options @click.option("--no-progress", is_flag=True, default=False, help="Disable interactive transfer progress.") @artifact_option( @@ -316,6 +318,7 @@ def descriptor(ctx, image_ref, accept): # =========================================================================== @manifest.command("put") +@request_reporting @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 00000000..87dfe1b7 --- /dev/null +++ b/src/regshape/cli/request_report.py @@ -0,0 +1,408 @@ +"""Render library request reports after command results, warnings and diagnostics. + +The invocation adapter owns only diagnostic resources. 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 +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 telemetry setup, after command-specific preflight.""" + self.collector: RequestReportCollector | None = None + self.config: TelemetryConfig | None = None + self.token: Token[_CommandReport | None] + self.stderr: TextIO + self.shared_stdout = False + self.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. + """Make this invocation the only activation target in the current context.""" + self.token = _active.set(self) + self.stderr = sys.stderr + self.output = _DownloadOutput(self.stderr) + self.shared_stdout = sys.stdout is self.stderr + if self.shared_stdout: + sys.stdout = self.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 + if self.shared_stdout: + sys.stdout = self.stderr + _restore_stderr_handlers(self.output, self.log_streams) + _active.reset(self.token) + raise + return self + + def activate(self, config: TelemetryConfig) -> None: + """Acquire only the library collector; normal telemetry cleanup still precedes results.""" + if self.config is not None: + raise RuntimeError("Command request reporting is already active") + self.config = config + 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}).") from error + config.request_report_collector = 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. + """ + primary = exc + translated: click.exceptions.Exit | None = None + failure: BaseException | None = None + failure_diagnosed = False + try: + 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: + sys.stdout.flush() + except BaseException as error: # noqa: BLE001 - retain cancellation while delivering available reports. + 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 + sink.failed = True + 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 sys.stderr is self.output: + sys.stderr = _FailedFlushStream(self.stderr) if self.output.failed else self.stderr + if self.shared_stdout and sys.stdout is self.output: + sys.stdout = _FailedFlushStream(self.stderr) if self.output.failed else self.stderr + _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.collector is not None 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 2524c124..c3b74eff 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. @@ -82,7 +89,19 @@ 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 return wrapper diff --git a/src/regshape/libs/decorators/request_report.py b/src/regshape/libs/decorators/request_report.py index 5f12afa3..c493dc59 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]. diff --git a/src/regshape/tests/test_artifact_cli.py b/src/regshape/tests/test_artifact_cli.py index bd24b911..10d38095 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 9a55068f..da57d9ed 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 3575fb19..6ab3f18b 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 @@ -1009,6 +1013,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 +1225,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 +1234,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 +1251,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 +1382,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 25995707..0da7d193 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_component_cli.py b/src/regshape/tests/test_component_cli.py index 0a11ef7e..f23ccb44 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 fd45b0d9..4bec17b3 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_manifest_cli.py b/src/regshape/tests/test_manifest_cli.py index 5607c920..6f4989d4 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 46cd6ae3..40c7c67f 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 b391f433..4bc5e218 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_cli.py b/src/regshape/tests/test_request_report_cli.py new file mode 100644 index 00000000..ab4e2d29 --- /dev/null +++ b/src/regshape/tests/test_request_report_cli.py @@ -0,0 +1,534 @@ +"""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 sys +from concurrent.futures import CancelledError +from contextlib import contextmanager + +import click +import pytest + +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_time, +) +from regshape.libs.decorators.request_report import Reference +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"] + 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["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.""" + 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("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 + + +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 From ce6c47fd417a92a7028f9f9bfe2580f7217f98a1 Mon Sep 17 00:00:00 2001 From: Toddy Mladenov Date: Fri, 4 Dec 2026 15:59:44 -0800 Subject: [PATCH 02/12] test: keep layout push result assertions separate from reports Read the stdout channel explicitly on both minimum and current Click, whose merged diagnostic output now includes the automatic request report. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/regshape/tests/test_layout_push.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/regshape/tests/test_layout_push.py b/src/regshape/tests/test_layout_push.py index baa329a1..c4caf44f 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 From 8a148626c5242a8c70d5ff3606d2006607c10fa4 Mon Sep 17 00:00:00 2001 From: Toddy Mladenov Date: Fri, 4 Dec 2026 16:11:43 -0800 Subject: [PATCH 03/12] fix: preserve command preflight before report acquisition Acquire caller-owned reporting lazily at the first library operation scope. Preserve portable validation errors and explicitly suppress reporting in the downloader-only retry test. Reject manifest output aliases before opening diagnostic logs, including hard links and symlinks, with focused regression coverage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/library/telemetry.md | 11 +++++ src/regshape/cli/manifest.py | 20 +++++++- src/regshape/cli/request_report.py | 18 ++++++-- src/regshape/libs/_pull_report.py | 5 +- src/regshape/libs/_push_report.py | 5 +- src/regshape/libs/decorators/__init__.py | 6 +++ .../libs/decorators/request_report.py | 8 +++- src/regshape/tests/test_blob_ranges.py | 1 + src/regshape/tests/test_request_report.py | 25 ++++++++++ src/regshape/tests/test_request_report_cli.py | 46 +++++++++++++++++++ 10 files changed, 135 insertions(+), 10 deletions(-) diff --git a/docs/library/telemetry.md b/docs/library/telemetry.md index 37c75048..d887721b 100644 --- a/docs/library/telemetry.md +++ b/docs/library/telemetry.md @@ -104,10 +104,21 @@ diagnostics by default, including noninteractive invocations. 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 downloads reject log/output aliases (including hard links and + symlinks) before opening either destination. - `--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. +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. + 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 diff --git a/src/regshape/cli/manifest.py b/src/regshape/cli/manifest.py index b6722919..e883b7b0 100644 --- a/src/regshape/cli/manifest.py +++ b/src/regshape/cli/manifest.py @@ -16,11 +16,13 @@ import json import sys from collections.abc import Callable -from functools import partial +from functools import partial, wraps +from typing import Any import click import requests +from regshape.cli.downloads import separate_log_output from regshape.cli.formatting import ( emit_error, emit_json, @@ -79,8 +81,24 @@ def manifest(): # manifest get # =========================================================================== +def _separate_get_output(function: Callable[..., None]) -> Callable[..., None]: + """Reject manifest/log aliases before telemetry opens either destination.""" + @wraps(function) + def wrapper(*args: Any, **kwargs: Any) -> None: + """Use shared path, symlink, hard-link and volume-case separation checks.""" + output = kwargs.get("output") + if output is not None: + try: + separate_log_output(output) + except (OSError, RuntimeError) as error: + emit_error("--log-file", f"Cannot inspect log/output separation: {error}") + return function(*args, **kwargs) + return wrapper + + @manifest.command("get") @request_reporting +@_separate_get_output @telemetry_options @click.option("--no-progress", is_flag=True, default=False, help="Disable interactive transfer progress.") @artifact_option( diff --git a/src/regshape/cli/request_report.py b/src/regshape/cli/request_report.py index 87dfe1b7..5cab3ffc 100644 --- a/src/regshape/cli/request_report.py +++ b/src/regshape/cli/request_report.py @@ -216,16 +216,24 @@ def __enter__(self) -> "_CommandReport": # noqa: PYI034 - Python 3.10, no typin return self def activate(self, config: TelemetryConfig) -> None: - """Acquire only the library collector; normal telemetry cleanup still precedes results.""" + """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}).") from error - config.request_report_collector = self.collector + 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, @@ -356,6 +364,8 @@ def __exit__( 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 self.shared_stdout and sys.stdout is self.output: @@ -386,7 +396,7 @@ def activate_reporting(config: TelemetryConfig) -> None: 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.collector is not None and config.log_file is not None: + 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 diff --git a/src/regshape/libs/_pull_report.py b/src/regshape/libs/_pull_report.py index d17fe381..5112e324 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 65f96f52..6a6731fa 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 908e91ca..bf531945 100644 --- a/src/regshape/libs/decorators/__init__.py +++ b/src/regshape/libs/decorators/__init__.py @@ -17,6 +17,7 @@ """ import sys +from collections.abc import Callable from contextlib import AbstractContextManager from contextvars import ContextVar from dataclasses import dataclass, field @@ -64,6 +65,10 @@ 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. """ time_methods_enabled: bool = False time_scenarios_enabled: bool = False @@ -77,6 +82,7 @@ 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) _telemetry_config: ContextVar[TelemetryConfig] = ContextVar( diff --git a/src/regshape/libs/decorators/request_report.py b/src/regshape/libs/decorators/request_report.py index c493dc59..54bd6e55 100644 --- a/src/regshape/libs/decorators/request_report.py +++ b/src/regshape/libs/decorators/request_report.py @@ -1445,11 +1445,17 @@ 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 failures propagate. 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: + collector = config.request_report_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_blob_ranges.py b/src/regshape/tests/test_blob_ranges.py index 048ad011..0f4fa2ef 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_request_report.py b/src/regshape/tests/test_request_report.py index 4ca31b5f..25b22885 100644 --- a/src/regshape/tests/test_request_report.py +++ b/src/regshape/tests/test_request_report.py @@ -36,6 +36,31 @@ 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 _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 index ab4e2d29..185bc779 100644 --- a/src/regshape/tests/test_request_report_cli.py +++ b/src/regshape/tests/test_request_report_cli.py @@ -423,6 +423,8 @@ def unavailable(): @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, []) @@ -431,6 +433,50 @@ def command(): 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"]) +def test_manifest_output_cannot_alias_diagnostic_log(monkeypatch, runner, tmp_path, alias): + """Reject aliases before log acquisition, HTTP or any overwrite of the existing manifest.""" + 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) + result = runner.invoke(regshape, [ + "--log-file", str(log), "manifest", "get", "-a", SOURCE, + "--output", str(output), "--no-progress", + ]) + 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("boundary", ["open", "short_write", "flush", "close"]) def test_report_log_failure_preserves_result_and_healthy_stderr( boundary, network, monkeypatch, tmp_path, runner, From 7621c6ac1fae327371644f6f07c7c6284f090c64 Mon Sep 17 00:00:00 2001 From: Toddy Mladenov Date: Fri, 4 Dec 2026 16:18:23 -0800 Subject: [PATCH 04/12] fix: preserve reporting failure boundaries Keep healthy diagnostic sinks available after spool-read errors, fail on collection errors discovered during rendering, and expose suppressed telemetry cleanup failures without replacing primary exceptions. Reject blob/log aliases before telemetry acquisition. Ten focused regression cases reproduce the reviewed failures and pass with these corrections. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/library/telemetry.md | 9 +- src/regshape/cli/blob.py | 10 +- src/regshape/cli/request_report.py | 9 +- src/regshape/cli/telemetry.py | 5 +- src/regshape/libs/decorators/__init__.py | 13 +- src/regshape/tests/test_request_report_cli.py | 112 +++++++++++++++++- 6 files changed, 146 insertions(+), 12 deletions(-) diff --git a/docs/library/telemetry.md b/docs/library/telemetry.md index d887721b..1d22fbd4 100644 --- a/docs/library/telemetry.md +++ b/docs/library/telemetry.md @@ -104,7 +104,7 @@ diagnostics by default, including noninteractive invocations. 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 downloads reject log/output aliases (including hard links and + Manifest and blob downloads reject log/output aliases (including hard links and symlinks) before opening either destination. - `--time-methods`, `--time-scenarios`, `--debug-calls`, and `--metrics` remain independently opt-in. All six common telemetry controls are also available @@ -119,6 +119,13 @@ 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. + 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 diff --git a/src/regshape/cli/blob.py b/src/regshape/cli/blob.py index 662d1354..8c4f392f 100644 --- a/src/regshape/cli/blob.py +++ b/src/regshape/cli/blob.py @@ -19,7 +19,7 @@ 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_log_output 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 @@ -102,10 +102,16 @@ def blob_head(ctx, repo, digest): def _after_blob_telemetry(func: Callable[..., BlobInfo]) -> Callable[..., None]: - """Keep the original blob JSON outside cleanup, followed by any deferred warning.""" + """Reject log/output aliases before acquisition; emit blob JSON after telemetry cleanup.""" @wraps(func) def wrapper(*args: Any, **kwargs: Any) -> None: """Await all transfer/telemetry cleanup before output and warning delivery.""" + output = kwargs.get("output") + if output is not None: + try: + separate_log_output(output) + except (OSError, RuntimeError) as error: + emit_error("--log-file", f"Cannot inspect log/output separation: {error}") with DownloadWarnings() as warnings: info = func(*args, **kwargs, download_warnings=warnings) try: diff --git a/src/regshape/cli/request_report.py b/src/regshape/cli/request_report.py index 5cab3ffc..3c59a5d3 100644 --- a/src/regshape/cli/request_report.py +++ b/src/regshape/cli/request_report.py @@ -181,7 +181,7 @@ class _CommandReport: """Keep reports alive through command output, appending after the telemetry log closes.""" def __init__(self) -> None: - """Defer acquisition until telemetry setup, after command-specific preflight.""" + """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] @@ -245,6 +245,7 @@ def __exit__( 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. """ primary = exc translated: click.exceptions.Exit | None = None @@ -317,7 +318,11 @@ def __exit__( except BaseException as error: # noqa: BLE001 - retain sink/cancellation identity and try only healthy sinks. if failure is None: failure = error - sink.failed = True + if isinstance(error, RequestReportError) and error.code == "report_export": + sink.failed = True + 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. " diff --git a/src/regshape/cli/telemetry.py b/src/regshape/cli/telemetry.py index c3b74eff..c9c9a54e 100644 --- a/src/regshape/cli/telemetry.py +++ b/src/regshape/cli/telemetry.py @@ -77,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( @@ -103,5 +103,8 @@ def wrapper( 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/decorators/__init__.py b/src/regshape/libs/decorators/__init__.py index bf531945..27328b81 100644 --- a/src/regshape/libs/decorators/__init__.py +++ b/src/regshape/libs/decorators/__init__.py @@ -69,6 +69,9 @@ class TelemetryConfig: 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. + :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 @@ -83,6 +86,7 @@ class TelemetryConfig: 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) + cleanup_failed: bool = field(default=False, init=False, repr=False) _telemetry_config: ContextVar[TelemetryConfig] = ContextVar( @@ -125,7 +129,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 " @@ -135,6 +139,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 @@ -144,7 +149,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: @@ -152,6 +157,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 @@ -161,6 +167,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") @@ -187,6 +194,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/tests/test_request_report_cli.py b/src/regshape/tests/test_request_report_cli.py index 185bc779..59bf5ef1 100644 --- a/src/regshape/tests/test_request_report_cli.py +++ b/src/regshape/tests/test_request_report_cli.py @@ -25,7 +25,9 @@ request_report_scope, track_time, ) -from regshape.libs.decorators.request_report import Reference +from regshape.libs.decorators._request_report_store import ReportStore +from regshape.libs.decorators.request_report import Reference, RequestReport +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 @@ -450,8 +452,9 @@ def unavailable(): @pytest.mark.parametrize("alias", ["same", "symlink", "hardlink"]) -def test_manifest_output_cannot_alias_diagnostic_log(monkeypatch, runner, tmp_path, alias): - """Reject aliases before log acquisition, HTTP or any overwrite of the existing manifest.""" +@pytest.mark.parametrize("command", ["manifest", "blob"]) +def test_download_output_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" @@ -468,8 +471,11 @@ def forbidden(*args, **kwargs): monkeypatch.setattr("regshape.libs.decorators.open", forbidden, raising=False) monkeypatch.setattr("regshape.libs.transport.client.resolve_credentials", forbidden) + args = ["manifest", "get", "-a", SOURCE] if command == "manifest" else [ + "blob", "get", "--repo", "registry.example/repo", "-d", DIGEST, + ] result = runner.invoke(regshape, [ - "--log-file", str(log), "manifest", "get", "-a", SOURCE, + "--log-file", str(log), *args, "--output", str(output), "--no-progress", ]) assert result.exit_code == 2 and not result.stdout @@ -477,6 +483,104 @@ def forbidden(*args, **kwargs): assert output.read_text() == log.read_text() == '{"keep":"unchanged"}' +@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", ["open", "short_write", "flush", "close"]) def test_report_log_failure_preserves_result_and_healthy_stderr( boundary, network, monkeypatch, tmp_path, runner, From a96f1f192f2bb4ce205824a46165e22caa6fe18c Mon Sep 17 00:00:00 2001 From: Toddy Mladenov Date: Fri, 4 Dec 2026 16:26:14 -0800 Subject: [PATCH 05/12] fix: coordinate shared report resources across scopes Serialize lazy collector acquisition per configuration and recheck ownership under the lock. Propagate known failed destinations through nested diagnostic proxies so aliased result writes and flushes are not retried. Cover copied worker contexts and distinct descriptors for the same pipe, preserving primary errors and healthy report logs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/library/telemetry.md | 4 + src/regshape/cli/downloads.py | 23 +++-- src/regshape/cli/request_report.py | 2 +- src/regshape/libs/decorators/__init__.py | 5 + .../libs/decorators/request_report.py | 11 ++- src/regshape/tests/test_request_report.py | 37 ++++++++ src/regshape/tests/test_request_report_cli.py | 91 +++++++++++++++++++ 7 files changed, 161 insertions(+), 12 deletions(-) diff --git a/docs/library/telemetry.md b/docs/library/telemetry.md index 1d22fbd4..6e411edc 100644 --- a/docs/library/telemetry.md +++ b/docs/library/telemetry.md @@ -114,6 +114,8 @@ 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 @@ -125,6 +127,8 @@ 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. Reports follow settled library operations, progress and telemetry finalization, then command results/errors and deferred download warnings. Authentication, diff --git a/src/regshape/cli/downloads.py b/src/regshape/cli/downloads.py index 41e90ee7..9bf66220 100644 --- a/src/regshape/cli/downloads.py +++ b/src/regshape/cli/downloads.py @@ -129,6 +129,7 @@ class _DownloadOutput(io.TextIOBase, IO[str]): collector uses the persistent flag to avoid any additional diagnostics. ``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: @@ -138,6 +139,14 @@ def __init__(self, stream: IO[str]) -> None: self.failed = False self.failure: BaseException | None = None + 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 write(self, text: str) -> int: """Record a real text-write failure, excluding Click's empty binary probes.""" if not isinstance(text, str): @@ -145,9 +154,7 @@ def write(self, text: str) -> int: 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: @@ -155,9 +162,7 @@ def flush(self) -> None: 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: @@ -234,9 +239,9 @@ 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. @@ -309,6 +314,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/request_report.py b/src/regshape/cli/request_report.py index 3c59a5d3..279b7d35 100644 --- a/src/regshape/cli/request_report.py +++ b/src/regshape/cli/request_report.py @@ -319,7 +319,7 @@ def __exit__( if failure is None: failure = error if isinstance(error, RequestReportError) and error.code == "report_export": - sink.failed = True + 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) diff --git a/src/regshape/libs/decorators/__init__.py b/src/regshape/libs/decorators/__init__.py index 27328b81..65af386b 100644 --- a/src/regshape/libs/decorators/__init__.py +++ b/src/regshape/libs/decorators/__init__.py @@ -17,10 +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 @@ -69,6 +71,8 @@ class TelemetryConfig: 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. @@ -86,6 +90,7 @@ class TelemetryConfig: 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) diff --git a/src/regshape/libs/decorators/request_report.py b/src/regshape/libs/decorators/request_report.py index 54bd6e55..0c6036ba 100644 --- a/src/regshape/libs/decorators/request_report.py +++ b/src/regshape/libs/decorators/request_report.py @@ -1446,7 +1446,8 @@ def request_report_scope( 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 failures propagate. + 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 @@ -1454,8 +1455,12 @@ def request_report_scope( config = get_telemetry_config() collector = config.request_report_collector if collector is None and config.request_report_factory is not None: - collector = config.request_report_factory() - config.request_report_collector = collector + 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_request_report.py b/src/regshape/tests/test_request_report.py index 25b22885..c0fc40ed 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 @@ -61,6 +62,42 @@ def acquire(): 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 index 59bf5ef1..4eae3705 100644 --- a/src/regshape/tests/test_request_report_cli.py +++ b/src/regshape/tests/test_request_report_cli.py @@ -6,6 +6,7 @@ import io import json +import os import sys from concurrent.futures import CancelledError from contextlib import contextmanager @@ -13,6 +14,7 @@ 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 @@ -581,6 +583,95 @@ def command(): assert "private-operation" not in result.stderr and "private-close" not in result.stderr +@pytest.mark.parametrize("boundary", ["write", "flush", "deferred_flush"]) +def test_aliased_result_failure_reaches_outer_report_scope(monkeypatch, tmp_path, boundary): + """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, inside the ordinary warning coordinator.""" + with DownloadWarnings() as warnings: + @telemetry_options + def operation(): + """Complete a library scope before telemetry closes its owned log.""" + with request_report_scope("test", "pull"): + pass + + operation() + try: + if boundary == "deferred_flush": + warnings.observe(DownloadStatus( + "blob", DIGEST, "fallback", "full", "etag_changed", None, 2, DownloadStats(), + )) + sys.stdout.write("Published") + else: + click.echo("Published") + except BaseException: + warnings.result_failed() + raise + + 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 + 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, From 2d34aba0c9d1122cea805a17d63627e0af8b3817 Mon Sep 17 00:00:00 2001 From: Toddy Mladenov Date: Fri, 4 Dec 2026 16:32:12 -0800 Subject: [PATCH 06/12] fix: keep diagnostic logs separate from upload sources Share the pre-telemetry file separation decorator across manifest and blob downloads and uploads. Reject path, symlink and hard-link aliases before opening logs or credentials, preserving upload inputs. Six added source-alias cases reproduce the missing preflight and pass alongside current/minimum Click command regressions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/library/telemetry.md | 4 +-- src/regshape/cli/blob.py | 12 +++---- src/regshape/cli/downloads.py | 35 ++++++++++++++++--- src/regshape/cli/manifest.py | 23 +++--------- src/regshape/tests/test_request_report_cli.py | 22 +++++++----- 5 files changed, 53 insertions(+), 43 deletions(-) diff --git a/docs/library/telemetry.md b/docs/library/telemetry.md index 6e411edc..d481b417 100644 --- a/docs/library/telemetry.md +++ b/docs/library/telemetry.md @@ -104,8 +104,8 @@ diagnostics by default, including noninteractive invocations. 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 downloads reject log/output aliases (including hard links and - symlinks) before opening either destination. + Manifest and blob transfers reject logs that alias download outputs or upload + source files (including hard links and symlinks) before opening either file. - `--time-methods`, `--time-scenarios`, `--debug-calls`, and `--metrics` remain independently opt-in. All six common telemetry controls are also available on `docker push`. diff --git a/src/regshape/cli/blob.py b/src/regshape/cli/blob.py index 8c4f392f..f2b15b88 100644 --- a/src/regshape/cli/blob.py +++ b/src/regshape/cli/blob.py @@ -19,7 +19,7 @@ import click import requests -from regshape.cli.downloads import DownloadWarnings, download_options, download_policy, separate_log_output +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 @@ -102,16 +102,10 @@ def blob_head(ctx, repo, digest): def _after_blob_telemetry(func: Callable[..., BlobInfo]) -> Callable[..., None]: - """Reject log/output aliases before acquisition; emit blob JSON after telemetry cleanup.""" + """Keep the original blob JSON outside cleanup, followed by any deferred warning.""" @wraps(func) def wrapper(*args: Any, **kwargs: Any) -> None: """Await all transfer/telemetry cleanup before output and warning delivery.""" - output = kwargs.get("output") - if output is not None: - try: - separate_log_output(output) - except (OSError, RuntimeError) as error: - emit_error("--log-file", f"Cannot inspect log/output separation: {error}") with DownloadWarnings() as warnings: info = func(*args, **kwargs, download_warnings=warnings) try: @@ -124,6 +118,7 @@ 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.") @@ -286,6 +281,7 @@ 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( diff --git a/src/regshape/cli/downloads.py b/src/regshape/cli/downloads.py index 9bf66220..f4bb6535 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,7 @@ 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`` selects upload-source wording; path validation is identical. """ ctx = click.get_current_context() log_path = ctx.obj.get("log_file") if ctx.obj else None @@ -67,11 +71,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 file argument 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(( diff --git a/src/regshape/cli/manifest.py b/src/regshape/cli/manifest.py index e883b7b0..3c3b7b90 100644 --- a/src/regshape/cli/manifest.py +++ b/src/regshape/cli/manifest.py @@ -16,13 +16,12 @@ import json import sys from collections.abc import Callable -from functools import partial, wraps -from typing import Any +from functools import partial import click import requests -from regshape.cli.downloads import separate_log_output +from regshape.cli.downloads import separate_file_log from regshape.cli.formatting import ( emit_error, emit_json, @@ -81,24 +80,9 @@ def manifest(): # manifest get # =========================================================================== -def _separate_get_output(function: Callable[..., None]) -> Callable[..., None]: - """Reject manifest/log aliases before telemetry opens either destination.""" - @wraps(function) - def wrapper(*args: Any, **kwargs: Any) -> None: - """Use shared path, symlink, hard-link and volume-case separation checks.""" - output = kwargs.get("output") - if output is not None: - try: - separate_log_output(output) - except (OSError, RuntimeError) as error: - emit_error("--log-file", f"Cannot inspect log/output separation: {error}") - return function(*args, **kwargs) - return wrapper - - @manifest.command("get") @request_reporting -@_separate_get_output +@separate_file_log("output") @telemetry_options @click.option("--no-progress", is_flag=True, default=False, help="Disable interactive transfer progress.") @artifact_option( @@ -337,6 +321,7 @@ 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/tests/test_request_report_cli.py b/src/regshape/tests/test_request_report_cli.py index 4eae3705..ab69c671 100644 --- a/src/regshape/tests/test_request_report_cli.py +++ b/src/regshape/tests/test_request_report_cli.py @@ -454,8 +454,8 @@ def unavailable(): @pytest.mark.parametrize("alias", ["same", "symlink", "hardlink"]) -@pytest.mark.parametrize("command", ["manifest", "blob"]) -def test_download_output_cannot_alias_diagnostic_log(monkeypatch, runner, tmp_path, alias, command): +@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"}') @@ -473,13 +473,17 @@ def forbidden(*args, **kwargs): monkeypatch.setattr("regshape.libs.decorators.open", forbidden, raising=False) monkeypatch.setattr("regshape.libs.transport.client.resolve_credentials", forbidden) - args = ["manifest", "get", "-a", SOURCE] if command == "manifest" else [ - "blob", "get", "--repo", "registry.example/repo", "-d", DIGEST, - ] - result = runner.invoke(regshape, [ - "--log-file", str(log), *args, - "--output", str(output), "--no-progress", - ]) + 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"}' From a972b1ceaa6ac6073299b963ff292657271a8a78 Mon Sep 17 00:00:00 2001 From: Toddy Mladenov Date: Fri, 4 Dec 2026 16:39:53 -0800 Subject: [PATCH 07/12] fix: protect layout push sources from diagnostic logs Apply shared log separation before layout telemetry, including dry runs and archive inputs. Reject directory-contained logs and ambiguous multiply-linked outside logs using bounded ancestor metadata rather than scanning the source graph. Nine directory metadata/content and archive alias cases fail before the guard and pass afterward; document the conservative outside-log policy. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/library/telemetry.md | 4 ++ src/regshape/cli/downloads.py | 17 +++++++- src/regshape/cli/layout.py | 4 ++ src/regshape/tests/test_request_report_cli.py | 40 +++++++++++++++++++ 4 files changed, 63 insertions(+), 2 deletions(-) diff --git a/docs/library/telemetry.md b/docs/library/telemetry.md index d481b417..e3cd8f12 100644 --- a/docs/library/telemetry.md +++ b/docs/library/telemetry.md @@ -106,6 +106,10 @@ diagnostics by default, including noninteractive invocations. 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`. diff --git a/src/regshape/cli/downloads.py b/src/regshape/cli/downloads.py index f4bb6535..cb68fcd8 100644 --- a/src/regshape/cli/downloads.py +++ b/src/regshape/cli/downloads.py @@ -44,7 +44,10 @@ def separate_log_output(output: str, *, source: bool = False) -> 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`` selects upload-source wording; path validation is identical. + ``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 @@ -53,6 +56,16 @@ def separate_log_output(output: str, *, source: bool = False) -> 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) @@ -80,7 +93,7 @@ def separate_log_output(output: str, *, source: bool = False) -> None: def separate_file_log( parameter: str, *, source: bool = False, ) -> Callable[[Callable[..., _R]], Callable[..., _R]]: - """Guard an optional parsed file argument before telemetry or command acquisition.""" + """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) diff --git a/src/regshape/cli/layout.py b/src/regshape/cli/layout.py index 5f088239..225b6e4b 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, @@ -772,6 +773,7 @@ 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) @@ -826,6 +828,8 @@ def push_cmd( 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. 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) diff --git a/src/regshape/tests/test_request_report_cli.py b/src/regshape/tests/test_request_report_cli.py index ab69c671..80bbaf85 100644 --- a/src/regshape/tests/test_request_report_cli.py +++ b/src/regshape/tests/test_request_report_cli.py @@ -489,6 +489,46 @@ def forbidden(*args, **kwargs): 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.""" From 63c0fd201356b8b69e4f71e15929923aaeed3171 Mon Sep 17 00:00:00 2001 From: Toddy Mladenov Date: Sat, 5 Dec 2026 08:18:17 -0800 Subject: [PATCH 08/12] fix: preserve layout report source and result flush diagnostics Address the remaining #276 review feedback with sanitized source metadata and distinct result-output failure reporting. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/library/telemetry.md | 6 ++- src/regshape/cli/layout.py | 7 ++- src/regshape/cli/request_report.py | 17 +++++- src/regshape/tests/test_request_report_cli.py | 54 +++++++++++++++++++ 4 files changed, 79 insertions(+), 5 deletions(-) diff --git a/docs/library/telemetry.md b/docs/library/telemetry.md index e3cd8f12..4db41e1c 100644 --- a/docs/library/telemetry.md +++ b/docs/library/telemetry.md @@ -99,7 +99,8 @@ diagnostics by default, including noninteractive invocations. 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. + 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 @@ -147,6 +148,9 @@ 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. 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. diff --git a/src/regshape/cli/layout.py b/src/regshape/cli/layout.py index 225b6e4b..1609a59d 100644 --- a/src/regshape/cli/layout.py +++ b/src/regshape/cli/layout.py @@ -827,7 +827,8 @@ def push_cmd( 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. The automatic report follows final output. + 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. """ @@ -846,7 +847,9 @@ def push_cmd( if tag_override: dest_display += f":{tag_override}" try: - with request_report_scope("layout push", "push", destination=dest_display), \ + 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) diff --git a/src/regshape/cli/request_report.py b/src/regshape/cli/request_report.py index 279b7d35..0b3b6a0a 100644 --- a/src/regshape/cli/request_report.py +++ b/src/regshape/cli/request_report.py @@ -246,6 +246,8 @@ def __exit__( 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. """ primary = exc translated: click.exceptions.Exit | None = None @@ -273,9 +275,20 @@ def __exit__( code = Failure.from_exception(exc, "operation").code click.echo(f"Error: Operation did not complete ({code}).", err=True) if exc is None: - sys.stdout.flush() + try: + sys.stdout.flush() + except BaseException as error: # noqa: BLE001 - retain result failure while delivering healthy reports. + failure = 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. - failure = error + 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) diff --git a/src/regshape/tests/test_request_report_cli.py b/src/regshape/tests/test_request_report_cli.py index 80bbaf85..01ea0c5c 100644 --- a/src/regshape/tests/test_request_report_cli.py +++ b/src/regshape/tests/test_request_report_cli.py @@ -29,6 +29,7 @@ ) 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 @@ -156,6 +157,8 @@ def export(image, output, **kwargs): 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" @@ -201,6 +204,7 @@ def forbidden(*args, **kwargs): 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 @@ -779,6 +783,56 @@ def append(path, mode): 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 + 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 + + 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") From 64f26a7cda868f22c890b644a3343c502cb975b7 Mon Sep 17 00:00:00 2001 From: Toddy Mladenov Date: Sat, 5 Dec 2026 08:32:13 -0800 Subject: [PATCH 09/12] fix: propagate shared result failures and guard stdout shutdown Address the remaining #276 sink-coordination review findings without retrying failed output destinations. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/library/telemetry.md | 5 +- src/regshape/cli/downloads.py | 56 ++++++++++--------- src/regshape/cli/request_report.py | 32 +++++++---- src/regshape/tests/test_request_report_cli.py | 22 ++++++-- 4 files changed, 71 insertions(+), 44 deletions(-) diff --git a/docs/library/telemetry.md b/docs/library/telemetry.md index 4db41e1c..f5dc2ea0 100644 --- a/docs/library/telemetry.md +++ b/docs/library/telemetry.md @@ -133,7 +133,9 @@ 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. +distinct standard-output/error descriptors that alias the same pipe. The report +coordinator also tracks result writes/flushes for commands without a warning +coordinator, so shared failed destinations receive no diagnostic retries. Reports follow settled library operations, progress and telemetry finalization, then command results/errors and deferred download warnings. Authentication, @@ -151,6 +153,7 @@ 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. 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. diff --git a/src/regshape/cli/downloads.py b/src/regshape/cli/downloads.py index cb68fcd8..508f3dcb 100644 --- a/src/regshape/cli/downloads.py +++ b/src/regshape/cli/downloads.py @@ -229,6 +229,32 @@ def close(self) -> None: """Never close or flush the borrowed sink, including during adapter 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)): @@ -282,32 +308,10 @@ def result_failed(self) -> None: 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, diff --git a/src/regshape/cli/request_report.py b/src/regshape/cli/request_report.py index 0b3b6a0a..6fa9d48b 100644 --- a/src/regshape/cli/request_report.py +++ b/src/regshape/cli/request_report.py @@ -1,7 +1,8 @@ """Render library request reports after command results, warnings and diagnostics. -The invocation adapter owns only diagnostic resources. Library operations choose -scope boundaries and supply every identity, count, timing and sanitized value. +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. """ @@ -16,7 +17,7 @@ import click -from regshape.cli.downloads import _DownloadOutput +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 @@ -186,21 +187,24 @@ def __init__(self) -> 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. - """Make this invocation the only activation target in the current context.""" + """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 = sys.stdout is self.stderr - if self.shared_stdout: - sys.stdout = self.output + 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) + sys.stdout = self.result_output sys.stderr = self.output try: _redirect_stderr_handlers( @@ -208,8 +212,7 @@ def __enter__(self) -> "_CommandReport": # noqa: PYI034 - Python 3.10, no typin ) except BaseException: sys.stderr = self.stderr - if self.shared_stdout: - sys.stdout = self.stderr + sys.stdout = self.stdout _restore_stderr_handlers(self.output, self.log_streams) _active.reset(self.token) raise @@ -248,12 +251,16 @@ def __exit__( 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 @@ -279,6 +286,8 @@ def __exit__( 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. " @@ -386,8 +395,9 @@ def __exit__( 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 self.shared_stdout and sys.stdout is self.output: - sys.stdout = _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: diff --git a/src/regshape/tests/test_request_report_cli.py b/src/regshape/tests/test_request_report_cli.py index 01ea0c5c..8c24f8d1 100644 --- a/src/regshape/tests/test_request_report_cli.py +++ b/src/regshape/tests/test_request_report_cli.py @@ -9,7 +9,7 @@ import os import sys from concurrent.futures import CancelledError -from contextlib import contextmanager +from contextlib import contextmanager, nullcontext import click import pytest @@ -631,8 +631,13 @@ def command(): assert "private-operation" not in result.stderr and "private-close" not in result.stderr -@pytest.mark.parametrize("boundary", ["write", "flush", "deferred_flush"]) -def test_aliased_result_failure_reaches_outer_report_scope(monkeypatch, tmp_path, boundary): +@pytest.mark.parametrize("boundary,warnings_enabled", [ + ("write", True), ("flush", True), ("deferred_flush", True), + ("write", False), ("flush", False), +]) +def test_aliased_result_failure_reaches_outer_report_scope( + monkeypatch, tmp_path, boundary, warnings_enabled, +): """Distinct wrappers/descriptors for one pipe must not retry a failed result destination.""" primary = BrokenPipeError("private-pipe") read_fd, output_fd = os.pipe() @@ -678,8 +683,8 @@ def flush(self): @click.command() @request_reporting def command(): - """Place result delivery outside telemetry, inside the ordinary warning coordinator.""" - with DownloadWarnings() as warnings: + """Place result delivery outside telemetry, with or without a warning coordinator.""" + with DownloadWarnings() if warnings_enabled else nullcontext() as warnings: @telemetry_options def operation(): """Complete a library scope before telemetry closes its owned log.""" @@ -689,6 +694,7 @@ def operation(): operation() try: if boundary == "deferred_flush": + assert warnings is not None warnings.observe(DownloadStatus( "blob", DIGEST, "fallback", "full", "etag_changed", None, 2, DownloadStats(), )) @@ -696,7 +702,8 @@ def operation(): else: click.echo("Published") except BaseException: - warnings.result_failed() + if warnings is not None: + warnings.result_failed() raise output, error = PipeSink(output_fd, result=True), PipeSink(error_fd) @@ -711,6 +718,8 @@ def operation(): ): 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 @@ -818,6 +827,7 @@ def command(): ): 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.") From 601673abc21f7c41978ea46fdb31fdee872adbc4 Mon Sep 17 00:00:00 2001 From: Toddy Mladenov Date: Sat, 5 Dec 2026 08:43:09 -0800 Subject: [PATCH 10/12] fix: preserve Click output encoding and binary buffer tracking Keep Unicode and binary CLI results compatible while sharing no-retry failure state across adapted buffers for #276. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/library/telemetry.md | 3 + src/regshape/cli/downloads.py | 63 ++++++++++++++ src/regshape/tests/test_request_report_cli.py | 85 +++++++++++++++++++ 3 files changed, 151 insertions(+) diff --git a/docs/library/telemetry.md b/docs/library/telemetry.md index f5dc2ea0..2859607b 100644 --- a/docs/library/telemetry.md +++ b/docs/library/telemetry.md @@ -154,6 +154,9 @@ 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. diff --git a/src/regshape/cli/downloads.py b/src/regshape/cli/downloads.py index 508f3dcb..e5c78d17 100644 --- a/src/regshape/cli/downloads.py +++ b/src/regshape/cli/downloads.py @@ -176,6 +176,7 @@ def __init__(self, stream: IO[str]) -> None: self.stream = stream self.failed = False self.failure: BaseException | None = None + self._buffer: _DownloadBinaryOutput | None = None def mark_failed(self, error: BaseException | None = None) -> None: """Share a known failed destination with outer proxies, retaining the first exact error.""" @@ -220,6 +221,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.""" @@ -229,6 +241,57 @@ 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 _verify_healthy(self) -> None: + """Reject known failures without I/O, including encoding-wrapper destructor flushes.""" + if self.owner.failed: + raise OSError("Output destination already failed") from self.owner.failure + + def write(self, data) -> int: + """Track encoded/binary result writes without weakening the original buffer's contract.""" + self._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._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. diff --git a/src/regshape/tests/test_request_report_cli.py b/src/regshape/tests/test_request_report_cli.py index 8c24f8d1..67a4e9f9 100644 --- a/src/regshape/tests/test_request_report_cli.py +++ b/src/regshape/tests/test_request_report_cli.py @@ -843,6 +843,91 @@ def command(): 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") From 0bf4039030f9222c6eab37f4a04f028c5546aa7d Mon Sep 17 00:00:00 2001 From: Toddy Mladenov Date: Sat, 5 Dec 2026 08:50:29 -0800 Subject: [PATCH 11/12] fix: share aliased output failures before telemetry finalization Prevent timed result failures from retrying a broken destination; preserve original errors and Click empty-probe behavior for #276. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/library/telemetry.md | 3 +- src/regshape/cli/downloads.py | 63 ++++++++++++++----- src/regshape/cli/request_report.py | 4 +- src/regshape/tests/test_request_report_cli.py | 48 ++++++++------ 4 files changed, 82 insertions(+), 36 deletions(-) diff --git a/docs/library/telemetry.md b/docs/library/telemetry.md index 2859607b..2dd12134 100644 --- a/docs/library/telemetry.md +++ b/docs/library/telemetry.md @@ -135,7 +135,8 @@ 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, so shared failed destinations receive no diagnostic retries. +coordinator. Aliased proxies share failure state immediately, so even scenario +telemetry emitted before the outer command exits cannot retry a failed destination. Reports follow settled library operations, progress and telemetry finalization, then command results/errors and deferred download warnings. Authentication, diff --git a/src/regshape/cli/downloads.py b/src/regshape/cli/downloads.py index e5c78d17..5d851362 100644 --- a/src/regshape/cli/downloads.py +++ b/src/regshape/cli/downloads.py @@ -163,21 +163,42 @@ 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 @@ -186,10 +207,24 @@ def mark_failed(self, error: BaseException | None = None) -> None: 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: @@ -198,6 +233,7 @@ def write(self, text: str) -> int: def flush(self) -> None: """Record flush failures without changing their exception identity.""" + self._verify_healthy() try: self.stream.flush() except BaseException as error: @@ -248,14 +284,11 @@ 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 _verify_healthy(self) -> None: - """Reject known failures without I/O, including encoding-wrapper destructor flushes.""" - if self.owner.failed: - raise OSError("Output destination already failed") from self.owner.failure - def write(self, data) -> int: - """Track encoded/binary result writes without weakening the original buffer's contract.""" - self._verify_healthy() + """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: @@ -264,7 +297,7 @@ def write(self, data) -> int: def flush(self) -> None: """Track encoding-wrapper flush failures and never retry a known failed buffer.""" - self._verify_healthy() + self.owner._verify_healthy() try: self.stream.flush() except BaseException as error: diff --git a/src/regshape/cli/request_report.py b/src/regshape/cli/request_report.py index 6fa9d48b..b0e78bfa 100644 --- a/src/regshape/cli/request_report.py +++ b/src/regshape/cli/request_report.py @@ -203,7 +203,9 @@ def __enter__(self) -> "_CommandReport": # noqa: PYI034 - Python 3.10, no typin 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) + 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: diff --git a/src/regshape/tests/test_request_report_cli.py b/src/regshape/tests/test_request_report_cli.py index 67a4e9f9..982fcc76 100644 --- a/src/regshape/tests/test_request_report_cli.py +++ b/src/regshape/tests/test_request_report_cli.py @@ -25,6 +25,7 @@ configure_telemetry, get_telemetry_config, request_report_scope, + track_scenario, track_time, ) from regshape.libs.decorators._request_report_store import ReportStore @@ -631,12 +632,13 @@ def command(): assert "private-operation" not in result.stderr and "private-close" not in result.stderr -@pytest.mark.parametrize("boundary,warnings_enabled", [ - ("write", True), ("flush", True), ("deferred_flush", True), - ("write", False), ("flush", False), +@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, + 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") @@ -685,26 +687,34 @@ def flush(self): 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(): - """Complete a library scope before telemetry closes its owned log.""" + """Optionally deliver inside a timed scenario before telemetry log finalization.""" with request_report_scope("test", "pull"): pass + if timed_scenario: + deliver_result() - operation() - 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 + 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" From a14c9c69547a47afdfb63319897c4aac6cba83f5 Mon Sep 17 00:00:00 2001 From: Toddy Mladenov Date: Sat, 5 Dec 2026 09:02:16 -0800 Subject: [PATCH 12/12] test(cli): enforce artifact progress failed-sink contract Keep failed/cancelled row assertions for healthy terminals and verify no destination writes or flushes after a terminal failure. Preserve error identity, borrowed streams and resource cleanup. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/library/telemetry.md | 3 +++ src/regshape/tests/test_artifact_pull_cli.py | 17 ++++++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/library/telemetry.md b/docs/library/telemetry.md index 2dd12134..fd6e02bc 100644 --- a/docs/library/telemetry.md +++ b/docs/library/telemetry.md @@ -137,6 +137,9 @@ 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, diff --git a/src/regshape/tests/test_artifact_pull_cli.py b/src/regshape/tests/test_artifact_pull_cli.py index 6ab3f18b..c2790a8d 100644 --- a/src/regshape/tests/test_artifact_pull_cli.py +++ b/src/regshape/tests/test_artifact_pull_cli.py @@ -805,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.""" @@ -824,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)