Skip to content

fix(k8s): pod logs reach callers as whole lines, with and without --follow #864

Closed

Description

@dan-petty

Problem

KubernetesService.read_pod_logs (src/devops_cli/k8s/service.py:272-302) returns the whole log as a str when follow=False, and a PodLogStream when follow=True (line 298). PodLogStream.__iter__ (service.py:37-43) yields each urllib3 chunk as it arrives and decodes each chunk on its own (line 40). Neither mode yields lines. The three callers each go wrong in a different way. Every case below was reproduced on the release/v0.2.25 tip (9c879ae) with mocked responses.

  1. devops argo workflows logs prints one character per line by default. --follow is off by default (src/devops_cli/commands/argo.py:440). The loop at argo.py:454-455 iterates whatever read_pod_logs returns. On a str, that walks the characters. It writes each one with a newline added, and writes each \n as a blank line. For a log of "a\nb\n", the output after the pod header is "a\n\nb\n\n". The loop dates from cb75261 (v0.2.22).

  2. Followed output splits lines at chunk boundaries. A chunk can hold several lines or end mid-line. Chunks b"a\nb" and b"c\n" come out of read_pod_logs(follow=True) as ["a\nb", "c\n"]. argo.py:455 then adds a newline after b, so the line bc prints as two lines. write_stdout masks secrets on each write (src/devops_cli/output/console.py:119-136), so mask_secrets never sees a token that is split across two chunks as a whole.

  3. A multi-byte character split across two chunks ends the stream. Chunks b"caf\xc3" and b"\xa9\n" raise UnicodeDecodeError at service.py:40. Each caller then fails differently:

    • the dashboard pane shows stream ended: UnicodeDecodeError (src/devops_cli/ui/widgets.py:756-758);
    • devops k8s logs --follow falls back to kubectl logs --follow (src/devops_cli/commands/k8s/cluster_context.py:335-344), which prints the tail a second time.
  4. Logs read without follow can come back as Python reprs. Without follow, read_pod_logs sets _preload_content=True (service.py:291). kubernetes 36.0.3 then runs the body through json.loads before it calls str() (kubernetes/client/api_client.py:280-285, 611-624). So a log that is a single JSON document comes back as a Python repr:

    • {"level": "info", "msg": "up"}\n comes back as {'level': 'info', 'msg': 'up'};
    • true\n comes back as True.

    --tail 1 on any pod that logs JSON hits this.

  5. The dashboard log pane stores each chunk as one line. PodLogSource (src/devops_cli/ui/refresh.py:105-145) passes the stream to LogPane._produce (widgets.py:742). _append (widgets.py:788-794) adds each item as a single VirtualLogBuffer entry (src/devops_cli/ui/log_buffer.py:56). A chunk that holds several lines becomes one entry with embedded newlines, so the status count, viewport and scrolling all treat it as one line. A line split across two chunks becomes two entries. refresh.py:132-133 handles a str with splitlines(). That method also splits on \x0c, \x1c-\x1e, \x85 and \u2028.

  6. devops k8s logs <pod> is a caller the original body missed. Its native path (cluster_context.py:319-336) prints with the console print at level raw. That print takes **kwargs (console.py:172) but never passes them to Console.print on the raw path (console.py:299-302), so end="" is dropped. It also passes log text through as Rich markup, because safe is off. With mocked logs:

    • followed chunks "a\nb" and "c\n" print as "a\nb\nc\n\n", which splits bc and adds a blank line;
    • without follow, an extra blank line follows the log;
    • a line longer than the console is hard-wrapped (at 80 columns when stdout is not a terminal);
    • a line containing [/bold] raises MarkupError. except Exception: pass (cluster_context.py:335-336) swallows it, and the read runs again through kubectl logs.

    This caller has to change once read_pod_logs yields lines anyway, because print(str(log_output)) (line 333) assumes a str.

No test reaches the argo log loop. tests/test_argo.py:226-229 passes --follow. #961 added tests/test_argo.py:286-328, which runs without it. But both tests mock a workflow with "nodes": {} (test_argo.py:192, 297), so workflow_pod_names returns no pods and the loop never runs. Two other sets of tests pin the current behaviour:

  • tests/test_k8s_service.py:153-165 and 307-323 assert the str return and the raw chunks;
  • tests/test_ui_reactive.py:1775-1853 replaces KubernetesService with fakes that already yield lines, so no test exercises the framing.

Since this was filed on 2026-10-01, only the line numbers have moved. read_pod_logs moved from 278 to 272. The argo loop moved from 458 to 454 after #961 removed _crd. #961 changed only how the argo commands choose a namespace, and the defect is unchanged.

Acceptance criteria

  • read_pod_logs returns a PodLogStream in both modes. Iterating it yields complete lines without their trailing newline. Both modes read the response unpreloaded (_preload_content=False) through one decode-and-split path. Pre-1.0, there is no shim: the str return goes, and so do the isinstance(..., str) branches at refresh.py:132-133 and cluster_context.py:329.
  • Offline unit tests in tests/test_k8s_service.py with a mocked CoreV1Api response:
    • followed chunks b"a\nb" and b"c\n" yield ["a", "bc"];
    • chunks b"a\n" and b"tail" yield ["a", "tail"], so a final partial line is flushed when the stream ends;
    • chunks b"caf\xc3" and b"\xa9\n" yield ["café"];
    • chunk b"\xff\nok\n" yields ["\ufffd", "ok"], and the stream does not end;
    • a chunk with no newline that is longer than the line cap yields a line of exactly the cap's length, and the rest follows as the next line;
    • "a\x0cb\n" yields one line, because only \n ends a line;
    • without follow, a body of b'{"level": "info"}\n' yields ['{"level": "info"}'], and the call passes follow=False and _preload_content=False.
  • The two close() tests (test_k8s_service.py:350-392) still pass with ["first"] and ["only"] in place of "first\n" and "only\n". A read blocked on a quiet container still ends when close() is called from another thread, and the response is still closed and its connection released. This is the behaviour feat(k8s): truthful pod status, filters, container-aware logs and pod inspector in the dashboard (tab-k8s) #686 added.
  • devops argo workflows logs my-wf: the test's workflow has one Pod node, so the loop runs, and the service is mocked.
    • Without --follow, a log of "a\nb\n" prints exactly a\nb\n after the pod header.
    • With --follow, chunks "a\nb" and "c\n" print exactly a\nbc\n.
  • devops k8s logs pod-1, with and without --follow, writes each line through write_stdout (no Rich markup or wrapping, secrets masked) with exactly one newline after it.
    • Chunks "a\nb" and "c\n" print a\nbc\n.
    • A line containing [/bold] prints literally.
    • A 200-character line prints unwrapped.
    • No case calls the kubectl fallback (run_subprocess and _run_cmd patched and asserted not called).
  • Dashboard: a LogPane that streams pod_log_source("web-0", "shop") reads a mocked CoreV1Api response whose chunks are b"a\nb" and b"c\nd\n". Its buffer ends with the entries ["a", "bc", "d"]. The test for the removed str branch (test_ui_reactive.py:1800-1815) goes.
  • Tests never touch the network or a cluster. uv run devops ci passes. changelog.d/864.md has a ### Fixed entry.
  • Person-run check, not in CI: on the workstation k3s cluster, pick a pod that has stopped writing, such as a Completed job pod.
    • diff <(uv run devops k8s logs <pod> -n <ns> --tail 50) <(kubectl logs <pod> -n <ns> --tail=50) prints nothing.
    • In uv run devops dashboard, opening that pod's logs shows the same lines as kubectl logs <pod> -n <ns> --tail=100 (the pane's tail is DEFAULT_LOG_TAIL_LINES, 100), one row per line, and the status line reads N retained of N where N is that line count.

Key questions

  • Should lines keep their trailing newline? Proposed: no. Yield them without it, and have each writer add exactly one. The pane's rstrip("\n") (widgets.py:793) then has nothing to do, and can stay or go.
  • What does read_pod_logs return? Proposed: a PodLogStream in both modes. Reading both modes unpreloaded removes the json.loads repr defect (item 4), gives both modes one decoder and one splitter, and lets close() work on a long non-follow read as well. Callers lose their str branches.
  • What ends a line? Proposed: \n only, as the API and kubectl logs do. A trailing \r stays in the line, as kubectl prints it. str.splitlines() is not used, because it also splits on form feeds, \x1c-\x1e, \x85 and \u2028.
  • How are bytes decoded? Proposed: a codecs incremental UTF-8 decoder with errors="replace", kept across chunks. A split character then decodes whole, and an invalid byte becomes U+FFFD instead of ending the stream.
  • Is a line's length bounded? Proposed: yes. Buffering adds a new memory risk: a container that writes without newlines, such as a \r progress bar or binary output, would grow the pending text without limit. A pending line that reaches a new DEFAULT_LOG_MAX_LINE_CHARS (65536, in src/devops_cli/config/defaults.py) is yielded as a line, and reading continues.
  • Is a partial line flushed when the stream ends? Proposed: yes, whenever iteration ends without an exception, which includes an end of stream after close(). When the read raises, the exception propagates as it does today, and the partial line is dropped.
  • Does the devops k8s logs writer change here or in fix(cli): docker and sandbox output render remote text as rich markup #955? Proposed: here. This item has to rewrite those lines (cluster_context.py:329-333) for the new return type. The fix is the same write_stdout that argo already uses. fix(cli): docker and sandbox output render remote text as rich markup #955 covers only docker and sandbox output.
  • Does the kubectl fallback in devops k8s logs (cluster_context.py:335-346) change? Proposed: no, it is out of scope. Once the lines are framed and written raw, a markup or decode error no longer triggers it.
  • Does this item make devops argo workflows logs work against a real Argo install? No. That needs a separate item, so the argo criteria above use mocks. Two problems stop the command before it reaches these lines:
    • workflow_pod_names (src/devops_cli/argo/crd.py:286-296) returns node IDs. Argo's default pod naming since v3.4 (POD_NAMES=v2) is <workflow>-<template>-<hash>, so a node ID is not a pod name and the read returns 404.
    • Argo pods run wait and main containers, and argo.py:454 names no container, so the API server answers 400.

Order

Milestone v0.2.29 (P1, due before v0.3.0).

Depends on: #686 (closed in v0.2.24), which added PodLogStream and its close(). No open item in v0.2.25 to v0.2.29 changes service.py:25-302, argo.py:435-455, refresh.py:105-145, widgets.py:724-794 or cluster_context.py:289-346, so this item can land at any point in v0.2.29.

Related: #955 (v0.2.25, the same Rich-markup defect in docker and sandbox output), #548 (v0.2.26, the Loki path of devops k8s logs, cluster_context.py:254-286), #961 (closed, added the argo test that does not reach the loop). If the argo pod-name and container defect is filed, it lands after this item, because both change argo.py:450-455.

Update 2026-10-08: amended criteria (assessed against release/v0.2.29, 910b823)

The Problem claims hold, and the core defects were reproduced offline with kubernetes 36.0.3 and urllib3 2.8.0. Four points change the criteria.

  1. write_stdout is not a raw writer. console.py:130-143 still prints through a Rich Console. That strips \r, BEL, BS, VT and FF, and turns :shortcode: text into emoji, so the key question's "\r stays in the line, as kubectl prints it" is false at the CLI.
    • The person-run diff against kubectl logs uses a pod whose log has no control characters and no :shortcode: text. Alternatively the log writers stop rewriting those; if so, the task file says which was chosen.
  2. The default mode gets a new failure path. A non-follow read used to be preloaded inside read_pod_logs, so a body error fell back to kubectl before anything was printed. Now the body is read inside the write loop. _execute_legacy_kubectl_logs (cluster_context.py:319-346) wraps both the read and the loop in except Exception: pass and then reruns kubectl logs, which would print the tail twice.
    • Only a failure to open the native read falls back to kubectl. An error after lines have been written is raised with its message: no swallowed error and no duplicate output. A test covers a mid-body error in non-follow mode.
  3. The line cap must not depend on chunk boundaries. "Reaches the cap" yields a spurious empty line when a line of exactly the cap's length has its \n in the next chunk.
    • Pending text is cut only when it is longer than DEFAULT_LOG_MAX_LINE_CHARS. A test case [b"x" * cap, b"\n"] yields exactly one line.
  4. Libraries first. io.TextIOWrapper(resp, encoding="utf-8", errors="replace", newline="\n").readline(cap) is the stdlib way to frame lines from a streaming response.
    • Use it, unless the close() criterion cannot hold with it. That would be because urllib3's read1 path differs from read_chunked on shutdown. If so, the task file records why the small framer was kept, with that evidence rather than mock fixtures.

Smaller corrections:

  • Remove # noqa: C901 from _execute_legacy_kubectl_logs. Its complexity measures exactly 10 after the change, and RUF100 is selected. write_stdout is already imported in cluster_context.py.
  • With real urllib3, shutdown(SHUT_RD) during a followed chunked read ends in ProtocolError("Response ended prematurely"). So a real close() drops a partial last line. Don't describe flushing after close() as product behaviour; it holds only for the mocks.
  • Per-line masking fixes tokens split across chunks, but it can no longer match the multi-line private-key pattern (sanitizer.py:229-233) that a single-chunk write could match in argo --follow. Note this in the risk list. devops k8s logs was not masked at all before, so it still gains.
  • Citations that moved: widgets.py _produce is at :778, the "stream ended" message at :810-812, and _append/rstrip at :842-847. In console.py, write_stream is at :130-143, print's **kwargs at :175, and the raw path at :304-305.
  • fix(cli): devops argo workflows logs finds no pod and names no container on a real argo install #988 (backlog) will later change the argo fixture that treats a workflow node id as a pod name, and argo.py:450-455.

Out of scope here (noted for a later item):

  • k8s/doctor.py:605 reads pod logs with preload and has the same JSON-repr defect with --tail 1. It also swallows errors with except Exception: pass.

Activity

  1. added
    type/bug
    scope/k8s
    priority/p2-medium
    on Oct 1, 2026
  2. added
    priority/p1-high
    and removed
    priority/p2-medium
    on Oct 2, 2026
  3. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    Grooming (2026-10-02): Priority p2-medium → p1-high. In its default mode (no --follow), devops argo workflows logs prints every character on its own line, which leaves the command unusable. Policy makes a broken command at least P1.

    Checked against the code at the release/v0.2.25 tip.

  4. added this to the v0.2.29 milestone on Oct 2, 2026
  5. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    Placed in v0.2.29 on 2026-10-02. v0.2.29 holds P1 work that has to land before v0.3.0, which v0.2.25 to v0.2.28 had no room for. Backlog P1 items were ranked by Value, then Effort, with defects and security fixes first at a tie. This item ranked in the top ten, and two of the release's twelve slots stay open for P1 items that surface before then.

  6. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    Refined to Ready on 2026-10-02 for v0.2.29. The body was checked claim by claim against release/v0.2.25 at 9c879ae, and a second agent then tried to refute it; every major objection was resolved in a revision. Cited lines were updated for code that moved, and the scope was corrected where merged work changed it. Acceptance criteria were tightened so each fails on the current code, and every key question now has a proposed answer.

  7. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    The acceptance criteria were amended on 2026-10-08 (see "Update 2026-10-08" at the end of the body). The changes: write_stdout is not raw, an error partway through the default mode must not print the tail twice, the line cap must not depend on chunk boundaries, and a stdlib io.TextIOWrapper should be tried before the hand-rolled framer.

  8. dan-petty-bot commented on Oct 8, 2026

    @dan-petty-bot
    Collaborator

    What changed

    #1408, merged into release/v0.2.29 as 01c5022.

    Resolves #864

    10 file(s) changed.

    How it was verified

    Check runs at 84e682b:

    • Prune PR DevContainer Images: pass
    • CodeQL: pass
    • Static Analysis: pass
    • Analyze (actions): pass
    • Analyze (python): pass
    • Tests & Coverage: pass
    • DevContainer Image: skipping
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-864-stream-framing-pod-logs.md:

    • read_pod_logs returns a PodLogStream in both modes. Iterating it yields complete lines without their trailing newline. Both modes read the response unpreloaded (_preload_content=False) through one decode-and-split path. Pre-1.0, there is no shim: the str return goes, and so do the isinstance(..., str) branches at refresh.py:132-133 and cluster_context.py:329.
    • Offline unit tests in tests/test_k8s_service.py with a mocked CoreV1Api response:
      • followed chunks b"a\nb" and b"c\n" yield ["a", "bc"];
      • chunks b"a\n" and b"tail" yield ["a", "tail"], so a final partial line is flushed when the stream ends;
      • chunks b"caf\xc3" and b"\xa9\n" yield ["café"];
      • chunk b"\xff\nok\n" yields ["\ufffd", "ok"], and the stream does not end;
      • a chunk with no newline that is longer than the line cap yields a line of exactly the cap's length, and the rest follows as the next line;
      • pending text is cut only when it is longer than DEFAULT_LOG_MAX_LINE_CHARS: a test case [b"x" * cap, b"\n"] yields exactly one line;
      • "a\x0cb\n" yields one line, because only \n ends a line;
      • without follow, a body of b'{"level": "info"}\n' yields ['{"level": "info"}'], and the call passes follow=False and _preload_content=False.
    • The two close() tests (test_k8s_service.py:350-392) still pass with ["first"] and ["only"] in place of "first\n" and "only\n". A read blocked on a quiet container still ends when close() is called from another thread, and the response is still closed and its connection released.
    • devops argo workflows logs my-wf: the test's workflow has one Pod node, so the loop runs, and the service is mocked.
      • Without --follow, a log of "a\nb\n" prints exactly a\nb\n after the pod header.
      • With --follow, chunks "a\nb" and "c\n" print exactly a\nbc\n.
    • devops k8s logs pod-1, with and without --follow, writes each line through write_stdout (no Rich markup or wrapping, secrets masked) with exactly one newline after it.
      • Chunks "a\nb" and "c\n" print a\nbc\n.
      • A line containing [/bold] prints literally.
      • A 200-character line prints unwrapped.
      • No case calls the kubectl fallback (run_subprocess and _run_cmd patched and asserted not called).
      • Only a failure to open the native read falls back to kubectl. An error after lines have been written is raised with its message: no swallowed error and no duplicate output. A test covers a mid-body error in non-follow mode.
    • Dashboard: a LogPane that streams pod_log_source("web-0", "shop") reads a mocked CoreV1Api response whose chunks are b"a\nb" and b"c\nd\n". Its buffer ends with the entries ["a", "bc", "d"]. The test for the removed str branch (test_ui_reactive.py:1800-1815) goes.
    • Tests never touch the network or a cluster. uv run devops ci passes. changelog.d/864.md has a ### Fixed entry.
    • Pending a person: on the workstation k3s cluster, pick a pod that has stopped writing, such as a Completed job pod (with no control characters or :shortcode: text).
      • diff <(uv run devops k8s logs <pod> -n <ns> --tail 50) <(kubectl logs <pod> -n <ns> --tail=50) prints nothing.
      • In uv run devops dashboard, opening that pod's logs shows the same lines as kubectl logs <pod> -n <ns> --tail=100 (the pane's tail is DEFAULT_LOG_TAIL_LINES, 100), one row per line, and the status line reads N retained of N where N is that line count.
  9. added a commit that references this issue on Oct 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p1-highscope/k8stype/bug

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions