Skip to content

decode partial stdout/stderr in run_path TimeoutExpired branch#64

Open
HrachShah wants to merge 1 commit into
microsoft:mainfrom
HrachShah:fix/run-path-timeout-bytes-decoding
Open

decode partial stdout/stderr in run_path TimeoutExpired branch#64
HrachShah wants to merge 1 commit into
microsoft:mainfrom
HrachShah:fix/run-path-timeout-bytes-decoding

Conversation

@HrachShah

Copy link
Copy Markdown

What

run_path (the no-use_stdin branch) returns a RunResult whose stdout/stderr were bytes instead of str whenever the subprocess timed out.

Why

subprocess.run(..., encoding="utf-8") decodes bytes from the pipe to str on the normal completion path, but subprocess.TimeoutExpired.stdout / .stderr still carry the raw bytes the OS delivered before the kill. The previous code forwarded those bytes straight into RunResult(e.stdout or "", e.stderr or "", None), so:

  • on success: result.stdout is str (whatever the subprocess printed).
  • on timeout: result.stdout is bytes (whatever was buffered before kill).

Any caller that did result.stdout + "\n" or f"tool said: {result.stdout}" would work fine on success and TypeError: can only concatenate str (not "bytes") to str on timeout — exactly the case where you most want the partial output to surface to the user.

This is most visible when a formatter / linter is slow on a large file, hits the LSP-side FORMATTING_TIMEOUT, and the caller wants to surface the partial stderr ("black: would reformat ..."). Today you get b"black: would reformat ...\n".

Fix

Decode e.stdout and e.stderr using the same encoding that was passed to subprocess.run, with errors="replace" so a malformed UTF-8 partial byte at the cut-off point doesn't raise. The decode mirrors the encoding on the happy path so the result is uniformly typed.

Added a test (test_timeout_returns_str_stdout_stderr) that asserts the result is str after a forced timeout with partial output. The test fails on the pre-fix code with the exact TypeError callers would see at runtime.

Repro

import subprocess
try:
    subprocess.run(["python3", "-u", "-c", "import time; print('partial'); time.sleep(5)"],
                   encoding="utf-8", capture_output=True, timeout=1)
except subprocess.TimeoutExpired as e:
    print(type(e.stdout), repr(e.stdout))  # <class 'bytes'> b'partial\n'

Test

cd python
pip install -e .
pip install pytest
python -m pytest tests/test_runner.py -v
# 18 passed

When a subprocess call exceeds its timeout, subprocess.run returns a
TimeoutExpired exception whose stdout/stderr attributes hold the raw
bytes the OS had already delivered to the pipe before the kill — even
when the call itself was configured with encoding='utf-8' for a
uniform str return on the normal completion path. The previous
implementation just forwarded those bytes straight into the RunResult,
so the result's stdout was bytes and stderr was str (or vice-versa)
on timeout, depending on which stream had buffered output.

A caller that did 'result.stdout + other_str' would get TypeError on
timeout only; on success the same code worked. The decode here matches
the encoding passed to subprocess.run so the result is uniformly typed
regardless of whether the subprocess finished cleanly or was killed by
the timeout.

Adds a test that runs a long-running script with a short timeout,
captures partial stdout, and asserts RunResult.stdout is a str.
@microsoft-github-policy-service

Copy link
Copy Markdown

@HrachShah please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

# normal completion path, but TimeoutExpired still carries the
# raw bytes captured from the pipe before decoding — produce
# str here so RunResult is uniformly typed.
partial_out = e.stdout.decode("utf-8", errors="replace") if e.stdout else ""

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📍 python/vscode_common_python_lsp/runner.py:139
Critical, platform-asymmetric regression: this fix crashes on Windows. The Skeptic, Architect, and Advocate all verified by execution on Windows/CPython 3.14 that TimeoutExpired.stdout/.stderr are already str there — CPython's subprocess.run calls process.communicate() after kill on _mswindows, which decodes because encoding="utf-8" is set. So .decode(...) raises AttributeError: 'str' object has no attribute 'decode' whenever there is partial output (the exact case this PR targets). The if e.stdout guard only covers the empty case. Pre-fix Windows behavior was already correct str; this makes it worse. Decode defensively instead, e.g. def _as_str(v): return "" if not v else (v.decode("utf-8", errors="replace") if isinstance(v, bytes) else v) then RunResult(_as_str(e.stdout), _as_str(e.stderr), None). The POSIX half (errors="replace" for a multibyte char severed at the kill boundary) is sound and should be preserved.

[verified]

assert isinstance(result.stdout, str)
assert isinstance(result.stderr, str)
assert "partial line" in result.stdout

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📍 python/tests/test_runner.py:73
This test only exercises the POSIX path and will itself AttributeError on Windows (where TimeoutExpired.stdout is already str), so a POSIX-only CI gives false confidence about the platform the current patch breaks. Add coverage that injects a fake TimeoutExpired carrying str output (Windows reality) in addition to bytes (POSIX), so both legs of the normalization are pinned. Separately, the genuinely subtle errors="replace" choice for a multibyte sequence truncated at the kill boundary has no test — consider emitting an incomplete multi-byte sequence before the kill to lock in that behavior.

[verified]

# stdout/stderr must be str, not bytes, regardless of whether
# the subprocess had produced any output before being killed
assert isinstance(result.stdout, str)
assert isinstance(result.stderr, str)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📍 python/tests/test_runner.py:94
Review-rule violation (tests-no-partial-asserts). The subprocess output is deterministic (print('partial line') with -u yields exactly "partial line\n", and universal-newline translation normalizes any \r\n), and none of the rule's non-determinism exceptions (timestamps, random IDs, PIDs) apply. Replace assert "partial line" in result.stdout with assert result.stdout == "partial line\n" for an exact assertion.

[verified]

# normal completion path, but TimeoutExpired still carries the
# raw bytes captured from the pipe before decoding — produce
# str here so RunResult is uniformly typed.
partial_out = e.stdout.decode("utf-8", errors="replace") if e.stdout else ""

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📍 python/vscode_common_python_lsp/runner.py:135
The comment says "same encoding that was passed to subprocess.run," but the decode hardcodes the "utf-8" literal independently from the encoding="utf-8" argument three lines up — the two would silently desync if either changes or if run_path ever gains an encoding parameter. Prefer deriving the decode encoding from a single source. Also consider applying the same normalization to the use_stdin=True Popen timeout branch so both timeout paths share one rule.

[verified]

@rchiodo

rchiodo commented Jun 22, 2026

Copy link
Copy Markdown

Solid catch on the POSIX bytes/str inconsistency, and the test is a good repro. The blocker is that the fix unconditionally calls .decode() on TimeoutExpired output, which crashes on Windows where that output is already str. Normalize defensively (isinstance check or only-decode-if-bytes) and add coverage for the str path before merge.

@rchiodo

rchiodo commented Jun 30, 2026

Copy link
Copy Markdown

🔒 Automated review in progress — @rchiodo is auto-reviewing this PR via the Review Center.

Other automated reviewers defer to this claim to avoid duplicate, conflicting feedback. The claim is refreshed while the review is active; if it is not refreshed within the ownership timeout it is treated as vacant and another reviewer may take over. This is an automated marker.

# str here so RunResult is uniformly typed.
partial_out = e.stdout.decode("utf-8", errors="replace") if e.stdout else ""
partial_err = e.stderr.decode("utf-8", errors="replace") if e.stderr else ""
return RunResult(partial_out, partial_err, None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📍 python/vscode_common_python_lsp/runner.py:136
The unconditional e.stdout.decode(...) assumes TimeoutExpired always carries bytes, but that is only true on POSIX. The Advocate, Skeptic, and Architect each independently verified (live, Python 3.14.3 / Windows) that subprocess.run(encoding="utf-8") populates TimeoutExpired.stdout as str on Windows, so this branch raises AttributeError: 'str' object has no attribute 'decode' — an uncaught crash thrown from inside run_path on every timeout, strictly worse than the bytes it replaced (which only blew up downstream and only for some callers). Make the conversion type-defensive, e.g. a helper def _as_text(v): return "" if not v else (v if isinstance(v, str) else v.decode("utf-8", errors="replace")) applied to both fields. The errors="replace" guard against a truncated multibyte sequence is correct and should be kept inside that helper.

[verified]

# the subprocess had produced any output before being killed
assert isinstance(result.stdout, str)
assert isinstance(result.stderr, str)
assert "partial line" in result.stdout

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📍 python/tests/test_runner.py:73
This test encodes the same false invariant as the fix: on Windows/newer CPython TimeoutExpired.stdout is already str, so the fixed code raises AttributeError before any assertion runs, making the test error (not pass) on Windows CI — the author's "18 passed" is POSIX-only. Make it platform/version-agnostic so it asserts the str contract on both the bytes-carrying (POSIX) and str-carrying (Windows) timeout behaviors, e.g. via monkeypatch/parametrize that forces e.stdout to each type.

[verified]

# str here so RunResult is uniformly typed.
partial_out = e.stdout.decode("utf-8", errors="replace") if e.stdout else ""
partial_err = e.stderr.decode("utf-8", errors="replace") if e.stderr else ""
return RunResult(partial_out, partial_err, None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📍 python/vscode_common_python_lsp/runner.py:136
The Skeptic and Architect both observe the sibling use_stdin=True timeout path already yields uniform str by doing process.kill(); process.communicate() (which decodes in text mode). Mirroring that proven kill-then-communicate pattern here would have produced str on all platforms and avoided this bug entirely; worth considering instead of decoding the exception attribute, to keep the two branches consistent.

[verified]

@rchiodo

rchiodo commented Jun 30, 2026

Copy link
Copy Markdown

Good catch on the bytes-vs-str timeout bug, but the decode is only correct on POSIX. On Windows subprocess.run already returns str in the TimeoutExpired attributes, so .decode() will crash. Make the conversion type-defensive (or mirror the kill-then-communicate pattern used in the use_stdin=True branch) and ensure the test exercises both platforms.

@rchiodo

rchiodo commented Jun 30, 2026

Copy link
Copy Markdown

🔒 Automated review in progress — @rchiodo is auto-reviewing this PR via the Review Center.

Other automated reviewers defer to this claim to avoid duplicate, conflicting feedback. The claim is refreshed while the review is active; if it is not refreshed within the ownership timeout it is treated as vacant and another reviewer may take over. This is an automated marker.

# stdout/stderr must be str, not bytes, regardless of whether
# the subprocess had produced any output before being killed
assert isinstance(result.stdout, str)
assert isinstance(result.stderr, str)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📍 python/tests/test_runner.py:92
Confirmed violation of review rule tests-no-partial-asserts.md: assert "partial line" in result.stdout is a banned substring check. The output is fully deterministic (print('partial line') always yields "partial line\n"), so an exact assertion is achievable and required: assert result.stdout == "partial line\n". Per the non-downgradeable rule gate this stays issue — the only way to waive it is to amend the rule doc, not this PR.

[verified]

@rchiodo

rchiodo commented Jul 1, 2026

Copy link
Copy Markdown

The core fix is directionally right (RunResult should be uniformly typed), but the unconditional .decode() breaks on Windows, where subprocess.run(encoding=...) already populates TimeoutExpired.stdout/.stderr as str. Make the conversion type-defensive (only decode when the value is bytes) and the accompanying test platform-agnostic before merging.

@rchiodo

rchiodo commented Jul 2, 2026

Copy link
Copy Markdown

🔒 Automated review in progress — @rchiodo is auto-reviewing this PR.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants